socket 0.14.48 → 0.14.49

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.
@@ -54,8 +54,8 @@ var index_cjs = require('@socketregistry/hyrious__bun.lockb/index.cjs');
54
54
  var sorts = require('@socketsecurity/registry/lib/sorts');
55
55
  var strings = require('@socketsecurity/registry/lib/strings');
56
56
  var yaml = _socketInterop(require('yaml'));
57
- var npm$1 = require('./npm.js');
58
57
  var npmPaths = require('./npm-paths.js');
58
+ var npm$1 = require('./npm.js');
59
59
  var betterAjvErrors = _socketInterop(require('@apideck/better-ajv-errors'));
60
60
  var config$A = require('@socketsecurity/config');
61
61
  var readline = require('node:readline/promises');
@@ -1285,6 +1285,51 @@ async function runAction(githubEventBefore, githubEventAfter) {
1285
1285
  }
1286
1286
  }
1287
1287
 
1288
+ const {
1289
+ API_V0_URL
1290
+ } = constants;
1291
+ function handleUnsuccessfulApiResponse(_name, result, spinner) {
1292
+ // SocketSdkErrorType['error'] is not typed.
1293
+ const resultErrorMessage = result.error?.message;
1294
+ const message = typeof resultErrorMessage === 'string' ? resultErrorMessage : 'No error message returned';
1295
+ if (result.status === 401 || result.status === 403) {
1296
+ spinner.stop();
1297
+ throw new index.AuthError(message);
1298
+ }
1299
+ spinner.error(`${colors.bgRed(colors.white('API returned an error:'))} ${message}`);
1300
+ process$1.exit(1);
1301
+ }
1302
+ async function handleApiCall(value, description) {
1303
+ let result;
1304
+ try {
1305
+ result = await value;
1306
+ } catch (cause) {
1307
+ throw new Error(`Failed ${description}`, {
1308
+ cause
1309
+ });
1310
+ }
1311
+ return result;
1312
+ }
1313
+ async function handleAPIError(code) {
1314
+ if (code === 400) {
1315
+ return 'One of the options passed might be incorrect.';
1316
+ } else if (code === 403) {
1317
+ return 'You might be trying to access an organization that is not linked to the API key you are logged in with.';
1318
+ }
1319
+ }
1320
+ function getLastFiveOfApiToken(token) {
1321
+ // Get the last 5 characters of the API token before the trailing "_api".
1322
+ return token.slice(-9, -4);
1323
+ }
1324
+ async function queryAPI(path, apiToken) {
1325
+ return await fetch(`${API_V0_URL}/${path}`, {
1326
+ method: 'GET',
1327
+ headers: {
1328
+ Authorization: `Basic ${btoa(`${apiToken}:${apiToken}`)}`
1329
+ }
1330
+ });
1331
+ }
1332
+
1288
1333
  function getFlagListOutput(list, indent, {
1289
1334
  keyPrefix = '--',
1290
1335
  padName
@@ -1452,6 +1497,7 @@ function meowOrExit({
1452
1497
  if (constants.ENV[SOCKET_CLI_SHOW_BANNER]) {
1453
1498
  console.log(getAsciiHeader(command));
1454
1499
  }
1500
+
1455
1501
  // This exits if .printHelp() is called either by meow itself or by us.
1456
1502
  const cli = meow({
1457
1503
  argv,
@@ -1469,15 +1515,15 @@ function meowOrExit({
1469
1515
  }
1470
1516
  function getAsciiHeader(command) {
1471
1517
  const cliVersion = // The '@rollup/plugin-replace' will replace "process.env['SOCKET_CLI_VERSION_HASH']".
1472
- "0.14.48:61ff8dc:8fc87ff3:pub";
1518
+ "0.14.49:216163f:fdc0b2b7:pub";
1473
1519
  const nodeVersion = process.version;
1474
- // Get the last 5 characters of the API token before the trailing "_api".
1475
- const lastFiveCharsOfApiToken = index.getSetting('apiToken')?.slice(-9, -4) || 'no';
1520
+ const apiToken = index.getSetting('apiToken');
1521
+ const shownToken = apiToken ? getLastFiveOfApiToken(apiToken) : 'no';
1476
1522
  const relCwd = process.cwd().replace(new RegExp(`^${regexps.escapeRegExp(constants.homePath)}`, 'i'), '~/');
1477
1523
  const body = `
1478
1524
  _____ _ _ /---------------
1479
1525
  | __|___ ___| |_ ___| |_ | Socket.dev CLI ver ${cliVersion}
1480
- |__ | . | _| '_| -_| _| | Node: ${nodeVersion}, API token set: ${lastFiveCharsOfApiToken}
1526
+ |__ | . | _| '_| -_| _| | Node: ${nodeVersion}, API token set: ${shownToken}
1481
1527
  |_____|___|___|_,_|___|_|.dev | Command: \`${command}\`, cwd: ${relCwd}`.trimStart();
1482
1528
  return ` ${body}\n`;
1483
1529
  }
@@ -1533,49 +1579,10 @@ async function run$z(argv, importMeta, {
1533
1579
  });
1534
1580
  const githubEventBefore = String(cli.flags['githubEventBefore'] || '');
1535
1581
  const githubEventAfter = String(cli.flags['githubEventAfter'] || '');
1536
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
1537
- await runAction(githubEventBefore, githubEventAfter);
1538
- }
1539
-
1540
- const {
1541
- API_V0_URL
1542
- } = constants;
1543
- function handleUnsuccessfulApiResponse(_name, result, spinner) {
1544
- // SocketSdkErrorType['error'] is not typed.
1545
- const resultErrorMessage = result.error?.message;
1546
- const message = typeof resultErrorMessage === 'string' ? resultErrorMessage : 'No error message returned';
1547
- if (result.status === 401 || result.status === 403) {
1548
- spinner.stop();
1549
- throw new index.AuthError(message);
1550
- }
1551
- spinner.error(`${colors.bgRed(colors.white('API returned an error:'))} ${message}`);
1552
- process$1.exit(1);
1553
- }
1554
- async function handleApiCall(value, description) {
1555
- let result;
1556
- try {
1557
- result = await value;
1558
- } catch (cause) {
1559
- throw new Error(`Failed ${description}`, {
1560
- cause
1561
- });
1562
- }
1563
- return result;
1564
- }
1565
- async function handleAPIError(code) {
1566
- if (code === 400) {
1567
- return 'One of the options passed might be incorrect.';
1568
- } else if (code === 403) {
1569
- return 'You might be trying to access an organization that is not linked to the API key you are logged in with.';
1582
+ if (cli.flags['dryRun']) {
1583
+ return console.log('[DryRun] Bailing now');
1570
1584
  }
1571
- }
1572
- async function queryAPI(path, apiToken) {
1573
- return await fetch(`${API_V0_URL}/${path}`, {
1574
- method: 'GET',
1575
- headers: {
1576
- Authorization: `Basic ${btoa(`${apiToken}:${apiToken}`)}`
1577
- }
1578
- });
1585
+ await runAction(githubEventBefore, githubEventAfter);
1579
1586
  }
1580
1587
 
1581
1588
  // Note: Widgets does not seem to actually work as code :'(
@@ -1850,7 +1857,9 @@ async function run$y(argv, importMeta, {
1850
1857
  - Repository name using --repo when scope is "repo" ${badRepo ? colors.red('(bad!)') : colors.green('(ok)')}\n`);
1851
1858
  return;
1852
1859
  }
1853
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
1860
+ if (cli.flags['dryRun']) {
1861
+ return console.log('[DryRun] Bailing now');
1862
+ }
1854
1863
  const apiToken = index.getDefaultToken();
1855
1864
  if (!apiToken) {
1856
1865
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API token.');
@@ -1978,7 +1987,9 @@ async function run$x(argv, importMeta, {
1978
1987
  - Org name as the first argument ${!orgSlug ? colors.red('(missing!)') : colors.green('(ok)')}\n`);
1979
1988
  return;
1980
1989
  }
1981
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
1990
+ if (cli.flags['dryRun']) {
1991
+ return console.log('[DryRun] Bailing now');
1992
+ }
1982
1993
  const apiToken = index.getDefaultToken();
1983
1994
  if (!apiToken) {
1984
1995
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -2200,7 +2211,9 @@ async function run$w(argv, importMeta, {
2200
2211
  if (yargv.output === undefined) {
2201
2212
  yargv.output = 'socket-cdx.json';
2202
2213
  }
2203
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
2214
+ if (cli.flags['dryRun']) {
2215
+ return console.log('[DryRun] Bailing now');
2216
+ }
2204
2217
  await runCycloneDX(yargv);
2205
2218
  }
2206
2219
 
@@ -2303,7 +2316,9 @@ async function run$v(argv, importMeta, {
2303
2316
  importMeta,
2304
2317
  parentName
2305
2318
  });
2306
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
2319
+ if (cli.flags['dryRun']) {
2320
+ return console.log('[DryRun] Bailing now');
2321
+ }
2307
2322
 
2308
2323
  // TODO: markdown flag is ignored
2309
2324
  await findDependencies({
@@ -2425,7 +2440,9 @@ async function run$u(argv, importMeta, {
2425
2440
  - Org name as the first argument ${!orgSlug ? colors.red('(missing!)') : colors.green('(ok)')}\n`);
2426
2441
  return;
2427
2442
  }
2428
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
2443
+ if (cli.flags['dryRun']) {
2444
+ return console.log('[DryRun] Bailing now');
2445
+ }
2429
2446
  const apiToken = index.getDefaultToken();
2430
2447
  if (!apiToken) {
2431
2448
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -2458,7 +2475,7 @@ const cmdDiffScan = {
2458
2475
  }
2459
2476
  };
2460
2477
 
2461
- // import { detect } from '../../utils/package-manager-detector'
2478
+ // import { detect } from '../../utils/package-environment-detector'
2462
2479
 
2463
2480
  const {
2464
2481
  NPM: NPM$d
@@ -2593,7 +2610,9 @@ async function run$t(argv, importMeta, {
2593
2610
  importMeta,
2594
2611
  parentName
2595
2612
  });
2596
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
2613
+ if (cli.flags['dryRun']) {
2614
+ return console.log('[DryRun] Bailing now');
2615
+ }
2597
2616
  await runFix();
2598
2617
  }
2599
2618
 
@@ -2856,7 +2875,9 @@ async function run$s(argv, importMeta, {
2856
2875
  const versionSeparator = rawPkgName.lastIndexOf('@');
2857
2876
  const pkgName = versionSeparator < 1 ? rawPkgName : rawPkgName.slice(0, versionSeparator);
2858
2877
  const pkgVersion = versionSeparator < 1 ? 'latest' : rawPkgName.slice(versionSeparator + 1);
2859
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
2878
+ if (cli.flags['dryRun']) {
2879
+ return console.log('[DryRun] Bailing now');
2880
+ }
2860
2881
  await getPackageInfo({
2861
2882
  commandName: `${parentName} ${config$s.commandName}`,
2862
2883
  includeAllIssues: Boolean(cli.flags['all']),
@@ -2985,7 +3006,9 @@ async function run$r(argv, importMeta, {
2985
3006
  });
2986
3007
  let apiBaseUrl = cli.flags['apiBaseUrl'];
2987
3008
  let apiProxy = cli.flags['apiProxy'];
2988
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
3009
+ if (cli.flags['dryRun']) {
3010
+ return console.log('[DryRun] Bailing now');
3011
+ }
2989
3012
  if (!isInteractive()) {
2990
3013
  throw new index.InputError('Cannot prompt for credentials in a non-interactive shell');
2991
3014
  }
@@ -3036,7 +3059,9 @@ async function run$q(argv, importMeta, {
3036
3059
  importMeta,
3037
3060
  parentName
3038
3061
  });
3039
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
3062
+ if (cli.flags['dryRun']) {
3063
+ return console.log('[DryRun] Bailing now');
3064
+ }
3040
3065
  attemptLogout();
3041
3066
  }
3042
3067
 
@@ -3265,7 +3290,9 @@ async function run$p(argv, importMeta, {
3265
3290
  if (cli.flags['gradleOpts']) {
3266
3291
  gradleOpts = cli.flags['gradleOpts'].split(' ').map(s => s.trim()).filter(Boolean);
3267
3292
  }
3268
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
3293
+ if (cli.flags['dryRun']) {
3294
+ return console.log('[DryRun] Bailing now');
3295
+ }
3269
3296
  await convertGradleToMaven(target, bin, out, verbose, gradleOpts);
3270
3297
  }
3271
3298
 
@@ -3489,7 +3516,9 @@ async function run$o(argv, importMeta, {
3489
3516
  if (cli.flags['sbtOpts']) {
3490
3517
  sbtOpts = cli.flags['sbtOpts'].split(' ').map(s => s.trim()).filter(Boolean);
3491
3518
  }
3492
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
3519
+ if (cli.flags['dryRun']) {
3520
+ return console.log('[DryRun] Bailing now');
3521
+ }
3493
3522
  await convertSbtToMaven(target, bin, out, verbose, sbtOpts);
3494
3523
  }
3495
3524
 
@@ -3557,7 +3586,9 @@ async function run$n(argv, importMeta, {
3557
3586
  subArgs.push('--cwd', cwd);
3558
3587
  }
3559
3588
  subArgs.push(dir);
3560
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
3589
+ if (cli.flags['dryRun']) {
3590
+ return console.log('[DryRun] Bailing now');
3591
+ }
3561
3592
  await cmdManifestScala.run(subArgs, importMeta, {
3562
3593
  parentName
3563
3594
  });
@@ -3569,7 +3600,9 @@ async function run$n(argv, importMeta, {
3569
3600
  // This command takes the cwd as first arg.
3570
3601
  subArgs.push(cwd);
3571
3602
  }
3572
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
3603
+ if (cli.flags['dryRun']) {
3604
+ return console.log('[DryRun] Bailing now');
3605
+ }
3573
3606
  await cmdManifestGradle.run(subArgs, importMeta, {
3574
3607
  parentName
3575
3608
  });
@@ -3732,7 +3765,9 @@ async function run$m(argv, importMeta, {
3732
3765
  if (cli.flags['gradleOpts']) {
3733
3766
  gradleOpts = cli.flags['gradleOpts'].split(' ').map(s => s.trim()).filter(Boolean);
3734
3767
  }
3735
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
3768
+ if (cli.flags['dryRun']) {
3769
+ return console.log('[DryRun] Bailing now');
3770
+ }
3736
3771
  await convertGradleToMaven(target, bin, out, verbose, gradleOpts);
3737
3772
  }
3738
3773
 
@@ -3810,7 +3845,9 @@ async function run$k(argv, importMeta, {
3810
3845
  importMeta,
3811
3846
  parentName
3812
3847
  });
3813
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
3848
+ if (cli.flags['dryRun']) {
3849
+ return console.log('[DryRun] Bailing now');
3850
+ }
3814
3851
  await wrapNpm(argv);
3815
3852
  }
3816
3853
 
@@ -3852,7 +3889,9 @@ async function run$j(argv, importMeta, {
3852
3889
  importMeta,
3853
3890
  parentName
3854
3891
  });
3855
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
3892
+ if (cli.flags['dryRun']) {
3893
+ return console.log('[DryRun] Bailing now');
3894
+ }
3856
3895
  await wrapNpx(argv);
3857
3896
  }
3858
3897
 
@@ -3884,7 +3923,9 @@ async function run$i(argv, importMeta, {
3884
3923
  importMeta,
3885
3924
  parentName
3886
3925
  });
3887
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
3926
+ if (cli.flags['dryRun']) {
3927
+ return console.log('[DryRun] Bailing now');
3928
+ }
3888
3929
  throw new Error('This error was intentionally left blank');
3889
3930
  }
3890
3931
 
@@ -3902,16 +3943,7 @@ function matchHumanStdout(stdout, name) {
3902
3943
  function matchQueryStdout(stdout, name) {
3903
3944
  return stdout.includes(`"${name}"`);
3904
3945
  }
3905
- const depsIncludesByAgent = {
3906
- // @ts-ignore
3907
- __proto__: null,
3908
- [BUN$6]: matchHumanStdout,
3909
- [NPM$9]: matchQueryStdout,
3910
- [PNPM$7]: matchQueryStdout,
3911
- [VLT$6]: matchQueryStdout,
3912
- [YARN_BERRY$6]: matchHumanStdout,
3913
- [YARN_CLASSIC$6]: matchHumanStdout
3914
- };
3946
+ const depsIncludesByAgent = new Map([[BUN$6, matchHumanStdout], [NPM$9, matchQueryStdout], [PNPM$7, matchQueryStdout], [VLT$6, matchQueryStdout], [YARN_BERRY$6, matchHumanStdout], [YARN_CLASSIC$6, matchHumanStdout]]);
3915
3947
 
3916
3948
  const {
3917
3949
  BINARY_LOCK_EXT,
@@ -4011,15 +4043,15 @@ const readLockFileByAgent = (() => {
4011
4043
  [YARN_CLASSIC$5]: defaultReader
4012
4044
  };
4013
4045
  })();
4014
- async function detect({
4046
+ async function detectPackageEnvironment({
4015
4047
  cwd = process$1.cwd(),
4016
4048
  onUnknown
4017
4049
  } = {}) {
4018
4050
  let lockPath = await index.findUp(Object.keys(LOCKS), {
4019
4051
  cwd
4020
4052
  });
4021
- let lockBasename = lockPath ? path.basename(lockPath) : undefined;
4022
- const isHiddenLockFile = lockBasename === '.package-lock.json';
4053
+ let lockName = lockPath ? path.basename(lockPath) : undefined;
4054
+ const isHiddenLockFile = lockName === '.package-lock.json';
4023
4055
  const pkgJsonPath = lockPath ? path.resolve(lockPath, `${isHiddenLockFile ? '../' : ''}../package.json`) : await index.findUp('package.json', {
4024
4056
  cwd
4025
4057
  });
@@ -4044,8 +4076,8 @@ async function detect({
4044
4076
  }
4045
4077
  }
4046
4078
  }
4047
- if (agent === undefined && !isHiddenLockFile && typeof pkgJsonPath === 'string' && typeof lockBasename === 'string') {
4048
- agent = LOCKS[lockBasename];
4079
+ if (agent === undefined && !isHiddenLockFile && typeof pkgJsonPath === 'string' && typeof lockName === 'string') {
4080
+ agent = LOCKS[lockName];
4049
4081
  }
4050
4082
  if (agent === undefined) {
4051
4083
  agent = NPM$8;
@@ -4096,14 +4128,14 @@ async function detect({
4096
4128
  targets.node = constants.maintainedNodeVersions.some(v => semver.satisfies(v, `>=${minimumNodeVersion}`));
4097
4129
  lockSrc = typeof lockPath === 'string' ? await readLockFileByAgent[agent](lockPath, agentExecPath) : undefined;
4098
4130
  } else {
4099
- lockBasename = undefined;
4131
+ lockName = undefined;
4100
4132
  lockPath = undefined;
4101
4133
  }
4102
4134
  return {
4103
4135
  agent,
4104
4136
  agentExecPath,
4105
4137
  agentVersion,
4106
- lockBasename,
4138
+ lockName,
4107
4139
  lockPath,
4108
4140
  lockSrc,
4109
4141
  minimumNodeVersion,
@@ -4117,74 +4149,53 @@ async function detect({
4117
4149
 
4118
4150
  const {
4119
4151
  BUN: BUN$4,
4120
- NPM: NPM$7,
4121
4152
  VLT: VLT$4,
4122
4153
  YARN_BERRY: YARN_BERRY$4
4123
4154
  } = constants;
4124
4155
  const COMMAND_TITLE$2 = 'Socket Optimize';
4125
- const manifestNpmOverrides = registry.getManifestData(NPM$7);
4126
- async function detectAndValidatePackageManager(cwd, prod) {
4156
+ async function detectAndValidatePackageEnvironment(cwd, options) {
4127
4157
  const {
4128
- agent,
4129
- agentExecPath,
4130
- agentVersion,
4131
- lockBasename,
4132
- lockPath,
4133
- lockSrc,
4134
- minimumNodeVersion,
4135
- npmExecPath,
4136
- pkgJson,
4137
- pkgPath,
4138
- supported
4139
- } = await detect({
4158
+ logger,
4159
+ prod
4160
+ } = {
4161
+ __proto__: null,
4162
+ ...options
4163
+ };
4164
+ const details = await detectPackageEnvironment({
4140
4165
  cwd,
4141
4166
  onUnknown(pkgManager) {
4142
- console.warn(`⚠️ ${COMMAND_TITLE$2}: Unknown package manager${pkgManager ? ` ${pkgManager}` : ''}, defaulting to npm`);
4167
+ logger?.warn(`⚠️ ${COMMAND_TITLE$2}: Unknown package manager${pkgManager ? ` ${pkgManager}` : ''}, defaulting to npm`);
4143
4168
  }
4144
4169
  });
4145
- if (!supported) {
4146
- console.error(`✖️ ${COMMAND_TITLE$2}: No supported Node or browser range detected`);
4170
+ if (!details.supported) {
4171
+ logger?.error(`✖️ ${COMMAND_TITLE$2}: No supported Node or browser range detected`);
4147
4172
  return;
4148
4173
  }
4149
- if (agent === VLT$4) {
4150
- console.error(`✖️ ${COMMAND_TITLE$2}: ${agent} does not support overrides. Soon, though ⚡`);
4174
+ if (details.agent === VLT$4) {
4175
+ logger?.error(`✖️ ${COMMAND_TITLE$2}: ${details.agent} does not support overrides. Soon, though ⚡`);
4151
4176
  return;
4152
4177
  }
4153
- const lockName = lockPath && lockBasename ? lockBasename : 'lock file';
4154
- if (lockBasename === undefined || lockSrc === undefined) {
4155
- console.error(`✖️ ${COMMAND_TITLE$2}: No ${lockName} found`);
4178
+ const lockName = details.lockName ?? 'lock file';
4179
+ if (details.lockName === undefined || details.lockSrc === undefined) {
4180
+ logger?.error(`✖️ ${COMMAND_TITLE$2}: No ${lockName} found`);
4156
4181
  return;
4157
4182
  }
4158
- if (lockSrc.trim() === '') {
4159
- console.error(`✖️ ${COMMAND_TITLE$2}: ${lockName} is empty`);
4183
+ if (details.lockSrc.trim() === '') {
4184
+ logger?.error(`✖️ ${COMMAND_TITLE$2}: ${lockName} is empty`);
4160
4185
  return;
4161
4186
  }
4162
- if (pkgPath === undefined) {
4163
- console.error(`✖️ ${COMMAND_TITLE$2}: No package.json found`);
4187
+ if (details.pkgPath === undefined) {
4188
+ logger?.error(`✖️ ${COMMAND_TITLE$2}: No package.json found`);
4164
4189
  return;
4165
4190
  }
4166
- if (prod && (agent === BUN$4 || agent === YARN_BERRY$4)) {
4167
- console.error(`✖️ ${COMMAND_TITLE$2}: --prod not supported for ${agent}${agentVersion ? `@${agentVersion.toString()}` : ''}`);
4191
+ if (prod && (details.agent === BUN$4 || details.agent === YARN_BERRY$4)) {
4192
+ logger?.error(`✖️ ${COMMAND_TITLE$2}: --prod not supported for ${details.agent}${details.agentVersion ? `@${details.agentVersion.toString()}` : ''}`);
4168
4193
  return;
4169
4194
  }
4170
- if (lockPath && path.relative(cwd, lockPath).startsWith('.')) {
4171
- console.warn(`⚠️ ${COMMAND_TITLE$2}: Package ${lockName} found at ${lockPath}`);
4195
+ if (details.lockPath && path.relative(cwd, details.lockPath).startsWith('.')) {
4196
+ logger?.warn(`⚠️ ${COMMAND_TITLE$2}: Package ${lockName} found at ${details.lockPath}`);
4172
4197
  }
4173
- const nodeRange = `>=${minimumNodeVersion}`;
4174
- const manifestEntries = manifestNpmOverrides.filter(({
4175
- 1: data
4176
- }) => semver.satisfies(semver.coerce(data.engines.node), nodeRange));
4177
- return {
4178
- agent,
4179
- agentExecPath,
4180
- lockBasename,
4181
- lockName,
4182
- lockSrc,
4183
- manifestEntries,
4184
- npmExecPath,
4185
- pkgJson,
4186
- pkgPath
4187
- };
4198
+ return details;
4188
4199
  }
4189
4200
 
4190
4201
  function getDependencyEntries(pkgJson) {
@@ -4213,7 +4224,7 @@ function getDependencyEntries(pkgJson) {
4213
4224
 
4214
4225
  const {
4215
4226
  BUN: BUN$3,
4216
- NPM: NPM$6,
4227
+ NPM: NPM$7,
4217
4228
  OVERRIDES: OVERRIDES$1,
4218
4229
  PNPM: PNPM$5,
4219
4230
  RESOLUTIONS: RESOLUTIONS$1,
@@ -4234,7 +4245,7 @@ function getOverridesDataBun(pkgJson) {
4234
4245
  function getOverridesDataNpm(pkgJson) {
4235
4246
  const overrides = pkgJson?.[OVERRIDES$1] ?? {};
4236
4247
  return {
4237
- type: NPM$6,
4248
+ type: NPM$7,
4238
4249
  overrides
4239
4250
  };
4240
4251
  }
@@ -4275,16 +4286,7 @@ function getOverridesDataClassic(pkgJson) {
4275
4286
  overrides
4276
4287
  };
4277
4288
  }
4278
- const getOverridesDataByAgent = {
4279
- // @ts-ignore
4280
- __proto__: null,
4281
- [BUN$3]: getOverridesDataBun,
4282
- [NPM$6]: getOverridesDataNpm,
4283
- [PNPM$5]: getOverridesDataPnpm,
4284
- [VLT$3]: getOverridesDataVlt,
4285
- [YARN_BERRY$3]: getOverridesDataYarn,
4286
- [YARN_CLASSIC$4]: getOverridesDataClassic
4287
- };
4289
+ const overridesDataByAgent = new Map([[BUN$3, getOverridesDataBun], [NPM$7, getOverridesDataNpm], [PNPM$5, getOverridesDataPnpm], [VLT$3, getOverridesDataVlt], [YARN_BERRY$3, getOverridesDataYarn], [YARN_CLASSIC$4, getOverridesDataClassic]]);
4288
4290
 
4289
4291
  const {
4290
4292
  PNPM: PNPM$4
@@ -4332,7 +4334,7 @@ function workspacePatternToGlobPattern(workspace) {
4332
4334
  const {
4333
4335
  BUN: BUN$2,
4334
4336
  LOCK_EXT,
4335
- NPM: NPM$5,
4337
+ NPM: NPM$6,
4336
4338
  PNPM: PNPM$3,
4337
4339
  VLT: VLT$2,
4338
4340
  YARN_BERRY: YARN_BERRY$2,
@@ -4343,12 +4345,12 @@ function lockIncludesNpm(lockSrc, name) {
4343
4345
  // "name":
4344
4346
  return lockSrc.includes(`"${name}":`);
4345
4347
  }
4346
- function lockIncludesBun(lockSrc, name, lockBasename) {
4347
- // This is a bit counterintuitive. When lockBasename ends with a .lockb
4348
- // we treat it as a yarn.lock. When lockBasename ends with a .lock we
4348
+ function lockIncludesBun(lockSrc, name, lockName) {
4349
+ // This is a bit counterintuitive. When lockName ends with a .lockb
4350
+ // we treat it as a yarn.lock. When lockName ends with a .lock we
4349
4351
  // treat it as a package-lock.json. The bun.lock format is not identical
4350
4352
  // package-lock.json, however it close enough for npmLockIncludes to work.
4351
- const lockScanner = lockBasename?.endsWith(LOCK_EXT) ? lockIncludesNpm : lockIncludesYarn;
4353
+ const lockScanner = lockName?.endsWith(LOCK_EXT) ? lockIncludesNpm : lockIncludesYarn;
4352
4354
  return lockScanner(lockSrc, name);
4353
4355
  }
4354
4356
  function lockIncludesPnpm(lockSrc, name) {
@@ -4376,20 +4378,11 @@ function lockIncludesYarn(lockSrc, name) {
4376
4378
  // , name@
4377
4379
  `(?<=(?:^\\s*|,\\s*)"?)${escapedName}(?=@)`, 'm').test(lockSrc);
4378
4380
  }
4379
- const lockIncludesByAgent = {
4380
- // @ts-ignore
4381
- __proto__: null,
4382
- [BUN$2]: lockIncludesBun,
4383
- [NPM$5]: lockIncludesNpm,
4384
- [PNPM$3]: lockIncludesPnpm,
4385
- [VLT$2]: lockIncludesVlt,
4386
- [YARN_BERRY$2]: lockIncludesYarn,
4387
- [YARN_CLASSIC$3]: lockIncludesYarn
4388
- };
4381
+ const lockIncludesByAgent = new Map([[BUN$2, lockIncludesBun], [NPM$6, lockIncludesNpm], [PNPM$3, lockIncludesPnpm], [VLT$2, lockIncludesVlt], [YARN_BERRY$2, lockIncludesYarn], [YARN_CLASSIC$3, lockIncludesYarn]]);
4389
4382
 
4390
4383
  const {
4391
4384
  BUN: BUN$1,
4392
- NPM: NPM$4,
4385
+ NPM: NPM$5,
4393
4386
  PNPM: PNPM$2,
4394
4387
  VLT: VLT$1,
4395
4388
  YARN_BERRY: YARN_BERRY$1,
@@ -4459,7 +4452,7 @@ async function lsNpm(agentExecPath, cwd) {
4459
4452
  }
4460
4453
  async function lsPnpm(agentExecPath, cwd, options) {
4461
4454
  const npmExecPath = options?.npmExecPath;
4462
- if (npmExecPath && npmExecPath !== NPM$4) {
4455
+ if (npmExecPath && npmExecPath !== NPM$5) {
4463
4456
  const result = await npmQuery(npmExecPath, cwd);
4464
4457
  if (result) {
4465
4458
  return result;
@@ -4510,7 +4503,7 @@ const lsByAgent = {
4510
4503
  // @ts-ignore
4511
4504
  __proto__: null,
4512
4505
  [BUN$1]: lsBun,
4513
- [NPM$4]: lsNpm,
4506
+ [NPM$5]: lsNpm,
4514
4507
  [PNPM$2]: lsPnpm,
4515
4508
  [VLT$1]: lsVlt,
4516
4509
  [YARN_BERRY$1]: lsYarnBerry,
@@ -4519,7 +4512,7 @@ const lsByAgent = {
4519
4512
 
4520
4513
  const {
4521
4514
  BUN,
4522
- NPM: NPM$3,
4515
+ NPM: NPM$4,
4523
4516
  OVERRIDES,
4524
4517
  PNPM: PNPM$1,
4525
4518
  RESOLUTIONS,
@@ -4623,55 +4616,75 @@ function updateResolutions(editablePkgJson, overrides) {
4623
4616
  function pnpmUpdatePkgJson(editablePkgJson, overrides) {
4624
4617
  updatePkgJson(editablePkgJson, PNPM_FIELD_NAME, overrides);
4625
4618
  }
4626
- const updateManifestByAgent = {
4627
- // @ts-ignore
4628
- __proto__: null,
4629
- [BUN]: updateResolutions,
4630
- [NPM$3]: updateOverrides,
4631
- [PNPM$1]: pnpmUpdatePkgJson,
4632
- [VLT]: updateOverrides,
4633
- [YARN_BERRY]: updateResolutions,
4634
- [YARN_CLASSIC$1]: updateResolutions
4635
- };
4619
+ const updateManifestByAgent = new Map([[BUN, updateResolutions], [NPM$4, updateOverrides], [PNPM$1, pnpmUpdatePkgJson], [VLT, updateOverrides], [YARN_BERRY, updateResolutions], [YARN_CLASSIC$1, updateResolutions]]);
4636
4620
 
4637
4621
  const {
4638
- NPM: NPM$2,
4639
- SOCKET_CLI_SAFE_WRAPPER,
4622
+ NPM: NPM$3,
4640
4623
  abortSignal: abortSignal$2
4641
4624
  } = constants;
4625
+ function runAgentInstall(agent, agentExecPath, options) {
4626
+ // All package managers support the "install" command.
4627
+ if (agent === NPM$3) {
4628
+ return npm$1.safeNpmInstall(options);
4629
+ }
4630
+ const {
4631
+ args = [],
4632
+ spinner,
4633
+ ...spawnOptions
4634
+ } = {
4635
+ __proto__: null,
4636
+ ...options
4637
+ };
4638
+ const isSilent = !npmPaths.isDebug();
4639
+ const isSpinning = spinner?.isSpinning ?? false;
4640
+ if (!isSilent) {
4641
+ spinner?.stop();
4642
+ }
4643
+ let spawnPromise = spawn(agentExecPath, ['install', ...args], {
4644
+ signal: abortSignal$2,
4645
+ stdio: isSilent ? 'ignore' : 'inherit',
4646
+ ...spawnOptions,
4647
+ env: {
4648
+ ...process.env,
4649
+ ...spawnOptions.env
4650
+ }
4651
+ });
4652
+ if (!isSilent && isSpinning) {
4653
+ const oldSpawnPromise = spawnPromise;
4654
+ spawnPromise = spawnPromise.finally(() => {
4655
+ spinner?.start();
4656
+ });
4657
+ spawnPromise.process = oldSpawnPromise.process;
4658
+ spawnPromise.stdin = spawnPromise.stdin;
4659
+ }
4660
+ return spawnPromise;
4661
+ }
4662
+
4663
+ const {
4664
+ NPM: NPM$2
4665
+ } = constants;
4642
4666
  const COMMAND_TITLE$1 = 'Socket Optimize';
4643
4667
  const NPM_OVERRIDE_PR_URL = 'https://github.com/npm/cli/pull/8089';
4644
- async function updatePackageLockJson(lockName, agentExecPath, agent, spinner) {
4645
- spinner.start(`Updating ${lockName}...`);
4668
+ async function updatePackageLockJson(pkgEnvDetails, options) {
4669
+ const {
4670
+ logger,
4671
+ spinner
4672
+ } = {
4673
+ __proto__: null,
4674
+ ...options
4675
+ };
4676
+ spinner?.start(`Updating ${pkgEnvDetails.lockName}...`);
4646
4677
  try {
4647
- if (agent === NPM$2) {
4648
- const ipc = {
4649
- [SOCKET_CLI_SAFE_WRAPPER]: true
4650
- };
4651
- await npm$1.safeNpmInstall({
4652
- ipc
4653
- });
4654
- // TODO: This is a temporary workaround for a `npm ci` bug where it
4655
- // will error out after Socket Optimize generates a lock file.
4656
- // More investigation is needed.
4657
- await npm$1.safeNpmInstall({
4658
- args: ['--ignore-scripts', '--package-lock-only'],
4659
- ipc
4660
- });
4661
- } else {
4662
- // All package managers support the "install" command.
4663
- await spawn(agentExecPath, ['install'], {
4664
- signal: abortSignal$2,
4665
- stdio: 'ignore'
4666
- });
4667
- }
4668
- spinner.stop();
4669
- if (agent === NPM$2) {
4670
- console.log(`💡 Re-run ${COMMAND_TITLE$1} whenever ${lockName} changes.\n This can be skipped once npm ships ${NPM_OVERRIDE_PR_URL}.`);
4678
+ await runAgentInstall(pkgEnvDetails.agent, pkgEnvDetails.agentExecPath, {
4679
+ spinner
4680
+ });
4681
+ spinner?.stop();
4682
+ if (pkgEnvDetails.agent === NPM$2) {
4683
+ logger?.log(`💡 Re-run ${COMMAND_TITLE$1} whenever ${pkgEnvDetails.lockName} changes.\n This can be skipped once npm ships ${NPM_OVERRIDE_PR_URL}.`);
4671
4684
  }
4672
4685
  } catch (e) {
4673
- spinner.error(`${COMMAND_TITLE$1}: ${agent} install failed to update ${lockName}`);
4674
- console.error(e);
4686
+ spinner?.error(`${COMMAND_TITLE$1}: ${pkgEnvDetails.agent} install failed to update ${pkgEnvDetails.lockName}`);
4687
+ logger?.error(e);
4675
4688
  }
4676
4689
  }
4677
4690
 
@@ -4681,91 +4694,85 @@ const {
4681
4694
  YARN_CLASSIC
4682
4695
  } = constants;
4683
4696
  const COMMAND_TITLE = 'Socket Optimize';
4697
+ const manifestNpmOverrides = registry.getManifestData(NPM$1);
4684
4698
  async function applyOptimization(cwd, pin, prod) {
4685
- const pkgMgrData = await detectAndValidatePackageManager(cwd, prod);
4686
- if (!pkgMgrData) return;
4687
- const {
4688
- agent,
4689
- agentExecPath,
4690
- lockBasename,
4691
- lockName,
4692
- lockSrc,
4693
- manifestEntries,
4694
- npmExecPath,
4695
- pkgJson,
4696
- pkgPath
4697
- } = pkgMgrData;
4699
+ const logger = console;
4700
+ const pkgEnvDetails = await detectAndValidatePackageEnvironment(cwd, {
4701
+ logger,
4702
+ prod
4703
+ });
4704
+ if (!pkgEnvDetails) {
4705
+ return;
4706
+ }
4698
4707
  const spinner$1 = new spinner.Spinner({
4699
4708
  text: 'Socket optimizing...'
4700
4709
  });
4701
4710
  spinner$1.start();
4702
- const state = await addOverrides({
4703
- agent,
4704
- agentExecPath,
4705
- lockBasename,
4706
- lockSrc,
4707
- manifestEntries,
4708
- npmExecPath,
4711
+ const state = await addOverrides(pkgEnvDetails.pkgPath, pkgEnvDetails, {
4712
+ logger,
4709
4713
  pin,
4710
- pkgJson,
4711
- pkgPath,
4712
4714
  prod,
4713
- rootPath: pkgPath
4714
- }, createAddOverridesState(spinner$1));
4715
+ spinner: spinner$1
4716
+ });
4715
4717
  spinner$1.stop();
4716
4718
  const addedCount = state.added.size;
4717
4719
  const updatedCount = state.updated.size;
4718
4720
  const pkgJsonChanged = addedCount > 0 || updatedCount > 0;
4719
4721
  if (pkgJsonChanged) {
4720
4722
  if (updatedCount > 0) {
4721
- console.log(`${createActionMessage('Updated', updatedCount, state.updatedInWorkspaces.size)}${addedCount ? '.' : '🚀'}`);
4723
+ logger?.log(`${createActionMessage('Updated', updatedCount, state.updatedInWorkspaces.size)}${addedCount ? '.' : '🚀'}`);
4722
4724
  }
4723
4725
  if (addedCount > 0) {
4724
- console.log(`${createActionMessage('Added', addedCount, state.addedInWorkspaces.size)} 🚀`);
4726
+ logger?.log(`${createActionMessage('Added', addedCount, state.addedInWorkspaces.size)} 🚀`);
4725
4727
  }
4726
4728
  } else {
4727
- console.log('Congratulations! Already Socket.dev optimized 🎉');
4729
+ logger?.log('Congratulations! Already Socket.dev optimized 🎉');
4728
4730
  }
4729
- if (agent === NPM$1 || pkgJsonChanged) {
4731
+ if (pkgEnvDetails.agent === NPM$1 || pkgJsonChanged) {
4730
4732
  // Always update package-lock.json until the npm overrides PR lands:
4731
4733
  // https://github.com/npm/cli/pull/8089
4732
- await updatePackageLockJson(lockName, agentExecPath, agent, spinner$1);
4734
+ await updatePackageLockJson(pkgEnvDetails, {
4735
+ logger,
4736
+ spinner: spinner$1
4737
+ });
4733
4738
  }
4734
4739
  }
4735
4740
  function createActionMessage(verb, overrideCount, workspaceCount) {
4736
4741
  return `${verb} ${overrideCount} Socket.dev optimized ${words.pluralize('override', overrideCount)}${workspaceCount ? ` in ${workspaceCount} ${words.pluralize('workspace', workspaceCount)}` : ''}`;
4737
4742
  }
4738
- function createAddOverridesState(spinner) {
4739
- return {
4740
- added: new Set(),
4741
- addedInWorkspaces: new Set(),
4743
+ async function addOverrides(pkgPath, pkgEnvDetails, options) {
4744
+ const {
4745
+ agent,
4746
+ agentExecPath,
4747
+ lockName,
4748
+ lockSrc,
4749
+ npmExecPath,
4750
+ pkgPath: rootPath
4751
+ } = pkgEnvDetails;
4752
+ const {
4753
+ logger,
4754
+ pin,
4755
+ prod,
4742
4756
  spinner,
4743
- updated: new Set(),
4744
- updatedInWorkspaces: new Set(),
4745
- warnedPnpmWorkspaceRequiresNpm: false
4757
+ state = {
4758
+ added: new Set(),
4759
+ addedInWorkspaces: new Set(),
4760
+ updated: new Set(),
4761
+ updatedInWorkspaces: new Set(),
4762
+ warnedPnpmWorkspaceRequiresNpm: false
4763
+ }
4764
+ } = {
4765
+ __proto__: null,
4766
+ ...options
4746
4767
  };
4747
- }
4748
- async function addOverrides({
4749
- agent,
4750
- agentExecPath,
4751
- lockBasename,
4752
- lockSrc,
4753
- manifestEntries,
4754
- npmExecPath,
4755
- pin,
4756
- pkgJson: editablePkgJson,
4757
- pkgPath,
4758
- prod,
4759
- rootPath
4760
- }, state) {
4768
+ let {
4769
+ pkgJson: editablePkgJson
4770
+ } = pkgEnvDetails;
4761
4771
  if (editablePkgJson === undefined) {
4762
4772
  editablePkgJson = await packages.readPackageJson(pkgPath, {
4763
4773
  editable: true
4764
4774
  });
4765
4775
  }
4766
- const {
4767
- spinner
4768
- } = state;
4769
4776
  const {
4770
4777
  content: pkgJson
4771
4778
  } = editablePkgJson;
@@ -4776,7 +4783,7 @@ async function addOverrides({
4776
4783
  const isWorkspace = !!workspaceGlobs;
4777
4784
  if (isWorkspace && agent === PNPM && npmExecPath === NPM$1 && !state.warnedPnpmWorkspaceRequiresNpm) {
4778
4785
  state.warnedPnpmWorkspaceRequiresNpm = true;
4779
- console.warn(`⚠️ ${COMMAND_TITLE}: pnpm workspace support requires \`npm ls\`, falling back to \`pnpm list\``);
4786
+ logger?.warn(`⚠️ ${COMMAND_TITLE}: pnpm workspace support requires \`npm ls\`, falling back to \`pnpm list\``);
4780
4787
  }
4781
4788
  const thingToScan = isLockScanned ? lockSrc : await lsByAgent[agent](agentExecPath, pkgPath, {
4782
4789
  npmExecPath
@@ -4785,18 +4792,22 @@ async function addOverrides({
4785
4792
  // first two parameters. AgentLockIncludesFn accepts an optional third
4786
4793
  // parameter which AgentDepsIncludesFn will ignore so we cast thingScanner
4787
4794
  // as an AgentLockIncludesFn type.
4788
- const thingScanner = isLockScanned ? lockIncludesByAgent[agent] : depsIncludesByAgent[agent];
4795
+ const thingScanner = isLockScanned ? lockIncludesByAgent.get(agent) : depsIncludesByAgent.get(agent);
4789
4796
  const depEntries = getDependencyEntries(pkgJson);
4790
4797
  const overridesDataObjects = [];
4791
4798
  if (pkgJson['private'] || isWorkspace) {
4792
- overridesDataObjects.push(getOverridesDataByAgent[agent](pkgJson));
4799
+ overridesDataObjects.push(overridesDataByAgent.get(agent)(pkgJson));
4793
4800
  } else {
4794
- overridesDataObjects.push(getOverridesDataByAgent[NPM$1](pkgJson), getOverridesDataByAgent[YARN_CLASSIC](pkgJson));
4801
+ overridesDataObjects.push(overridesDataByAgent.get(NPM$1)(pkgJson), overridesDataByAgent.get(YARN_CLASSIC)(pkgJson));
4795
4802
  }
4796
4803
  if (spinner) {
4797
4804
  spinner.text = `Adding overrides${workspaceName ? ` to ${workspaceName}` : ''}...`;
4798
4805
  }
4799
4806
  const depAliasMap = new Map();
4807
+ const nodeRange = `>=${pkgEnvDetails.minimumNodeVersion}`;
4808
+ const manifestEntries = manifestNpmOverrides.filter(({
4809
+ 1: data
4810
+ }) => semver.satisfies(semver.coerce(data.engines.node), nodeRange));
4800
4811
  // Chunk package names to process them in parallel 3 at a time.
4801
4812
  await promises.pEach(manifestEntries, 3, async ({
4802
4813
  1: data
@@ -4839,7 +4850,7 @@ async function addOverrides({
4839
4850
  type
4840
4851
  }) => {
4841
4852
  const overrideExists = objects.hasOwn(overrides, origPkgName);
4842
- if (overrideExists || thingScanner(thingToScan, origPkgName, lockBasename)) {
4853
+ if (overrideExists || thingScanner(thingToScan, origPkgName, lockName)) {
4843
4854
  const oldSpec = overrideExists ? overrides[origPkgName] : undefined;
4844
4855
  const origDepAlias = depAliasMap.get(origPkgName);
4845
4856
  const sockRegDepAlias = depAliasMap.get(sockRegPkgName);
@@ -4884,18 +4895,12 @@ async function addOverrides({
4884
4895
  });
4885
4896
  // Chunk package names to process them in parallel 3 at a time.
4886
4897
  await promises.pEach(workspacePkgJsonPaths, 3, async workspacePkgJsonPath => {
4887
- const otherState = await addOverrides({
4888
- agent,
4889
- agentExecPath,
4890
- lockBasename,
4891
- lockSrc,
4892
- manifestEntries,
4893
- npmExecPath,
4898
+ const otherState = await addOverrides(path.dirname(workspacePkgJsonPath), pkgEnvDetails, {
4899
+ logger,
4894
4900
  pin,
4895
- pkgPath: path.dirname(workspacePkgJsonPath),
4896
4901
  prod,
4897
- rootPath
4898
- }, createAddOverridesState(spinner));
4902
+ spinner
4903
+ });
4899
4904
  for (const key of ['added', 'addedInWorkspaces', 'updated', 'updatedInWorkspaces']) {
4900
4905
  for (const value of otherState[key]) {
4901
4906
  state[key].add(value);
@@ -4909,7 +4914,7 @@ async function addOverrides({
4909
4914
  overrides,
4910
4915
  type
4911
4916
  } of overridesDataObjects) {
4912
- updateManifestByAgent[type](editablePkgJson, objects.toSortedObject(overrides));
4917
+ updateManifestByAgent.get(type)(editablePkgJson, objects.toSortedObject(overrides));
4913
4918
  }
4914
4919
  await editablePkgJson.save();
4915
4920
  }
@@ -4960,32 +4965,74 @@ async function run$h(argv, importMeta, {
4960
4965
  parentName
4961
4966
  });
4962
4967
  const cwd = process$1.cwd();
4963
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
4968
+ if (cli.flags['dryRun']) {
4969
+ return console.log('[DryRun] Bailing now');
4970
+ }
4964
4971
  await applyOptimization(cwd, Boolean(cli.flags['pin']), Boolean(cli.flags['prod']));
4965
4972
  }
4966
4973
 
4967
- async function getOrganizations() {
4974
+ async function getOrganization(format = 'text') {
4968
4975
  const apiToken = index.getDefaultToken();
4969
4976
  if (!apiToken) {
4970
4977
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
4971
4978
  }
4979
+ await printOrganizationsFromToken(apiToken, format);
4980
+ }
4981
+ async function printOrganizationsFromToken(apiToken, format = 'text') {
4972
4982
  const spinner$1 = new spinner.Spinner({
4973
4983
  text: 'Fetching organizations...'
4974
4984
  }).start();
4975
4985
  const socketSdk = await index.setupSdk(apiToken);
4976
4986
  const result = await handleApiCall(socketSdk.getOrganizations(), 'looking up organizations');
4977
- if (result.success === false) {
4987
+ if (!result.success) {
4978
4988
  handleUnsuccessfulApiResponse('getOrganizations', result, spinner$1);
4979
4989
  return;
4980
4990
  }
4981
- spinner$1.stop(`List of organizations associated with your API key: ${colors.italic(apiToken)}`);
4991
+ spinner$1.stop();
4982
4992
  const organizations = Object.values(result.data.organizations);
4983
- for (const o of organizations) {
4984
- console.log(`
4985
- Name: ${o?.name}
4986
- ID: ${o?.id}
4987
- Plan: ${o?.plan}
4988
- `);
4993
+ const lastFiveOfApiToken = getLastFiveOfApiToken(apiToken);
4994
+ switch (format) {
4995
+ case 'json':
4996
+ {
4997
+ console.log(JSON.stringify(organizations.map(o => ({
4998
+ name: o.name,
4999
+ id: o.id,
5000
+ plan: o.plan
5001
+ })), null, 2));
5002
+ return;
5003
+ }
5004
+ case 'markdown':
5005
+ {
5006
+ // | Syntax | Description |
5007
+ // | ----------- | ----------- |
5008
+ // | Header | Title |
5009
+ // | Paragraph | Text |
5010
+ let mw1 = 4;
5011
+ let mw2 = 2;
5012
+ let mw3 = 4;
5013
+ for (const o of organizations) {
5014
+ mw1 = Math.max(mw1, o.name.length);
5015
+ mw2 = Math.max(mw2, o.id.length);
5016
+ mw3 = Math.max(mw3, o.plan.length);
5017
+ }
5018
+ console.log('# Organizations\n');
5019
+ console.log(`List of organizations associated with your API key, ending with: ${colors.italic(lastFiveOfApiToken)}\n`);
5020
+ console.log(`| Name${' '.repeat(mw1 - 4)} | ID${' '.repeat(mw2 - 2)} | Plan${' '.repeat(mw3 - 4)} |`);
5021
+ console.log(`| ${'-'.repeat(mw1)} | ${'-'.repeat(mw2)} | ${'-'.repeat(mw3)} |`);
5022
+ for (const o of organizations) {
5023
+ console.log(`| ${(o.name || '').padEnd(mw1, ' ')} | ${(o.id || '').padEnd(mw2, ' ')} | ${(o.plan || '').padEnd(mw3, ' ')} |`);
5024
+ }
5025
+ console.log(`| ${'-'.repeat(mw1)} | ${'-'.repeat(mw2)} | ${'-'.repeat(mw3)} |`);
5026
+ return;
5027
+ }
5028
+ default:
5029
+ {
5030
+ console.log(`List of organizations associated with your API key, ending with: ${colors.italic(lastFiveOfApiToken)}\n`);
5031
+ // Just dump
5032
+ for (const o of organizations) {
5033
+ console.log(`- Name: ${colors.bold(o.name)}, ID: ${colors.bold(o.id)}, Plan: ${colors.bold(o.plan)}`);
5034
+ }
5035
+ }
4989
5036
  }
4990
5037
  }
4991
5038
 
@@ -4993,13 +5040,19 @@ const config$g = {
4993
5040
  commandName: 'organizations',
4994
5041
  description: 'List organizations associated with the API key used',
4995
5042
  hidden: false,
4996
- flags: {},
5043
+ flags: {
5044
+ ...commonFlags,
5045
+ ...outputFlags
5046
+ },
4997
5047
  help: (command, _config) => `
4998
5048
  Usage
4999
5049
  $ ${command}
5050
+
5051
+ Options
5052
+ ${getFlagListOutput(config$g.flags, 6)}
5000
5053
  `
5001
5054
  };
5002
- const cmdOrganizations = {
5055
+ const cmdOrganization = {
5003
5056
  description: config$g.description,
5004
5057
  hidden: config$g.hidden,
5005
5058
  run: run$g
@@ -5013,8 +5066,23 @@ async function run$g(argv, importMeta, {
5013
5066
  importMeta,
5014
5067
  parentName
5015
5068
  });
5016
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
5017
- await getOrganizations();
5069
+ const json = Boolean(cli.flags['json']);
5070
+ const markdown = Boolean(cli.flags['markdown']);
5071
+ if (json && markdown) {
5072
+ // Use exit status of 2 to indicate incorrect usage, generally invalid
5073
+ // options or missing arguments.
5074
+ // https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html
5075
+ process.exitCode = 2;
5076
+ console.error(`
5077
+ ${colors.bgRed(colors.white('Input error'))}: Please provide the required fields:\n
5078
+ - The json and markdown flags cannot be both set, pick one
5079
+ `);
5080
+ return;
5081
+ }
5082
+ if (cli.flags['dryRun']) {
5083
+ return console.log('[DryRun] Bailing now');
5084
+ }
5085
+ await getOrganization(json ? 'json' : markdown ? 'markdown' : 'text');
5018
5086
  }
5019
5087
 
5020
5088
  const {
@@ -5073,7 +5141,9 @@ async function run$f(argv, importMeta, {
5073
5141
  importMeta,
5074
5142
  parentName
5075
5143
  });
5076
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
5144
+ if (cli.flags['dryRun']) {
5145
+ return console.log('[DryRun] Bailing now');
5146
+ }
5077
5147
  await runRawNpm(argv);
5078
5148
  }
5079
5149
 
@@ -5133,7 +5203,9 @@ async function run$e(argv, importMeta, {
5133
5203
  importMeta,
5134
5204
  parentName
5135
5205
  });
5136
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
5206
+ if (cli.flags['dryRun']) {
5207
+ return console.log('[DryRun] Bailing now');
5208
+ }
5137
5209
  await runRawNpx(argv);
5138
5210
  }
5139
5211
 
@@ -5331,7 +5403,9 @@ async function run$d(argv, importMeta, {
5331
5403
  const view = Boolean(cli.flags['view']);
5332
5404
 
5333
5405
  // Note exiting earlier to skirt a hidden auth requirement
5334
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
5406
+ if (cli.flags['dryRun']) {
5407
+ return console.log('[DryRun] Bailing now');
5408
+ }
5335
5409
  const socketConfig = await getSocketConfig(absoluteConfigPath);
5336
5410
  const result = await createReport(socketConfig, cli.input, {
5337
5411
  cwd,
@@ -5407,7 +5481,9 @@ async function run$c(argv, importMeta, {
5407
5481
  - Can only handle a single report ID ${extraInput.length < 2 ? colors.red(`(received ${extraInput.length}!)`) : colors.green('(ok)')}\n`);
5408
5482
  return;
5409
5483
  }
5410
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
5484
+ if (cli.flags['dryRun']) {
5485
+ return console.log('[DryRun] Bailing now');
5486
+ }
5411
5487
  await viewReport(reportId, {
5412
5488
  all: Boolean(cli.flags['all']),
5413
5489
  commandName: `${parentName} ${config$c.commandName}`,
@@ -5543,7 +5619,9 @@ async function run$b(argv, importMeta, {
5543
5619
  - Repository name using --repoName ${!repoName ? colors.red('(missing!)') : typeof repoName !== 'string' ? colors.red('(invalid!)') : colors.green('(ok)')}\n`);
5544
5620
  return;
5545
5621
  }
5546
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
5622
+ if (cli.flags['dryRun']) {
5623
+ return console.log('[DryRun] Bailing now');
5624
+ }
5547
5625
  const apiToken = index.getDefaultToken();
5548
5626
  if (!apiToken) {
5549
5627
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -5619,7 +5697,9 @@ async function run$a(argv, importMeta, {
5619
5697
  - At least one TARGET (e.g. \`.\` or \`./package.json\`\n`);
5620
5698
  return;
5621
5699
  }
5622
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
5700
+ if (cli.flags['dryRun']) {
5701
+ return console.log('[DryRun] Bailing now');
5702
+ }
5623
5703
  const apiToken = index.getDefaultToken();
5624
5704
  if (!apiToken) {
5625
5705
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -5744,7 +5824,9 @@ async function run$9(argv, importMeta, {
5744
5824
  - At least one TARGET (e.g. \`.\` or \`./package.json\`\n`);
5745
5825
  return;
5746
5826
  }
5747
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
5827
+ if (cli.flags['dryRun']) {
5828
+ return console.log('[DryRun] Bailing now');
5829
+ }
5748
5830
  const apiToken = index.getDefaultToken();
5749
5831
  if (!apiToken) {
5750
5832
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -5870,7 +5952,9 @@ async function run$8(argv, importMeta, {
5870
5952
  - At least one TARGET (e.g. \`.\` or \`./package.json\`\n`);
5871
5953
  return;
5872
5954
  }
5873
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
5955
+ if (cli.flags['dryRun']) {
5956
+ return console.log('[DryRun] Bailing now');
5957
+ }
5874
5958
  const apiToken = index.getDefaultToken();
5875
5959
  if (!apiToken) {
5876
5960
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -5972,7 +6056,9 @@ async function run$7(argv, importMeta, {
5972
6056
  - Repository name using --repoName ${!repoName ? colors.red('(missing!)') : typeof repoName !== 'string' ? colors.red('(invalid!)') : colors.green('(ok)')}\n`);
5973
6057
  return;
5974
6058
  }
5975
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
6059
+ if (cli.flags['dryRun']) {
6060
+ return console.log('[DryRun] Bailing now');
6061
+ }
5976
6062
  const apiToken = index.getDefaultToken();
5977
6063
  if (!apiToken) {
5978
6064
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -6148,7 +6234,9 @@ async function run$6(argv, importMeta, {
6148
6234
  const cwd = cli.flags['cwd'] && cli.flags['cwd'] !== 'process.cwd()' ? String(cli.flags['cwd']) : process$1.cwd();
6149
6235
 
6150
6236
  // Note exiting earlier to skirt a hidden auth requirement
6151
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
6237
+ if (cli.flags['dryRun']) {
6238
+ return console.log('[DryRun] Bailing now');
6239
+ }
6152
6240
  const socketSdk = await index.setupSdk();
6153
6241
  const supportedFiles = await socketSdk.getReportSupportedFiles().then(res => {
6154
6242
  if (!res.success) handleUnsuccessfulApiResponse('getReportSupportedFiles', res, new spinner.Spinner());
@@ -6255,7 +6343,9 @@ async function run$5(argv, importMeta, {
6255
6343
  - Full Scan ID to delete as second argument ${!fullScanId ? colors.red('(missing!)') : colors.green('(ok)')}\n`);
6256
6344
  return;
6257
6345
  }
6258
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
6346
+ if (cli.flags['dryRun']) {
6347
+ return console.log('[DryRun] Bailing now');
6348
+ }
6259
6349
  const apiToken = index.getDefaultToken();
6260
6350
  if (!apiToken) {
6261
6351
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -6385,7 +6475,9 @@ async function run$4(argv, importMeta, {
6385
6475
  - Org name as the argument ${!orgSlug ? colors.red('(missing!)') : colors.green('(ok)')}\n`);
6386
6476
  return;
6387
6477
  }
6388
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
6478
+ if (cli.flags['dryRun']) {
6479
+ return console.log('[DryRun] Bailing now');
6480
+ }
6389
6481
  const apiToken = index.getDefaultToken();
6390
6482
  if (!apiToken) {
6391
6483
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -6464,7 +6556,9 @@ async function run$3(argv, importMeta, {
6464
6556
  - Full Scan ID to inspect as second argument ${!fullScanId ? colors.red('(missing!)') : colors.green('(ok)')}\n`);
6465
6557
  return;
6466
6558
  }
6467
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
6559
+ if (cli.flags['dryRun']) {
6560
+ return console.log('[DryRun] Bailing now');
6561
+ }
6468
6562
  const apiToken = index.getDefaultToken();
6469
6563
  if (!apiToken) {
6470
6564
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -6532,7 +6626,9 @@ async function run$2(argv, importMeta, {
6532
6626
  - Full Scan ID to fetch as second argument ${!fullScanId ? colors.red('(missing!)') : colors.green('(ok)')}\n`);
6533
6627
  return;
6534
6628
  }
6535
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
6629
+ if (cli.flags['dryRun']) {
6630
+ return console.log('[DryRun] Bailing now');
6631
+ }
6536
6632
  const apiToken = index.getDefaultToken();
6537
6633
  if (!apiToken) {
6538
6634
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -6695,7 +6791,9 @@ async function run$1(argv, importMeta, {
6695
6791
  importMeta,
6696
6792
  parentName
6697
6793
  });
6698
- if (cli.flags['dryRun']) return console.log('[DryRun] Bailing now');
6794
+ if (cli.flags['dryRun']) {
6795
+ return console.log('[DryRun] Bailing now');
6796
+ }
6699
6797
  const apiToken = index.getDefaultToken();
6700
6798
  if (!apiToken) {
6701
6799
  throw new index.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
@@ -6924,7 +7022,7 @@ void (async () => {
6924
7022
  npx: cmdNpx,
6925
7023
  oops: cmdOops,
6926
7024
  optimize: cmdOptimize,
6927
- organization: cmdOrganizations,
7025
+ organization: cmdOrganization,
6928
7026
  'raw-npm': cmdRawNpm,
6929
7027
  'raw-npx': cmdRawNpx,
6930
7028
  report: cmdReport,
@@ -6976,5 +7074,5 @@ void (async () => {
6976
7074
  await index.captureException(e);
6977
7075
  }
6978
7076
  })();
6979
- //# debugId=2303041b-c570-4dda-ac6a-10845950c7af
7077
+ //# debugId=9211012b-2bab-40e6-b115-6389952c7273
6980
7078
  //# sourceMappingURL=cli.js.map