@socketsecurity/cli-with-sentry 0.14.59 → 0.14.61

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.
@@ -903,19 +903,20 @@ class GitHub {
903
903
  case 'push':
904
904
  return this.prNumber ? 'diff' : 'main';
905
905
  case 'pull_request':
906
- // This env variable needs to be set in the GitHub action.
907
- // Add this code below to GitHub action:
908
- // - steps:
909
- // - name: Get PR State
910
- // if: github.event_name == 'pull_request'
911
- // run: echo "EVENT_ACTION=${{ github.event.action }}" >> $GITHUB_ENV
912
- const eventAction = process.env['EVENT_ACTION'];
913
- if (!eventAction) {
914
- throw new Error('Missing event action');
915
- }
916
- if (['opened', 'synchronize'].includes(eventAction)) {
917
- return 'diff';
918
- } else {
906
+ {
907
+ // This env variable needs to be set in the GitHub action.
908
+ // Add this code below to GitHub action:
909
+ // - steps:
910
+ // - name: Get PR State
911
+ // if: github.event_name == 'pull_request'
912
+ // run: echo "EVENT_ACTION=${{ github.event.action }}" >> $GITHUB_ENV
913
+ const eventAction = process.env['EVENT_ACTION'];
914
+ if (eventAction === 'opened' || eventAction === 'synchronize') {
915
+ return 'diff';
916
+ }
917
+ if (!eventAction) {
918
+ throw new Error('Missing event action');
919
+ }
919
920
  logger.logger.log(`Pull request action: ${eventAction} is not supported`);
920
921
  process.exit();
921
922
  }
@@ -1518,14 +1519,14 @@ function emitBanner(name) {
1518
1519
  // It also helps with debugging since it contains version and command details.
1519
1520
  // Note: print over stderr to preserve stdout for flags like --json and
1520
1521
  // --markdown. If we don't do this, you can't use --json in particular
1521
- // and pipe the result to other tools. By emiting the banner over stderr
1522
+ // and pipe the result to other tools. By emitting the banner over stderr
1522
1523
  // you can do something like `socket scan view xyz | jq | process`.
1523
1524
  // The spinner also emits over stderr for example.
1524
1525
  logger.logger.error(getAsciiHeader(name));
1525
1526
  }
1526
1527
  function getAsciiHeader(command) {
1527
- const cliVersion = // The '@rollup/plugin-replace' will replace "process.env['SOCKET_CLI_VERSION_HASH']".
1528
- "0.14.59:e40b009:5200cfd8:pub";
1528
+ const cliVersion = // The '@rollup/plugin-replace' will replace "process.env['INLINED_SOCKET_CLI_VERSION_HASH']".
1529
+ "0.14.61:d32a295:723e3f67:pub";
1529
1530
  const nodeVersion = process.version;
1530
1531
  const apiToken = shadowNpmInject.getSetting('apiToken');
1531
1532
  const shownToken = apiToken ? getLastFiveOfApiToken(apiToken) : 'no';
@@ -2260,28 +2261,43 @@ async function run$x(argv, importMeta, {
2260
2261
  const {
2261
2262
  NPM: NPM$f,
2262
2263
  NPX: NPX$3,
2263
- PNPM: PNPM$a
2264
+ PACKAGE_LOCK_JSON,
2265
+ PNPM: PNPM$a,
2266
+ YARN: YARN$1,
2267
+ YARN_LOCK
2264
2268
  } = constants;
2265
2269
  const nodejsPlatformTypes = new Set(['javascript', 'js', 'nodejs', NPM$f, PNPM$a, 'ts', 'tsx', 'typescript']);
2266
- async function runCycloneDX(yargv) {
2270
+ async function runCycloneDX(yargvWithYes) {
2267
2271
  let cleanupPackageLock = false;
2268
- if (yargv.type !== 'yarn' && nodejsPlatformTypes.has(yargv.type) && fs.existsSync('./yarn.lock')) {
2269
- if (fs.existsSync('./package-lock.json')) {
2272
+ const {
2273
+ yes,
2274
+ ...yargv
2275
+ } = {
2276
+ __proto__: null,
2277
+ ...yargvWithYes
2278
+ };
2279
+ const yesArgs = yes ? ['--yes'] : [];
2280
+ if (yargv.type !== YARN$1 && nodejsPlatformTypes.has(yargv.type) && fs.existsSync(`./${YARN_LOCK}`)) {
2281
+ if (fs.existsSync(`./${PACKAGE_LOCK_JSON}`)) {
2270
2282
  yargv.type = NPM$f;
2271
2283
  } else {
2272
2284
  // Use synp to create a package-lock.json from the yarn.lock,
2273
2285
  // based on the node_modules folder, for a more accurate SBOM.
2274
2286
  try {
2275
- await shadowBin(NPX$3, ['synp@1.9.14', '--', '--source-file', './yarn.lock'], 2);
2287
+ await shadowBin(NPX$3, [...yesArgs,
2288
+ // The '@rollup/plugin-replace' will replace "process.env['INLINED_SYNP_VERSION']".
2289
+ `synp@${"^1.9.14"}`, '--source-file', `./${YARN_LOCK}`]);
2276
2290
  yargv.type = NPM$f;
2277
2291
  cleanupPackageLock = true;
2278
2292
  } catch {}
2279
2293
  }
2280
2294
  }
2281
- await shadowBin(NPX$3, ['@cyclonedx/cdxgen@11.2.0', '--', ...argvToArray(yargv)], 2);
2295
+ await shadowBin(NPX$3, [...yesArgs,
2296
+ // The '@rollup/plugin-replace' will replace "process.env['INLINED_CYCLONEDX_CDXGEN_VERSION']".
2297
+ `@cyclonedx/cdxgen@${"^11.2.1"}`, ...argvToArray(yargv)]);
2282
2298
  if (cleanupPackageLock) {
2283
2299
  try {
2284
- await fs.promises.rm('./package-lock.json');
2300
+ await fs.promises.rm(`./${PACKAGE_LOCK_JSON}`);
2285
2301
  } catch {}
2286
2302
  }
2287
2303
  const fullOutputPath = path.join(process$1.cwd(), yargv.output);
@@ -2290,13 +2306,17 @@ async function runCycloneDX(yargv) {
2290
2306
  }
2291
2307
  }
2292
2308
  function argvToArray(argv) {
2293
- if (argv['help']) return ['--help'];
2309
+ if (argv['help']) {
2310
+ return ['--help'];
2311
+ }
2294
2312
  const result = [];
2295
2313
  for (const {
2296
2314
  0: key,
2297
2315
  1: value
2298
2316
  } of Object.entries(argv)) {
2299
- if (key === '_' || key === '--') continue;
2317
+ if (key === '_' || key === '--') {
2318
+ continue;
2319
+ }
2300
2320
  if (key === 'babel' || key === 'install-deps' || key === 'validate') {
2301
2321
  // cdxgen documents no-babel, no-install-deps, and no-validate flags so
2302
2322
  // use them when relevant.
@@ -2315,6 +2335,32 @@ function argvToArray(argv) {
2315
2335
  return result;
2316
2336
  }
2317
2337
 
2338
+ const helpFlags = new Set(['--help', '-h']);
2339
+ function cmdFlagsToString(args) {
2340
+ const result = [];
2341
+ for (let i = 0, {
2342
+ length
2343
+ } = args; i < length; i += 1) {
2344
+ if (args[i].startsWith('--')) {
2345
+ // Check if the next item exists and is NOT another flag.
2346
+ if (i + 1 < length && !args[i + 1].startsWith('--')) {
2347
+ result.push(`${args[i]}=${args[i + 1]}`);
2348
+ i += 1;
2349
+ } else {
2350
+ result.push(args[i]);
2351
+ }
2352
+ }
2353
+ }
2354
+ return result.join(' ');
2355
+ }
2356
+ function cmdPrefixMessage(cmdName, text) {
2357
+ const cmdPrefix = cmdName ? `${cmdName}: ` : '';
2358
+ return `${cmdPrefix}${text}`;
2359
+ }
2360
+ function isHelpFlag(cmdArg) {
2361
+ return helpFlags.has(cmdArg);
2362
+ }
2363
+
2318
2364
  // import { meowOrExit } from '../../utils/meow-with-subcommands'
2319
2365
  const {
2320
2366
  DRY_RUN_BAIL_TEXT: DRY_RUN_BAIL_TEXT$v
@@ -2369,7 +2415,8 @@ const yargsConfig = {
2369
2415
  recurse: ['r'],
2370
2416
  'resolve-class': ['c'],
2371
2417
  type: ['t'],
2372
- version: ['v']
2418
+ version: ['v'],
2419
+ yes: ['y']
2373
2420
  },
2374
2421
  array: [{
2375
2422
  key: 'author',
@@ -2387,7 +2434,10 @@ const yargsConfig = {
2387
2434
  key: 'standard',
2388
2435
  type: 'string'
2389
2436
  }],
2390
- boolean: ['auto-compositions', 'babel', 'deep', 'evidence', 'fail-on-error', 'generate-key-and-sign', 'help', 'include-formulation', 'include-crypto', 'install-deps', 'print', 'required-only', 'server', 'validate', 'version'],
2437
+ boolean: ['auto-compositions', 'babel', 'deep', 'evidence', 'fail-on-error', 'generate-key-and-sign', 'help', 'include-formulation', 'include-crypto', 'install-deps', 'print', 'required-only', 'server', 'validate', 'version',
2438
+ // The --yes flag and -y alias map to the corresponding flag and alias of npx.
2439
+ // https://docs.npmjs.com/cli/v7/commands/npx#compatibility-with-older-npx-versions
2440
+ 'yes'],
2391
2441
  string: ['api-key', 'lifecycle', 'output', 'parent-project-id', 'profile', 'project-group', 'project-name', 'project-version', 'project-id', 'server-host', 'server-port', 'server-url', 'spec-version']
2392
2442
  };
2393
2443
  const config$w = {
@@ -2415,14 +2465,12 @@ async function run$w(argv, importMeta, {
2415
2465
  }) {
2416
2466
  const cli = meowOrExit({
2417
2467
  allowUnknownFlags: true,
2418
- argv: argv.filter(s => s !== '--help' && s !== '-h'),
2419
- // Don't let meow take over --help
2468
+ // Don't let meow take over --help.
2469
+ argv: argv.filter(a => !isHelpFlag(a)),
2420
2470
  config: config$w,
2421
2471
  importMeta,
2422
2472
  parentName
2423
2473
  });
2424
- //
2425
- //
2426
2474
  // if (cli.input.length)
2427
2475
  // logger.fail(
2428
2476
  // stripIndents`
@@ -2434,11 +2482,10 @@ async function run$w(argv, importMeta, {
2434
2482
  // return
2435
2483
  // }
2436
2484
 
2437
- // TODO: convert to meow
2485
+ // TODO: Convert to meow.
2438
2486
  const yargv = {
2439
2487
  ...yargsParse(argv, yargsConfig)
2440
- }; // as Record<string, unknown>;
2441
-
2488
+ };
2442
2489
  const unknown = yargv._;
2443
2490
  const {
2444
2491
  length: unknownLength
@@ -2451,13 +2498,13 @@ async function run$w(argv, importMeta, {
2451
2498
  logger.logger.fail(`Unknown ${words.pluralize('argument', unknownLength)}: ${yargv._.join(', ')}`);
2452
2499
  return;
2453
2500
  }
2454
- if (yargv.output === undefined) {
2455
- yargv.output = 'socket-cdx.json';
2456
- }
2457
2501
  if (cli.flags['dryRun']) {
2458
2502
  logger.logger.log(DRY_RUN_BAIL_TEXT$v);
2459
2503
  return;
2460
2504
  }
2505
+ if (yargv.output === undefined) {
2506
+ yargv.output = 'socket-cdx.json';
2507
+ }
2461
2508
  await runCycloneDX(yargv);
2462
2509
  }
2463
2510
 
@@ -2938,30 +2985,7 @@ async function getAlertsMapFromPnpmLockfile(lockfile, options) {
2938
2985
  return alertsByPkgId;
2939
2986
  }
2940
2987
 
2941
- function cmdFlagsToString(args) {
2942
- const result = [];
2943
- for (let i = 0, {
2944
- length
2945
- } = args; i < length; i += 1) {
2946
- if (args[i].startsWith('--')) {
2947
- // Check if the next item exists and is NOT another flag.
2948
- if (i + 1 < length && !args[i + 1].startsWith('--')) {
2949
- result.push(`${args[i]}=${args[i + 1]}`);
2950
- i += 1;
2951
- } else {
2952
- result.push(args[i]);
2953
- }
2954
- }
2955
- }
2956
- return result.join(' ');
2957
- }
2958
- function cmdPrefixMessage(cmdName, text) {
2959
- const cmdPrefix = cmdName ? `${cmdName}: ` : '';
2960
- return `${cmdPrefix}${text}`;
2961
- }
2962
-
2963
2988
  const {
2964
- SOCKET_CLI_SENTRY_BUILD,
2965
2989
  SOCKET_IPC_HANDSHAKE
2966
2990
  } = constants;
2967
2991
  function safeNpmInstall(options) {
@@ -2978,10 +3002,10 @@ function safeNpmInstall(options) {
2978
3002
  const useIpc = objects.isObject(ipc);
2979
3003
  const useDebug = debug.isDebug();
2980
3004
  const terminatorPos = args.indexOf('--');
2981
- const npmArgs = (terminatorPos === -1 ? args : args.slice(0, terminatorPos)).filter(a => !npm.isAuditFlag(a) && !npm.isFundFlag(a) && !npm.isProgressFlag(a));
3005
+ const binArgs = (terminatorPos === -1 ? args : args.slice(0, terminatorPos)).filter(a => !npm.isAuditFlag(a) && !npm.isFundFlag(a) && !npm.isProgressFlag(a));
2982
3006
  const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos);
2983
- const isSilent = !useDebug && !npmArgs.some(npm.isLoglevelFlag);
2984
- const logLevelArgs = isSilent ? ['--loglevel', 'error'] : [];
3007
+ const isSilent = !useDebug && !binArgs.some(npm.isLoglevelFlag);
3008
+ const logLevelArgs = isSilent ? ['--loglevel', 'silent'] : [];
2985
3009
  const spawnPromise = spawn.spawn(
2986
3010
  // Lazily access constants.execPath.
2987
3011
  constants.execPath, [
@@ -2989,20 +3013,19 @@ function safeNpmInstall(options) {
2989
3013
  ...constants.nodeHardenFlags,
2990
3014
  // Lazily access constants.nodeNoWarningsFlags.
2991
3015
  ...constants.nodeNoWarningsFlags,
2992
- // Lazily access constants.ENV[SOCKET_CLI_SENTRY_BUILD].
2993
- ...(constants.ENV[SOCKET_CLI_SENTRY_BUILD] ? ['--require',
3016
+ // Lazily access true.
3017
+ ...(['--require',
2994
3018
  // Lazily access constants.distInstrumentWithSentryPath.
2995
- constants.distInstrumentWithSentryPath] : []), '--require',
3019
+ constants.distInstrumentWithSentryPath] ), '--require',
2996
3020
  // Lazily access constants.distShadowNpmInjectPath.
2997
3021
  constants.distShadowNpmInjectPath, agentExecPath, 'install',
2998
3022
  // Avoid code paths for 'audit' and 'fund'.
2999
3023
  '--no-audit', '--no-fund',
3000
- // Add `--no-progress` flag to fix input being swallowed by the spinner
3001
- // when running the command with recent versions of npm.
3024
+ // Add '--no-progress' to fix input being swallowed by the npm spinner.
3002
3025
  '--no-progress',
3003
- // Add '--loglevel=error' if a loglevel flag is not provided and the
3026
+ // Add '--loglevel=silent' if a loglevel flag is not provided and the
3004
3027
  // SOCKET_CLI_DEBUG environment variable is not truthy.
3005
- ...logLevelArgs, ...npmArgs, ...otherArgs], {
3028
+ ...logLevelArgs, ...binArgs, ...otherArgs], {
3006
3029
  spinner,
3007
3030
  // Set stdio to include 'ipc'.
3008
3031
  // See https://github.com/nodejs/node/blob/v23.6.0/lib/child_process.js#L161-L166
@@ -3176,9 +3199,11 @@ async function pnpmFix(pkgEnvDetails, cwd, options) {
3176
3199
  const {
3177
3200
  BINARY_LOCK_EXT,
3178
3201
  BUN: BUN$5,
3202
+ HIDDEN_PACKAGE_LOCK_JSON,
3179
3203
  LOCK_EXT: LOCK_EXT$1,
3180
3204
  NPM: NPM$b,
3181
3205
  NPM_BUGGY_OVERRIDES_PATCHED_VERSION: NPM_BUGGY_OVERRIDES_PATCHED_VERSION$1,
3206
+ PACKAGE_JSON,
3182
3207
  PNPM: PNPM$8,
3183
3208
  VLT: VLT$5,
3184
3209
  YARN,
@@ -3280,8 +3305,8 @@ async function detectPackageEnvironment({
3280
3305
  cwd
3281
3306
  });
3282
3307
  let lockName = lockPath ? path.basename(lockPath) : undefined;
3283
- const isHiddenLockFile = lockName === '.package-lock.json';
3284
- const pkgJsonPath = lockPath ? path.resolve(lockPath, `${isHiddenLockFile ? '../' : ''}../package.json`) : await shadowNpmInject.findUp('package.json', {
3308
+ const isHiddenLockFile = lockName === HIDDEN_PACKAGE_LOCK_JSON;
3309
+ const pkgJsonPath = lockPath ? path.resolve(lockPath, `${isHiddenLockFile ? '../' : ''}../${PACKAGE_JSON}`) : await shadowNpmInject.findUp(PACKAGE_JSON, {
3285
3310
  cwd
3286
3311
  });
3287
3312
  const pkgPath = pkgJsonPath && fs.existsSync(pkgJsonPath) ? path.dirname(pkgJsonPath) : undefined;
@@ -3413,7 +3438,7 @@ async function detectAndValidatePackageEnvironment(cwd, options) {
3413
3438
  return;
3414
3439
  }
3415
3440
  if (details.pkgPath === undefined) {
3416
- logger?.fail(cmdPrefixMessage(cmdName, 'No package.json found'));
3441
+ logger?.fail(cmdPrefixMessage(cmdName, `No ${PACKAGE_JSON} found`));
3417
3442
  return;
3418
3443
  }
3419
3444
  if (prod && (details.agent === BUN$5 || details.agent === YARN_BERRY$5)) {
@@ -3430,7 +3455,7 @@ const {
3430
3455
  NPM: NPM$a,
3431
3456
  PNPM: PNPM$7
3432
3457
  } = constants;
3433
- const CMD_NAME$1 = 'socket fix';
3458
+ const CMD_NAME$2 = 'socket fix';
3434
3459
  async function runFix() {
3435
3460
  // Lazily access constants.spinner.
3436
3461
  const {
@@ -3439,7 +3464,7 @@ async function runFix() {
3439
3464
  spinner.start();
3440
3465
  const cwd = process.cwd();
3441
3466
  const pkgEnvDetails = await detectAndValidatePackageEnvironment(cwd, {
3442
- cmdName: CMD_NAME$1,
3467
+ cmdName: CMD_NAME$2,
3443
3468
  logger: logger.logger
3444
3469
  });
3445
3470
  if (!pkgEnvDetails) {
@@ -3930,9 +3955,11 @@ async function convertGradleToMaven(target, bin, _out, verbose, gradleOpts) {
3930
3955
  logger.logger.groupEnd();
3931
3956
  }
3932
3957
  try {
3933
- // Run sbt with the init script we provide which should yield zero or more pom files.
3934
- // We have to figure out where to store those pom files such that we can upload them and predict them through the GitHub API.
3935
- // We could do a .socket folder. We could do a socket.pom.gz with all the poms, although I'd prefer something plain-text if it is to be committed.
3958
+ // Run sbt with the init script we provide which should yield zero or more
3959
+ // pom files. We have to figure out where to store those pom files such that
3960
+ // we can upload them and predict them through the GitHub API. We could do a
3961
+ // .socket folder. We could do a socket.pom.gz with all the poms, although
3962
+ // I'd prefer something plain-text if it is to be committed.
3936
3963
 
3937
3964
  // Note: init.gradle will be exported by .config/rollup.dist.config.mjs
3938
3965
  const initLocation = path.join(constants.rootDistPath, 'init.gradle');
@@ -3979,7 +4006,7 @@ async function convertGradleToMaven(target, bin, _out, verbose, gradleOpts) {
3979
4006
  // // Move the pom file to ...? initial cwd? loc will be an absolute path, or dump to stdout
3980
4007
  // if (out === '-') {
3981
4008
  // spinner.start('Result:\n```')
3982
- // spinner.log(await safeReadFile(loc, 'utf8'))
4009
+ // spinner.log(await safeReadFile(loc))
3983
4010
  // spinner.log('```')
3984
4011
  // spinner.successAndStop(`OK`)
3985
4012
  // } else {
@@ -4214,7 +4241,7 @@ async function convertSbtToMaven(target, bin, out, verbose, sbtOpts) {
4214
4241
  // TODO: maybe we can add an option to target a specific file to dump to stdout
4215
4242
  if (out === '-' && poms.length === 1) {
4216
4243
  logger.logger.log('Result:\n```');
4217
- logger.logger.log(await shadowNpmInject.safeReadFile(poms[0], 'utf8'));
4244
+ logger.logger.log(await shadowNpmInject.safeReadFile(poms[0]));
4218
4245
  logger.logger.log('```');
4219
4246
  logger.logger.success(`OK`);
4220
4247
  } else if (out === '-') {
@@ -4933,7 +4960,7 @@ async function getWorkspaceGlobs(agent, pkgPath, pkgJson) {
4933
4960
  if (agent === PNPM$4) {
4934
4961
  for (const workspacePath of [path.join(pkgPath, `${PNPM_WORKSPACE}.yaml`), path.join(pkgPath, `${PNPM_WORKSPACE}.yml`)]) {
4935
4962
  // eslint-disable-next-line no-await-in-loop
4936
- const yml = await shadowNpmInject.safeReadFile(workspacePath, 'utf8');
4963
+ const yml = await shadowNpmInject.safeReadFile(workspacePath);
4937
4964
  if (yml) {
4938
4965
  try {
4939
4966
  workspacePatterns = yaml.parse(yml)?.packages;
@@ -5141,34 +5168,6 @@ async function lsYarnClassic(agentExecPath, cwd) {
5141
5168
  }
5142
5169
  const lsByAgent = new Map([[BUN$1, lsBun], [NPM$3, lsNpm], [PNPM$2, lsPnpm], [VLT$1, lsVlt], [YARN_BERRY$1, lsYarnBerry], [YARN_CLASSIC$2, lsYarnClassic]]);
5143
5170
 
5144
- const {
5145
- NPM_BUGGY_OVERRIDES_PATCHED_VERSION
5146
- } = constants;
5147
- async function updateLockfile(pkgEnvDetails, options) {
5148
- const {
5149
- cmdName = '',
5150
- logger,
5151
- spinner
5152
- } = {
5153
- __proto__: null,
5154
- ...options
5155
- };
5156
- spinner?.start(`Updating ${pkgEnvDetails.lockName}...`);
5157
- try {
5158
- await runAgentInstall(pkgEnvDetails, {
5159
- spinner
5160
- });
5161
- spinner?.stop();
5162
- if (pkgEnvDetails.features.npmBuggyOverrides) {
5163
- logger?.log(`💡 Re-run ${cmdName ? `${cmdName} ` : ''}whenever ${pkgEnvDetails.lockName} changes.\n This can be skipped for ${pkgEnvDetails.agent} >=${NPM_BUGGY_OVERRIDES_PATCHED_VERSION}.`);
5164
- }
5165
- } catch (e) {
5166
- spinner?.stop();
5167
- logger?.fail(cmdPrefixMessage(cmdName, `${pkgEnvDetails.agent} install failed to update ${pkgEnvDetails.lockName}`));
5168
- logger?.error(e);
5169
- }
5170
- }
5171
-
5172
5171
  const {
5173
5172
  BUN,
5174
5173
  NPM: NPM$2,
@@ -5179,7 +5178,6 @@ const {
5179
5178
  YARN_BERRY,
5180
5179
  YARN_CLASSIC: YARN_CLASSIC$1
5181
5180
  } = constants;
5182
- const PNPM_FIELD_NAME = PNPM$1;
5183
5181
  const depFields = ['dependencies', 'devDependencies', 'peerDependencies', 'peerDependenciesMeta', 'optionalDependencies', 'bundleDependencies'];
5184
5182
  function getEntryIndexes(entries, keys) {
5185
5183
  return keys.map(n => entries.findIndex(p => p[0] === n)).filter(n => n !== -1).sort((a, b) => a - b);
@@ -5190,26 +5188,30 @@ function getLowestEntryIndex(entries, keys) {
5190
5188
  function getHighestEntryIndex(entries, keys) {
5191
5189
  return getEntryIndexes(entries, keys).at(-1) ?? -1;
5192
5190
  }
5193
- function updatePkgJson(editablePkgJson, field, value) {
5191
+ function updatePkgJsonField(editablePkgJson, field, value) {
5194
5192
  const {
5195
5193
  content: pkgJson
5196
5194
  } = editablePkgJson;
5197
5195
  const oldValue = pkgJson[field];
5198
5196
  if (oldValue) {
5199
5197
  // The field already exists so we simply update the field value.
5200
- if (field === PNPM_FIELD_NAME) {
5198
+ if (field === PNPM$1) {
5199
+ const isPnpmObj = objects.isObject(oldValue);
5201
5200
  if (objects.hasKeys(value)) {
5202
5201
  editablePkgJson.update({
5203
5202
  [field]: {
5204
- ...(objects.isObject(oldValue) ? oldValue : {}),
5205
- overrides: value
5203
+ ...(isPnpmObj ? oldValue : {}),
5204
+ overrides: {
5205
+ ...(isPnpmObj ? oldValue[OVERRIDES] : {}),
5206
+ ...value
5207
+ }
5206
5208
  }
5207
5209
  });
5208
5210
  } else {
5209
5211
  // Properties with undefined values are omitted when saved as JSON.
5210
- editablePkgJson.update(objects.hasKeys(pkgJson[field]) ? {
5212
+ editablePkgJson.update(objects.hasKeys(oldValue) ? {
5211
5213
  [field]: {
5212
- ...(objects.isObject(oldValue) ? oldValue : {}),
5214
+ ...(isPnpmObj ? oldValue : {}),
5213
5215
  overrides: undefined
5214
5216
  }
5215
5217
  } : {
@@ -5228,7 +5230,7 @@ function updatePkgJson(editablePkgJson, field, value) {
5228
5230
  }
5229
5231
  return;
5230
5232
  }
5231
- if ((field === OVERRIDES || field === PNPM_FIELD_NAME || field === RESOLUTIONS) && !objects.hasKeys(value)) {
5233
+ if ((field === OVERRIDES || field === PNPM$1 || field === RESOLUTIONS) && !objects.hasKeys(value)) {
5232
5234
  return;
5233
5235
  }
5234
5236
  // Since the field doesn't exist we want to insert it into the package.json
@@ -5246,7 +5248,7 @@ function updatePkgJson(editablePkgJson, field, value) {
5246
5248
  } else if (field === RESOLUTIONS) {
5247
5249
  isPlacingHigher = true;
5248
5250
  insertIndex = getHighestEntryIndex(entries, [...depFields, OVERRIDES, PNPM$1]);
5249
- } else if (field === PNPM_FIELD_NAME) {
5251
+ } else if (field === PNPM$1) {
5250
5252
  insertIndex = getLowestEntryIndex(entries, [OVERRIDES, RESOLUTIONS]);
5251
5253
  if (insertIndex === -1) {
5252
5254
  isPlacingHigher = true;
@@ -5265,26 +5267,28 @@ function updatePkgJson(editablePkgJson, field, value) {
5265
5267
  } else if (isPlacingHigher) {
5266
5268
  insertIndex += 1;
5267
5269
  }
5268
- entries.splice(insertIndex, 0, [field, value]);
5270
+ entries.splice(insertIndex, 0, [field, field === PNPM$1 ? {
5271
+ [OVERRIDES]: value
5272
+ } : value]);
5269
5273
  editablePkgJson.fromJSON(`${JSON.stringify(Object.fromEntries(entries), null, 2)}\n`);
5270
5274
  }
5271
- function updateOverrides(editablePkgJson, overrides) {
5272
- updatePkgJson(editablePkgJson, OVERRIDES, overrides);
5275
+ function updateOverridesField(editablePkgJson, overrides) {
5276
+ updatePkgJsonField(editablePkgJson, OVERRIDES, overrides);
5273
5277
  }
5274
- function updateResolutions(editablePkgJson, overrides) {
5275
- updatePkgJson(editablePkgJson, RESOLUTIONS, overrides);
5278
+ function updateResolutionsField(editablePkgJson, overrides) {
5279
+ updatePkgJsonField(editablePkgJson, RESOLUTIONS, overrides);
5276
5280
  }
5277
- function pnpmUpdatePkgJson(editablePkgJson, overrides) {
5278
- updatePkgJson(editablePkgJson, PNPM_FIELD_NAME, overrides);
5281
+ function updatePnpmField(editablePkgJson, overrides) {
5282
+ updatePkgJsonField(editablePkgJson, PNPM$1, overrides);
5279
5283
  }
5280
- const updateManifestByAgent = new Map([[BUN, updateResolutions], [NPM$2, updateOverrides], [PNPM$1, pnpmUpdatePkgJson], [VLT, updateOverrides], [YARN_BERRY, updateResolutions], [YARN_CLASSIC$1, updateResolutions]]);
5284
+ const updateManifestByAgent = new Map([[BUN, updateResolutionsField], [NPM$2, updateOverridesField], [PNPM$1, updatePnpmField], [VLT, updateOverridesField], [YARN_BERRY, updateResolutionsField], [YARN_CLASSIC$1, updateResolutionsField]]);
5281
5285
 
5282
5286
  const {
5283
5287
  NPM: NPM$1,
5284
5288
  PNPM,
5285
5289
  YARN_CLASSIC
5286
5290
  } = constants;
5287
- const CMD_NAME = 'socket optimize';
5291
+ const CMD_NAME$1 = 'socket optimize';
5288
5292
  const manifestNpmOverrides = registry.getManifestData(NPM$1);
5289
5293
  async function addOverrides(pkgPath, pkgEnvDetails, options) {
5290
5294
  const {
@@ -5322,24 +5326,17 @@ async function addOverrides(pkgPath, pkgEnvDetails, options) {
5322
5326
  const {
5323
5327
  content: pkgJson
5324
5328
  } = editablePkgJson;
5325
- const isRoot = pkgPath === rootPath;
5326
- const isLockScanned = isRoot && !prod;
5327
5329
  const workspaceName = path.relative(rootPath, pkgPath);
5328
5330
  const workspaceGlobs = await getWorkspaceGlobs(agent, pkgPath, pkgJson);
5331
+ const isRoot = pkgPath === rootPath;
5332
+ const isLockScanned = isRoot && !prod;
5329
5333
  const isWorkspace = !!workspaceGlobs;
5330
- if (isWorkspace && agent === PNPM && npmExecPath === NPM$1 && !state.warnedPnpmWorkspaceRequiresNpm) {
5334
+ if (isWorkspace && agent === PNPM &&
5335
+ // npmExecPath will === the agent name IF it CANNOT be resolved.
5336
+ npmExecPath === NPM$1 && !state.warnedPnpmWorkspaceRequiresNpm) {
5331
5337
  state.warnedPnpmWorkspaceRequiresNpm = true;
5332
- logger?.warn(cmdPrefixMessage(CMD_NAME, 'pnpm workspace support requires `npm ls`, falling back to `pnpm list`'));
5338
+ logger?.warn(cmdPrefixMessage(CMD_NAME$1, `${agent} workspace support requires \`npm ls\`, falling back to \`${agent} list\``));
5333
5339
  }
5334
- const thingToScan = isLockScanned ? lockSrc : await lsByAgent.get(agent)(agentExecPath, pkgPath, {
5335
- npmExecPath
5336
- });
5337
- // The AgentDepsIncludesFn and AgentLockIncludesFn types overlap in their
5338
- // first two parameters. AgentLockIncludesFn accepts an optional third
5339
- // parameter which AgentDepsIncludesFn will ignore so we cast thingScanner
5340
- // as an AgentLockIncludesFn type.
5341
- const thingScanner = isLockScanned ? lockfileIncludesByAgent.get(agent) : depsIncludesByAgent.get(agent);
5342
- const depEntries = getDependencyEntries(pkgJson);
5343
5340
  const overridesDataObjects = [];
5344
5341
  if (pkgJson['private'] || isWorkspace) {
5345
5342
  overridesDataObjects.push(overridesDataByAgent.get(agent)(pkgJson));
@@ -5348,10 +5345,12 @@ async function addOverrides(pkgPath, pkgEnvDetails, options) {
5348
5345
  }
5349
5346
  spinner?.setText(`Adding overrides${workspaceName ? ` to ${workspaceName}` : ''}...`);
5350
5347
  const depAliasMap = new Map();
5348
+ const depEntries = getDependencyEntries(pkgJson);
5351
5349
  const nodeRange = `>=${pkgEnvDetails.minimumNodeVersion}`;
5352
5350
  const manifestEntries = manifestNpmOverrides.filter(({
5353
5351
  1: data
5354
5352
  }) => semver.satisfies(semver.coerce(data.engines.node), nodeRange));
5353
+
5355
5354
  // Chunk package names to process them in parallel 3 at a time.
5356
5355
  await promises.pEach(manifestEntries, 3, async ({
5357
5356
  1: data
@@ -5388,6 +5387,14 @@ async function addOverrides(pkgPath, pkgEnvDetails, options) {
5388
5387
  }
5389
5388
  }
5390
5389
  if (isRoot) {
5390
+ // The AgentDepsIncludesFn and AgentLockIncludesFn types overlap in their
5391
+ // first two parameters. AgentLockIncludesFn accepts an optional third
5392
+ // parameter which AgentDepsIncludesFn will ignore so we cast thingScanner
5393
+ // as an AgentLockIncludesFn type.
5394
+ const thingScanner = isLockScanned ? lockfileIncludesByAgent.get(agent) : depsIncludesByAgent.get(agent);
5395
+ const thingToScan = isLockScanned ? lockSrc : await lsByAgent.get(agent)(agentExecPath, pkgPath, {
5396
+ npmExecPath
5397
+ });
5391
5398
  // Chunk package names to process them in parallel 3 at a time.
5392
5399
  await promises.pEach(overridesDataObjects, 3, async ({
5393
5400
  overrides,
@@ -5464,6 +5471,44 @@ async function addOverrides(pkgPath, pkgEnvDetails, options) {
5464
5471
  }
5465
5472
  return state;
5466
5473
  }
5474
+
5475
+ const {
5476
+ NPM_BUGGY_OVERRIDES_PATCHED_VERSION
5477
+ } = constants;
5478
+ async function updateLockfile(pkgEnvDetails, options) {
5479
+ const {
5480
+ cmdName = '',
5481
+ logger,
5482
+ spinner
5483
+ } = {
5484
+ __proto__: null,
5485
+ ...options
5486
+ };
5487
+ const isSpinning = !!spinner?.isSpinning;
5488
+ if (!isSpinning) {
5489
+ spinner?.start();
5490
+ }
5491
+ spinner?.setText(`Updating ${pkgEnvDetails.lockName}...`);
5492
+ try {
5493
+ await runAgentInstall(pkgEnvDetails, {
5494
+ spinner
5495
+ });
5496
+ if (pkgEnvDetails.features.npmBuggyOverrides) {
5497
+ logger?.log(`💡 Re-run ${cmdName ? `${cmdName} ` : ''}whenever ${pkgEnvDetails.lockName} changes.\n This can be skipped for ${pkgEnvDetails.agent} >=${NPM_BUGGY_OVERRIDES_PATCHED_VERSION}.`);
5498
+ }
5499
+ } catch (e) {
5500
+ spinner?.stop();
5501
+ logger?.fail(cmdPrefixMessage(cmdName, `${pkgEnvDetails.agent} install failed to update ${pkgEnvDetails.lockName}`));
5502
+ logger?.error(e);
5503
+ }
5504
+ if (isSpinning) {
5505
+ spinner?.start();
5506
+ } else {
5507
+ spinner?.stop();
5508
+ }
5509
+ }
5510
+
5511
+ const CMD_NAME = 'socket optimize';
5467
5512
  function createActionMessage(verb, overrideCount, workspaceCount) {
5468
5513
  return `${verb} ${overrideCount} Socket.dev optimized ${words.pluralize('override', overrideCount)}${workspaceCount ? ` in ${workspaceCount} ${words.pluralize('workspace', workspaceCount)}` : ''}`;
5469
5514
  }
@@ -5487,10 +5532,17 @@ async function applyOptimization(cwd, pin, prod) {
5487
5532
  prod,
5488
5533
  spinner
5489
5534
  });
5490
- spinner.stop();
5491
5535
  const addedCount = state.added.size;
5492
5536
  const updatedCount = state.updated.size;
5493
5537
  const pkgJsonChanged = addedCount > 0 || updatedCount > 0;
5538
+ if (pkgJsonChanged || pkgEnvDetails.features.npmBuggyOverrides) {
5539
+ await updateLockfile(pkgEnvDetails, {
5540
+ cmdName: CMD_NAME,
5541
+ logger: logger.logger,
5542
+ spinner
5543
+ });
5544
+ }
5545
+ spinner.stop();
5494
5546
  if (pkgJsonChanged) {
5495
5547
  if (updatedCount > 0) {
5496
5548
  logger.logger?.log(`${createActionMessage('Updated', updatedCount, state.updatedInWorkspaces.size)}${addedCount ? '.' : '🚀'}`);
@@ -5501,13 +5553,6 @@ async function applyOptimization(cwd, pin, prod) {
5501
5553
  } else {
5502
5554
  logger.logger?.log('Congratulations! Already Socket.dev optimized 🎉');
5503
5555
  }
5504
- if (pkgJsonChanged || pkgEnvDetails.features.npmBuggyOverrides) {
5505
- await updateLockfile(pkgEnvDetails, {
5506
- cmdName: CMD_NAME,
5507
- logger: logger.logger,
5508
- spinner
5509
- });
5510
- }
5511
5556
  }
5512
5557
 
5513
5558
  const {
@@ -8240,15 +8285,15 @@ async function run(argv, importMeta, {
8240
8285
  }
8241
8286
 
8242
8287
  const {
8243
- SOCKET_CLI_BIN_NAME,
8244
- rootPkgJsonPath
8288
+ SOCKET_CLI_BIN_NAME
8245
8289
  } = constants;
8246
8290
 
8247
8291
  // TODO: Add autocompletion using https://socket.dev/npm/package/omelette
8248
8292
  void (async () => {
8249
8293
  await updateNotifier({
8250
8294
  name: SOCKET_CLI_BIN_NAME,
8251
- version: require(rootPkgJsonPath).version,
8295
+ // The '@rollup/plugin-replace' will replace "process.env['INLINED_SOCKET_CLI_VERSION']".
8296
+ version: "0.14.61",
8252
8297
  ttl: 86_400_000 /* 24 hours in milliseconds */
8253
8298
  });
8254
8299
  try {
@@ -8315,5 +8360,5 @@ void (async () => {
8315
8360
  await shadowNpmInject.captureException(e);
8316
8361
  }
8317
8362
  })();
8318
- //# debugId=c1c67343-d5ad-409c-8f8e-9236e0fb545a
8363
+ //# debugId=89426f9d-4cbc-4ef9-8acb-dd541c5afe36
8319
8364
  //# sourceMappingURL=cli.js.map