@socketsecurity/cli 0.14.3 → 0.14.5

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/dist/cli.js ADDED
@@ -0,0 +1,4701 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var vendor = require('./vendor.js');
5
+ var require$$0 = require('node:fs');
6
+ var require$$1 = require('node:path');
7
+ var require$$2$5 = require('node:url');
8
+ var require$$6 = require('pony-cause');
9
+ var require$$1$1 = require('@npmcli/promise-spawn');
10
+ var require$$5 = require('yargs-parser');
11
+ var sdk = require('./sdk.js');
12
+ var require$$1$2 = require('@inquirer/prompts');
13
+ var require$$3$2 = require('@npmcli/package-json');
14
+ var require$$4 = require('@socketsecurity/registry');
15
+ var require$$1$3 = require('@socketregistry/hyrious__bun.lockb');
16
+ var require$$3 = require('browserslist');
17
+ var require$$3$1 = require('semver');
18
+ var require$$5$1 = require('which');
19
+ var require$$2 = require('@apideck/better-ajv-errors');
20
+ var require$$3$3 = require('@socketsecurity/config');
21
+ var pathResolve = require('./path-resolve.js');
22
+ var require$$2$1 = require('node:os');
23
+ var require$$3$4 = require('node:readline');
24
+ var require$$0$1 = require('node:process');
25
+ var require$$2$2 = require('node:readline/promises');
26
+ var require$$2$3 = require('chalk-table');
27
+ var require$$2$4 = require('blessed');
28
+ var require$$3$5 = require('blessed-contrib');
29
+ var require$$0$2 = require('node:util');
30
+
31
+ var cli$1 = {};
32
+
33
+ var cli = {};
34
+
35
+ var commands = {};
36
+
37
+ var cdxgen = {};
38
+
39
+ var _interopRequireDefault$s = vendor.interopRequireDefault.default;
40
+ Object.defineProperty(cdxgen, "__esModule", {
41
+ value: true
42
+ });
43
+ cdxgen.cdxgen = void 0;
44
+ var _nodeFs$5 = require$$0;
45
+ var _nodePath$7 = require$$1;
46
+ var _promiseSpawn$6 = require$$1$1;
47
+ var _chalk$j = _interopRequireDefault$s(vendor.source);
48
+ var _yargsParser = require$$5;
49
+ const distPath$4 = __dirname;
50
+ const {
51
+ execPath
52
+ } = process;
53
+ const rootPath$1 = _nodePath$7.resolve(distPath$4, '..');
54
+ const binPath = _nodePath$7.join(rootPath$1, 'node_modules/.bin');
55
+ const cdxgenBinPath = _nodePath$7.join(binPath, 'cdxgen');
56
+ const synpBinPath = _nodePath$7.join(binPath, 'synp');
57
+ const {
58
+ SBOM_SIGN_ALGORITHM,
59
+ // Algorithm. Example: RS512
60
+ SBOM_SIGN_PRIVATE_KEY,
61
+ // Location to the RSA private key
62
+ SBOM_SIGN_PUBLIC_KEY // Optional. Location to the RSA public key
63
+ } = process.env;
64
+ const toLower = arg => arg.toLowerCase();
65
+ const arrayToLower = arg => arg.map(toLower);
66
+ const nodejsPlatformTypes = ['javascript', 'js', 'nodejs', 'npm', 'pnpm', 'ts', 'tsx', 'typescript'];
67
+ const yargsConfig = {
68
+ configuration: {
69
+ 'camel-case-expansion': false,
70
+ 'strip-aliased': true,
71
+ 'parse-numbers': false,
72
+ 'populate--': true,
73
+ 'unknown-options-as-args': true
74
+ },
75
+ coerce: {
76
+ author: arrayToLower,
77
+ filter: arrayToLower,
78
+ only: arrayToLower,
79
+ profile: toLower,
80
+ standard: arrayToLower,
81
+ type: toLower
82
+ },
83
+ default: {
84
+ //author: ['OWASP Foundation'],
85
+ //'auto-compositions': true,
86
+ //babel: true,
87
+ //evidence: false,
88
+ //'include-crypto': false,
89
+ //'include-formulation': false,
90
+ //'install-deps': true,
91
+ //output: 'bom.json',
92
+ //profile: 'generic',
93
+ //'project-version': '',
94
+ //recurse: true,
95
+ //'server-host': '127.0.0.1',
96
+ //'server-port': '9090',
97
+ //'spec-version': '1.5',
98
+ type: 'js'
99
+ //validate: true,
100
+ },
101
+ alias: {
102
+ help: ['h'],
103
+ output: ['o'],
104
+ print: ['p'],
105
+ recurse: ['r'],
106
+ 'resolve-class': ['c'],
107
+ type: ['t'],
108
+ version: ['v']
109
+ },
110
+ array: [{
111
+ key: 'author',
112
+ type: 'string'
113
+ }, {
114
+ key: 'exclude',
115
+ type: 'string'
116
+ }, {
117
+ key: 'filter',
118
+ type: 'string'
119
+ }, {
120
+ key: 'only',
121
+ type: 'string'
122
+ }, {
123
+ key: 'standard',
124
+ type: 'string'
125
+ }],
126
+ 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'],
127
+ string: ['api-key', 'output', 'parent-project-id', 'profile', 'project-group', 'project-name', 'project-version', 'project-id', 'server-host', 'server-port', 'server-url', 'spec-version']
128
+ };
129
+ function argvToArray(argv) {
130
+ if (argv['help']) return ['--help'];
131
+ const result = [];
132
+ for (const {
133
+ 0: key,
134
+ 1: value
135
+ } of Object.entries(argv)) {
136
+ if (key === '_' || key === '--') continue;
137
+ if (key === 'babel' || key === 'install-deps' || key === 'validate') {
138
+ // cdxgen documents no-babel, no-install-deps, and no-validate flags so
139
+ // use them when relevant.
140
+ result.push(`--${value ? key : `no-${key}`}`);
141
+ } else if (value === true) {
142
+ result.push(`--${key}`);
143
+ } else if (typeof value === 'string') {
144
+ result.push(`--${key}=${value}`);
145
+ } else if (Array.isArray(value)) {
146
+ result.push(`--${key}`, ...value.map(String));
147
+ }
148
+ }
149
+ if (argv['--']) {
150
+ result.push('--', ...argv['--']);
151
+ }
152
+ return result;
153
+ }
154
+ cdxgen.cdxgen = {
155
+ description: 'Create an SBOM with CycloneDX generator (cdxgen)',
156
+ async run(argv_) {
157
+ const yargv = {
158
+ __proto__: null,
159
+ ..._yargsParser(argv_, yargsConfig)
160
+ };
161
+ const unknown = yargv._;
162
+ const {
163
+ length: unknownLength
164
+ } = unknown;
165
+ if (unknownLength) {
166
+ console.error(`Unknown argument${unknownLength > 1 ? 's' : ''}: ${yargv._.join(', ')}`);
167
+ process.exitCode = 1;
168
+ return;
169
+ }
170
+ let cleanupPackageLock = false;
171
+ if (yargv.type !== 'yarn' && nodejsPlatformTypes.includes(yargv.type) && (0, _nodeFs$5.existsSync)('./yarn.lock')) {
172
+ if ((0, _nodeFs$5.existsSync)('./package-lock.json')) {
173
+ yargv.type = 'npm';
174
+ } else {
175
+ // Use synp to create a package-lock.json from the yarn.lock,
176
+ // based on the node_modules folder, for a more accurate SBOM.
177
+ try {
178
+ await _promiseSpawn$6(execPath, [await _nodeFs$5.promises.realpath(synpBinPath), '--source-file', './yarn.lock'], {
179
+ shell: true
180
+ });
181
+ yargv.type = 'npm';
182
+ cleanupPackageLock = true;
183
+ } catch {}
184
+ }
185
+ }
186
+ if (yargv.output === undefined) {
187
+ yargv.output = 'socket-cdx.json';
188
+ }
189
+ await _promiseSpawn$6(execPath, [await _nodeFs$5.promises.realpath(cdxgenBinPath), ...argvToArray(yargv)], {
190
+ env: {
191
+ NODE_ENV: '',
192
+ SBOM_SIGN_ALGORITHM,
193
+ SBOM_SIGN_PRIVATE_KEY,
194
+ SBOM_SIGN_PUBLIC_KEY
195
+ },
196
+ shell: true,
197
+ stdio: 'inherit'
198
+ });
199
+ if (cleanupPackageLock) {
200
+ try {
201
+ await _nodeFs$5.promises.unlink('./package-lock.json');
202
+ } catch {}
203
+ }
204
+ const fullOutputPath = _nodePath$7.join(process.cwd(), yargv.output);
205
+ if ((0, _nodeFs$5.existsSync)(fullOutputPath)) {
206
+ console.log(_chalk$j.default.cyanBright(`${yargv.output} created!`));
207
+ }
208
+ }
209
+ };
210
+
211
+ var info$1 = {};
212
+
213
+ var flags$1 = {};
214
+
215
+ Object.defineProperty(flags$1, "__esModule", {
216
+ value: true
217
+ });
218
+ flags$1.validationFlags = flags$1.outputFlags = flags$1.commandFlags = void 0;
219
+ flags$1.commandFlags = {
220
+ enable: {
221
+ type: 'boolean',
222
+ default: false,
223
+ description: 'Enables the Socket npm/npx wrapper'
224
+ },
225
+ disable: {
226
+ type: 'boolean',
227
+ default: false,
228
+ description: 'Disables the Socket npm/npx wrapper'
229
+ }
230
+ };
231
+ flags$1.outputFlags = {
232
+ json: {
233
+ type: 'boolean',
234
+ shortFlag: 'j',
235
+ default: false,
236
+ description: 'Output result as json'
237
+ },
238
+ markdown: {
239
+ type: 'boolean',
240
+ shortFlag: 'm',
241
+ default: false,
242
+ description: 'Output result as markdown'
243
+ }
244
+ };
245
+ flags$1.validationFlags = {
246
+ all: {
247
+ type: 'boolean',
248
+ default: false,
249
+ description: 'Include all issues'
250
+ },
251
+ strict: {
252
+ type: 'boolean',
253
+ default: false,
254
+ description: 'Exits with an error code if any matching issues are found'
255
+ }
256
+ };
257
+
258
+ var apiHelpers = {};
259
+
260
+ var _interopRequireDefault$r = vendor.interopRequireDefault.default;
261
+ Object.defineProperty(apiHelpers, "__esModule", {
262
+ value: true
263
+ });
264
+ apiHelpers.handleAPIError = handleAPIError;
265
+ apiHelpers.handleApiCall = handleApiCall;
266
+ apiHelpers.handleUnsuccessfulApiResponse = handleUnsuccessfulApiResponse;
267
+ apiHelpers.queryAPI = queryAPI;
268
+ var _chalk$i = _interopRequireDefault$r(vendor.source);
269
+ var _ponyCause$4 = require$$6;
270
+ var _errors$l = sdk.errors;
271
+ var _constants = sdk.constants;
272
+ function handleUnsuccessfulApiResponse(_name, result, spinner) {
273
+ const resultError = 'error' in result && result.error && typeof result.error === 'object' ? result.error : {};
274
+ const message = 'message' in resultError && typeof resultError.message === 'string' ? resultError.message : 'No error message returned';
275
+ if (result.status === 401 || result.status === 403) {
276
+ spinner.stop();
277
+ throw new _errors$l.AuthError(message);
278
+ }
279
+ spinner.fail(_chalk$i.default.white.bgRed('API returned an error:') + ' ' + message);
280
+ process.exit(1);
281
+ }
282
+ async function handleApiCall(value, description) {
283
+ let result;
284
+ try {
285
+ result = await value;
286
+ } catch (cause) {
287
+ throw new _ponyCause$4.ErrorWithCause(`Failed ${description}`, {
288
+ cause
289
+ });
290
+ }
291
+ return result;
292
+ }
293
+ async function handleAPIError(code) {
294
+ if (code === 400) {
295
+ return `One of the options passed might be incorrect.`;
296
+ } else if (code === 403) {
297
+ return `You might be trying to access an organization that is not linked to the API key you are logged in with.`;
298
+ }
299
+ }
300
+ async function queryAPI(path, apiKey) {
301
+ return await fetch(`${_constants.API_V0_URL}/${path}`, {
302
+ method: 'GET',
303
+ headers: {
304
+ Authorization: 'Basic ' + btoa(`${apiKey}:${apiKey}`)
305
+ }
306
+ });
307
+ }
308
+
309
+ var formatIssues = {};
310
+
311
+ var objects = {};
312
+
313
+ Object.defineProperty(objects, "__esModule", {
314
+ value: true
315
+ });
316
+ objects.getOwn = getOwn;
317
+ objects.hasOwn = hasOwn;
318
+ objects.isObjectObject = isObjectObject;
319
+ objects.objectSome = objectSome;
320
+ objects.pick = pick;
321
+ function getOwn(obj, propKey) {
322
+ if (obj === null || obj === undefined) return undefined;
323
+ return Object.hasOwn(obj, propKey) ? obj[propKey] : undefined;
324
+ }
325
+ function hasOwn(obj, propKey) {
326
+ if (obj === null || obj === undefined) return false;
327
+ return Object.hasOwn(obj, propKey);
328
+ }
329
+ function isObjectObject(value) {
330
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
331
+ }
332
+ function objectSome(obj) {
333
+ for (const key in obj) {
334
+ if (obj[key]) {
335
+ return true;
336
+ }
337
+ }
338
+ return false;
339
+ }
340
+ function pick(input, keys) {
341
+ const result = {};
342
+ for (const key of keys) {
343
+ result[key] = input[key];
344
+ }
345
+ return result;
346
+ }
347
+
348
+ Object.defineProperty(formatIssues, "__esModule", {
349
+ value: true
350
+ });
351
+ formatIssues.formatSeverityCount = formatSeverityCount;
352
+ formatIssues.getSeverityCount = getSeverityCount;
353
+ var _misc$2 = sdk.misc;
354
+ var _objects$4 = objects;
355
+ const SEVERITIES_BY_ORDER = ['critical', 'high', 'middle', 'low'];
356
+ function getDesiredSeverities(lowestToInclude) {
357
+ const result = [];
358
+ for (const severity of SEVERITIES_BY_ORDER) {
359
+ result.push(severity);
360
+ if (severity === lowestToInclude) {
361
+ break;
362
+ }
363
+ }
364
+ return result;
365
+ }
366
+ function formatSeverityCount(severityCount) {
367
+ const summary = [];
368
+ for (const severity of SEVERITIES_BY_ORDER) {
369
+ if (severityCount[severity]) {
370
+ summary.push(`${severityCount[severity]} ${severity}`);
371
+ }
372
+ }
373
+ return (0, _misc$2.stringJoinWithSeparateFinalSeparator)(summary);
374
+ }
375
+ function getSeverityCount(issues, lowestToInclude) {
376
+ const severityCount = (0, _objects$4.pick)({
377
+ low: 0,
378
+ middle: 0,
379
+ high: 0,
380
+ critical: 0
381
+ }, getDesiredSeverities(lowestToInclude));
382
+ for (const issue of issues) {
383
+ const value = issue.value;
384
+ if (!value) {
385
+ continue;
386
+ }
387
+ if (severityCount[value.severity] !== undefined) {
388
+ severityCount[value.severity] += 1;
389
+ }
390
+ }
391
+ return severityCount;
392
+ }
393
+
394
+ var formatting = {};
395
+
396
+ Object.defineProperty(formatting, "__esModule", {
397
+ value: true
398
+ });
399
+ formatting.printFlagList = printFlagList;
400
+ formatting.printHelpList = printHelpList;
401
+ function printFlagList(list, indent, {
402
+ keyPrefix = '--',
403
+ padName
404
+ } = {}) {
405
+ return printHelpList({
406
+ help: 'Print this help and exits.',
407
+ version: 'Prints current version and exits.',
408
+ ...list
409
+ }, indent, {
410
+ keyPrefix,
411
+ padName
412
+ });
413
+ }
414
+ function printHelpList(list, indent, {
415
+ keyPrefix = '',
416
+ padName = 18
417
+ } = {}) {
418
+ const names = Object.keys(list).sort();
419
+ let result = '';
420
+ for (const name of names) {
421
+ const rawDescription = list[name];
422
+ const description = (typeof rawDescription === 'object' ? rawDescription.description : rawDescription) || '';
423
+ result += ''.padEnd(indent) + (keyPrefix + name).padEnd(padName) + description + '\n';
424
+ }
425
+ return result.trim();
426
+ }
427
+
428
+ var _interopRequireDefault$q = vendor.interopRequireDefault.default;
429
+ Object.defineProperty(info$1, "__esModule", {
430
+ value: true
431
+ });
432
+ info$1.info = void 0;
433
+ var _chalk$h = _interopRequireDefault$q(vendor.source);
434
+ var _meow$p = _interopRequireDefault$q(vendor.build);
435
+ var _ora$l = _interopRequireDefault$q(vendor.ora);
436
+ var _flags$i = flags$1;
437
+ var _apiHelpers$i = apiHelpers;
438
+ var _chalkMarkdown$3 = sdk.chalkMarkdown;
439
+ var _errors$k = sdk.errors;
440
+ var _formatIssues$1 = formatIssues;
441
+ var _formatting$m = formatting;
442
+ var _objects$3 = objects;
443
+ var _sdk$j = sdk.sdk;
444
+ const info = info$1.info = {
445
+ description: 'Look up info regarding a package',
446
+ async run(argv, importMeta, {
447
+ parentName
448
+ }) {
449
+ const name = parentName + ' info';
450
+ const commandContext = setupCommand$m(name, info.description, argv, importMeta);
451
+ if (commandContext) {
452
+ const spinnerText = commandContext.pkgVersion === 'latest' ? `Looking up data for the latest version of ${commandContext.pkgName}\n` : `Looking up data for version ${commandContext.pkgVersion} of ${commandContext.pkgName}\n`;
453
+ const spinner = (0, _ora$l.default)(spinnerText).start();
454
+ const packageData = await fetchPackageData(commandContext.pkgName, commandContext.pkgVersion, commandContext, spinner);
455
+ if (packageData) {
456
+ formatPackageDataOutput(packageData, {
457
+ name,
458
+ ...commandContext
459
+ }, spinner);
460
+ }
461
+ }
462
+ }
463
+ };
464
+
465
+ // Internal functions
466
+
467
+ function setupCommand$m(name, description, argv, importMeta) {
468
+ const flags = {
469
+ __proto__: null,
470
+ ..._flags$i.outputFlags,
471
+ ..._flags$i.validationFlags
472
+ };
473
+ const cli = (0, _meow$p.default)(`
474
+ Usage
475
+ $ ${name} <name>
476
+
477
+ Options
478
+ ${(0, _formatting$m.printFlagList)(flags, 6)}
479
+
480
+ Examples
481
+ $ ${name} webtorrent
482
+ $ ${name} webtorrent@1.9.1
483
+ `, {
484
+ argv,
485
+ description,
486
+ importMeta,
487
+ flags
488
+ });
489
+ const {
490
+ all: includeAllIssues,
491
+ json: outputJson,
492
+ markdown: outputMarkdown,
493
+ strict
494
+ } = cli.flags;
495
+ if (cli.input.length > 1) {
496
+ throw new _errors$k.InputError('Only one package lookup supported at once');
497
+ }
498
+ const {
499
+ 0: rawPkgName = ''
500
+ } = cli.input;
501
+ if (!rawPkgName) {
502
+ cli.showHelp();
503
+ return;
504
+ }
505
+ const versionSeparator = rawPkgName.lastIndexOf('@');
506
+ const pkgName = versionSeparator < 1 ? rawPkgName : rawPkgName.slice(0, versionSeparator);
507
+ const pkgVersion = versionSeparator < 1 ? 'latest' : rawPkgName.slice(versionSeparator + 1);
508
+ return {
509
+ includeAllIssues,
510
+ outputJson,
511
+ outputMarkdown,
512
+ pkgName,
513
+ pkgVersion,
514
+ strict
515
+ };
516
+ }
517
+ async function fetchPackageData(pkgName, pkgVersion, {
518
+ includeAllIssues
519
+ }, spinner) {
520
+ const socketSdk = await (0, _sdk$j.setupSdk)((0, _sdk$j.getDefaultKey)() || _sdk$j.FREE_API_KEY);
521
+ const result = await (0, _apiHelpers$i.handleApiCall)(socketSdk.getIssuesByNPMPackage(pkgName, pkgVersion), 'looking up package');
522
+ const scoreResult = await (0, _apiHelpers$i.handleApiCall)(socketSdk.getScoreByNPMPackage(pkgName, pkgVersion), 'looking up package score');
523
+ if (result.success === false) {
524
+ return (0, _apiHelpers$i.handleUnsuccessfulApiResponse)('getIssuesByNPMPackage', result, spinner);
525
+ }
526
+ if (scoreResult.success === false) {
527
+ return (0, _apiHelpers$i.handleUnsuccessfulApiResponse)('getScoreByNPMPackage', scoreResult, spinner);
528
+ }
529
+ const severityCount = (0, _formatIssues$1.getSeverityCount)(result.data, includeAllIssues ? undefined : 'high');
530
+ return {
531
+ data: result.data,
532
+ severityCount,
533
+ score: scoreResult.data
534
+ };
535
+ }
536
+ function formatPackageDataOutput({
537
+ data,
538
+ severityCount,
539
+ score
540
+ }, {
541
+ name,
542
+ outputJson,
543
+ outputMarkdown,
544
+ pkgName,
545
+ pkgVersion,
546
+ strict
547
+ }, spinner) {
548
+ if (outputJson) {
549
+ console.log(JSON.stringify(data, undefined, 2));
550
+ } else {
551
+ console.log('\nPackage report card:');
552
+ const scoreResult = {
553
+ 'Supply Chain Risk': Math.floor(score.supplyChainRisk.score * 100),
554
+ Maintenance: Math.floor(score.maintenance.score * 100),
555
+ Quality: Math.floor(score.quality.score * 100),
556
+ Vulnerabilities: Math.floor(score.vulnerability.score * 100),
557
+ License: Math.floor(score.license.score * 100)
558
+ };
559
+ Object.entries(scoreResult).map(score => console.log(`- ${score[0]}: ${formatScore(score[1])}`));
560
+ if ((0, _objects$3.objectSome)(severityCount)) {
561
+ const issueSummary = (0, _formatIssues$1.formatSeverityCount)(severityCount);
562
+ console.log('\n');
563
+ spinner[strict ? 'fail' : 'succeed'](`Package has these issues: ${issueSummary}`);
564
+ formatPackageIssuesDetails(data, outputMarkdown);
565
+ } else {
566
+ console.log('\n');
567
+ spinner.succeed('Package has no issues');
568
+ }
569
+ const format = new _chalkMarkdown$3.ChalkOrMarkdown(!!outputMarkdown);
570
+ const url = `https://socket.dev/npm/package/${pkgName}/overview/${pkgVersion}`;
571
+ if (pkgVersion === 'latest') {
572
+ console.log('\nDetailed info on socket.dev: ' + format.hyperlink(`${pkgName}`, url, {
573
+ fallbackToUrl: true
574
+ }));
575
+ } else {
576
+ console.log('\nDetailed info on socket.dev: ' + format.hyperlink(`${pkgName} v${pkgVersion}`, url, {
577
+ fallbackToUrl: true
578
+ }));
579
+ }
580
+ if (!outputMarkdown) {
581
+ console.log(_chalk$h.default.dim('\nOr rerun', _chalk$h.default.italic(name), 'using the', _chalk$h.default.italic('--json'), 'flag to get full JSON output'));
582
+ }
583
+ }
584
+ if (strict && (0, _objects$3.objectSome)(severityCount)) {
585
+ process.exit(1);
586
+ }
587
+ }
588
+ function formatPackageIssuesDetails(packageData, outputMarkdown) {
589
+ const issueDetails = packageData.filter(d => d.value?.severity === 'high' || d.value?.severity === 'critical');
590
+ const uniqueIssues = issueDetails.reduce((acc, issue) => {
591
+ const {
592
+ type
593
+ } = issue;
594
+ if (type) {
595
+ if (acc[type] === undefined) {
596
+ acc[type] = {
597
+ label: issue.value?.label,
598
+ count: 1
599
+ };
600
+ } else {
601
+ acc[type].count += 1;
602
+ }
603
+ }
604
+ return acc;
605
+ }, {});
606
+ const format = new _chalkMarkdown$3.ChalkOrMarkdown(!!outputMarkdown);
607
+ for (const issue of Object.keys(uniqueIssues)) {
608
+ const issueWithLink = format.hyperlink(`${uniqueIssues[issue]?.label}`, `https://socket.dev/npm/issue/${issue}`, {
609
+ fallbackToUrl: true
610
+ });
611
+ if (uniqueIssues[issue]?.count === 1) {
612
+ console.log(`- ${issueWithLink}`);
613
+ } else {
614
+ console.log(`- ${issueWithLink}: ${uniqueIssues[issue]?.count}`);
615
+ }
616
+ }
617
+ }
618
+ function formatScore(score) {
619
+ const error = _chalk$h.default.hex('#de7c7b');
620
+ const warning = _chalk$h.default.hex('#e59361');
621
+ const success = _chalk$h.default.hex('#a4cb9d');
622
+ if (score > 80) {
623
+ return `${success(score)}`;
624
+ } else if (score < 80 && score > 60) {
625
+ return `${warning(score)}`;
626
+ }
627
+ return `${error(score)}`;
628
+ }
629
+
630
+ var login = {};
631
+
632
+ var _interopRequireDefault$p = vendor.interopRequireDefault.default;
633
+ Object.defineProperty(login, "__esModule", {
634
+ value: true
635
+ });
636
+ login.login = void 0;
637
+ var _prompts$1 = require$$1$2;
638
+ var _isInteractive = _interopRequireDefault$p(vendor.isInteractive);
639
+ var _meow$o = _interopRequireDefault$p(vendor.build);
640
+ var _ora$k = _interopRequireDefault$p(vendor.ora);
641
+ var _terminalLink = _interopRequireDefault$p(vendor.terminalLink);
642
+ var _errors$j = sdk.errors;
643
+ var _formatting$l = formatting;
644
+ var _sdk$i = sdk.sdk;
645
+ var _settings$1 = sdk.settings;
646
+ const description$7 = 'Socket API login';
647
+ const flags = {
648
+ apiBaseUrl: {
649
+ type: 'string',
650
+ description: 'API server to connect to for login'
651
+ },
652
+ apiProxy: {
653
+ type: 'string',
654
+ description: 'Proxy to use when making connection to API server'
655
+ }
656
+ };
657
+ login.login = {
658
+ description: description$7,
659
+ async run(argv, importMeta, {
660
+ parentName
661
+ }) {
662
+ const name = `${parentName} login`;
663
+ const cli = (0, _meow$o.default)(`
664
+ Usage
665
+ $ ${name}
666
+
667
+ Logs into the Socket API by prompting for an API key
668
+
669
+ Options
670
+ ${(0, _formatting$l.printFlagList)({
671
+ 'api-base-url': flags['apiBaseUrl'].description,
672
+ 'api-proxy': flags['apiProxy'].description
673
+ }, 8)}
674
+
675
+ Examples
676
+ $ ${name}
677
+ `, {
678
+ argv,
679
+ description: description$7,
680
+ importMeta,
681
+ flags
682
+ });
683
+ if (cli.input.length) {
684
+ cli.showHelp();
685
+ }
686
+ if (!(0, _isInteractive.default)()) {
687
+ throw new _errors$j.InputError('Cannot prompt for credentials in a non-interactive shell');
688
+ }
689
+ const apiKey = (await (0, _prompts$1.password)({
690
+ message: `Enter your ${(0, _terminalLink.default)('Socket.dev API key', 'https://docs.socket.dev/docs/api-keys')} (leave blank for a public key)`
691
+ })) || _sdk$i.FREE_API_KEY;
692
+ let apiBaseUrl = cli.flags['apiBaseUrl'];
693
+ apiBaseUrl ??= (0, _settings$1.getSetting)('apiBaseUrl') ?? undefined;
694
+ let apiProxy = cli.flags['apiProxy'];
695
+ apiProxy ??= (0, _settings$1.getSetting)('apiProxy') ?? undefined;
696
+ const spinner = (0, _ora$k.default)('Verifying API key...').start();
697
+ let orgs;
698
+ try {
699
+ const sdk = await (0, _sdk$i.setupSdk)(apiKey, apiBaseUrl, apiProxy);
700
+ const result = await sdk.getOrganizations();
701
+ if (!result.success) {
702
+ throw new _errors$j.AuthError();
703
+ }
704
+ orgs = result.data;
705
+ spinner.succeed('API key verified\n');
706
+ } catch {
707
+ spinner.fail('Invalid API key');
708
+ return;
709
+ }
710
+ const nonNullish = value => value != null;
711
+ const enforcedChoices = Object.values(orgs.organizations).filter(nonNullish).filter(org => org.plan === 'enterprise').map(org => ({
712
+ name: org.name,
713
+ value: org.id
714
+ }));
715
+ let enforcedOrgs = [];
716
+ if (enforcedChoices.length > 1) {
717
+ const id = await (0, _prompts$1.select)({
718
+ message: "Which organization's policies should Socket enforce system-wide?",
719
+ choices: enforcedChoices.concat({
720
+ name: 'None',
721
+ value: '',
722
+ description: 'Pick "None" if this is a personal device'
723
+ })
724
+ });
725
+ if (id) {
726
+ enforcedOrgs = [id];
727
+ }
728
+ } else if (enforcedChoices.length) {
729
+ const confirmOrg = await (0, _prompts$1.confirm)({
730
+ message: `Should Socket enforce ${enforcedChoices[0]?.name}'s security policies system-wide?`,
731
+ default: true
732
+ });
733
+ if (confirmOrg) {
734
+ const existing = enforcedChoices[0];
735
+ if (existing) {
736
+ enforcedOrgs = [existing.value];
737
+ }
738
+ }
739
+ }
740
+ (0, _settings$1.updateSetting)('enforcedOrgs', enforcedOrgs);
741
+ const oldKey = (0, _settings$1.getSetting)('apiKey');
742
+ (0, _settings$1.updateSetting)('apiKey', apiKey);
743
+ (0, _settings$1.updateSetting)('apiBaseUrl', apiBaseUrl);
744
+ (0, _settings$1.updateSetting)('apiProxy', apiProxy);
745
+ spinner.succeed(`API credentials ${oldKey ? 'updated' : 'set'}`);
746
+ }
747
+ };
748
+
749
+ var logout = {};
750
+
751
+ var _interopRequireDefault$o = vendor.interopRequireDefault.default;
752
+ Object.defineProperty(logout, "__esModule", {
753
+ value: true
754
+ });
755
+ logout.logout = void 0;
756
+ var _meow$n = _interopRequireDefault$o(vendor.build);
757
+ var _ora$j = _interopRequireDefault$o(vendor.ora);
758
+ var _settings = sdk.settings;
759
+ const description$6 = 'Socket API logout';
760
+ logout.logout = {
761
+ description: description$6,
762
+ async run(argv, importMeta, {
763
+ parentName
764
+ }) {
765
+ const name = `${parentName} logout`;
766
+ const cli = (0, _meow$n.default)(`
767
+ Usage
768
+ $ ${name}
769
+
770
+ Logs out of the Socket API and clears all Socket credentials from disk
771
+
772
+ Examples
773
+ $ ${name}
774
+ `, {
775
+ argv,
776
+ description: description$6,
777
+ importMeta
778
+ });
779
+ if (cli.input.length) {
780
+ cli.showHelp();
781
+ }
782
+ (0, _settings.updateSetting)('apiKey', null);
783
+ (0, _settings.updateSetting)('apiBaseUrl', null);
784
+ (0, _settings.updateSetting)('apiProxy', null);
785
+ (0, _settings.updateSetting)('enforcedOrgs', null);
786
+ (0, _ora$j.default)('Successfully logged out').succeed();
787
+ }
788
+ };
789
+
790
+ var npm = {};
791
+
792
+ Object.defineProperty(npm, "__esModule", {
793
+ value: true
794
+ });
795
+ npm.npm = void 0;
796
+ var _nodePath$6 = require$$1;
797
+ var _promiseSpawn$5 = require$$1$1;
798
+ const distPath$3 = __dirname;
799
+ const description$5 = 'npm wrapper functionality';
800
+ npm.npm = {
801
+ description: description$5,
802
+ async run(argv, _importMeta, _ctx) {
803
+ process.exitCode = 1;
804
+ const wrapperPath = _nodePath$6.join(distPath$3, 'npm-cli.js');
805
+ const spawnPromise = _promiseSpawn$5(process.execPath, [wrapperPath, ...argv], {
806
+ stdio: 'inherit'
807
+ });
808
+ spawnPromise.process.on('exit', (code, signal) => {
809
+ if (signal) {
810
+ process.kill(process.pid, signal);
811
+ } else if (code !== null) {
812
+ process.exit(code);
813
+ }
814
+ });
815
+ await spawnPromise;
816
+ }
817
+ };
818
+
819
+ var npx = {};
820
+
821
+ Object.defineProperty(npx, "__esModule", {
822
+ value: true
823
+ });
824
+ npx.npx = void 0;
825
+ var _nodePath$5 = require$$1;
826
+ var _promiseSpawn$4 = require$$1$1;
827
+ const distPath$2 = __dirname;
828
+ const description$4 = 'npx wrapper functionality';
829
+ npx.npx = {
830
+ description: description$4,
831
+ async run(argv, _importMeta, _ctx) {
832
+ const wrapperPath = _nodePath$5.join(distPath$2, 'npx-cli.js');
833
+ process.exitCode = 1;
834
+ const spawnPromise = _promiseSpawn$4(process.execPath, [wrapperPath, ...argv], {
835
+ stdio: 'inherit'
836
+ });
837
+ spawnPromise.process.on('exit', (code, signal) => {
838
+ if (signal) {
839
+ process.kill(process.pid, signal);
840
+ } else if (code !== null) {
841
+ process.exit(code);
842
+ }
843
+ });
844
+ await spawnPromise;
845
+ }
846
+ };
847
+
848
+ var optimize$1 = {};
849
+
850
+ var packageManagerDetector = {};
851
+
852
+ var fs = {};
853
+
854
+ Object.defineProperty(fs, "__esModule", {
855
+ value: true
856
+ });
857
+ fs.existsSync = existsSync;
858
+ fs.findUp = findUp;
859
+ fs.readFileBinary = readFileBinary;
860
+ fs.readFileUtf8 = readFileUtf8;
861
+ var _nodeFs$4 = require$$0;
862
+ var _nodePath$4 = require$$1;
863
+ function existsSync(filepath) {
864
+ try {
865
+ return filepath ? (0, _nodeFs$4.existsSync)(filepath) : false;
866
+ } catch {}
867
+ return false;
868
+ }
869
+ async function findUp(name, {
870
+ cwd = process.cwd()
871
+ }) {
872
+ let dir = _nodePath$4.resolve(cwd);
873
+ const {
874
+ root
875
+ } = _nodePath$4.parse(dir);
876
+ const names = [name].flat();
877
+ while (dir && dir !== root) {
878
+ for (const name of names) {
879
+ const filePath = _nodePath$4.join(dir, name);
880
+ try {
881
+ const stats = await _nodeFs$4.promises.stat(filePath);
882
+ if (stats.isFile()) {
883
+ return filePath;
884
+ }
885
+ } catch {}
886
+ }
887
+ dir = _nodePath$4.dirname(dir);
888
+ }
889
+ return undefined;
890
+ }
891
+ async function readFileBinary(filepath, options) {
892
+ return await _nodeFs$4.promises.readFile(filepath, {
893
+ ...options,
894
+ encoding: 'binary'
895
+ });
896
+ }
897
+ async function readFileUtf8(filepath, options) {
898
+ return await _nodeFs$4.promises.readFile(filepath, {
899
+ ...options,
900
+ encoding: 'utf8'
901
+ });
902
+ }
903
+
904
+ var json = {};
905
+
906
+ Object.defineProperty(json, "__esModule", {
907
+ value: true
908
+ });
909
+ json.parseJSONObject = parseJSONObject;
910
+ var _objects$2 = objects;
911
+ function parseJSONObject(jsonStr) {
912
+ try {
913
+ const value = JSON.parse(jsonStr);
914
+ if ((0, _objects$2.isObjectObject)(value)) {
915
+ return value;
916
+ }
917
+ } catch {}
918
+ return null;
919
+ }
920
+
921
+ var strings = {};
922
+
923
+ Object.defineProperty(strings, "__esModule", {
924
+ value: true
925
+ });
926
+ strings.isNonEmptyString = isNonEmptyString;
927
+ function isNonEmptyString(value) {
928
+ return typeof value === 'string' && value.length > 0;
929
+ }
930
+
931
+ Object.defineProperty(packageManagerDetector, "__esModule", {
932
+ value: true
933
+ });
934
+ packageManagerDetector.LOCKS = packageManagerDetector.AGENTS = void 0;
935
+ packageManagerDetector.detect = detect;
936
+ var _nodePath$3 = require$$1;
937
+ var _hyrious__bun = require$$1$3;
938
+ var _promiseSpawn$3 = require$$1$1;
939
+ var _browserslist = require$$3;
940
+ var _semver = require$$3$1;
941
+ var _which = require$$5$1;
942
+ var _fs = fs;
943
+ var _json = json;
944
+ var _objects$1 = objects;
945
+ var _strings = strings;
946
+ const AGENTS = packageManagerDetector.AGENTS = ['bun', 'npm', 'pnpm', 'yarn'];
947
+ const LOCKS = packageManagerDetector.LOCKS = {
948
+ 'bun.lockb': 'bun',
949
+ 'pnpm-lock.yaml': 'pnpm',
950
+ 'pnpm-lock.yml': 'pnpm',
951
+ 'yarn.lock': 'yarn',
952
+ // If both package-lock.json and npm-shrinkwrap.json are present in the root
953
+ // of a project, npm-shrinkwrap.json will take precedence and package-lock.json
954
+ // will be ignored.
955
+ // https://docs.npmjs.com/cli/v10/configuring-npm/package-lock-json#package-lockjson-vs-npm-shrinkwrapjson
956
+ 'npm-shrinkwrap.json': 'npm',
957
+ 'package-lock.json': 'npm',
958
+ // Look for a hidden lock file if .npmrc has package-lock=false:
959
+ // https://docs.npmjs.com/cli/v10/configuring-npm/package-lock-json#hidden-lockfiles
960
+ //
961
+ // Unlike the other LOCKS keys this key contains a directory AND filename so
962
+ // it has to be handled differently.
963
+ 'node_modules/.package-lock.json': 'npm'
964
+ };
965
+ const MAINTAINED_NODE_VERSIONS = _browserslist('maintained node versions')
966
+ // Trim value, e.g. 'node 22.5.0' to '22.5.0'
967
+ .map(v => v.slice(5));
968
+ const readLockFileByAgent = (() => {
969
+ const wrapReader = reader => async (lockPath, agentExecPath) => {
970
+ try {
971
+ return await reader(lockPath, agentExecPath);
972
+ } catch {}
973
+ return undefined;
974
+ };
975
+ return {
976
+ bun: wrapReader(async (lockPath, agentExecPath) => {
977
+ let lockBuffer;
978
+ try {
979
+ lockBuffer = await (0, _fs.readFileBinary)(lockPath);
980
+ } catch {
981
+ return undefined;
982
+ }
983
+ try {
984
+ return (0, _hyrious__bun.parse)(lockBuffer);
985
+ } catch {}
986
+ // To print a Yarn lockfile to your console without writing it to disk use `bun bun.lockb`.
987
+ // https://bun.sh/guides/install/yarnlock
988
+ return (await _promiseSpawn$3(agentExecPath ?? 'bun', [lockPath])).stdout;
989
+ }),
990
+ npm: wrapReader(async lockPath => await (0, _fs.readFileUtf8)(lockPath)),
991
+ pnpm: wrapReader(async lockPath => await (0, _fs.readFileUtf8)(lockPath)),
992
+ yarn: wrapReader(async lockPath => await (0, _fs.readFileUtf8)(lockPath))
993
+ };
994
+ })();
995
+ async function detect({
996
+ cwd,
997
+ onUnknown
998
+ } = {}) {
999
+ const lockPath = await (0, _fs.findUp)(Object.keys(LOCKS), {
1000
+ cwd
1001
+ });
1002
+ const isHiddenLockFile = lockPath?.endsWith('.package-lock.json') ?? false;
1003
+ const pkgJsonPath = lockPath ? _nodePath$3.resolve(lockPath, `${isHiddenLockFile ? '../' : ''}../package.json`) : await (0, _fs.findUp)('package.json', {
1004
+ cwd
1005
+ });
1006
+
1007
+ // Read Corepack `packageManager` field in package.json:
1008
+ // https://nodejs.org/api/packages.html#packagemanager
1009
+ const pkgJsonStr = (0, _fs.existsSync)(pkgJsonPath) ? await (0, _fs.readFileUtf8)(pkgJsonPath) : undefined;
1010
+ const pkgJson = typeof pkgJsonStr === 'string' ? (0, _json.parseJSONObject)(pkgJsonStr) ?? undefined : undefined;
1011
+ const pkgManager = (0, _strings.isNonEmptyString)((0, _objects$1.getOwn)(pkgJson, 'packageManager')) ? pkgJson?.['packageManager'] : undefined;
1012
+ let agent;
1013
+ let agentVersion;
1014
+ if (pkgManager) {
1015
+ const atSignIndex = pkgManager.lastIndexOf('@');
1016
+ if (atSignIndex !== -1) {
1017
+ const name = pkgManager.slice(0, atSignIndex);
1018
+ const version = pkgManager.slice(atSignIndex + 1);
1019
+ if (version && AGENTS.includes(name)) {
1020
+ agent = name;
1021
+ agentVersion = version;
1022
+ }
1023
+ }
1024
+ }
1025
+ if (agent === undefined && !isHiddenLockFile && typeof lockPath === 'string') {
1026
+ agent = LOCKS[_nodePath$3.basename(lockPath)];
1027
+ }
1028
+ if (agent === undefined) {
1029
+ agent = 'npm';
1030
+ onUnknown?.(pkgManager);
1031
+ }
1032
+ const agentExecPath = (await _which(agent, {
1033
+ nothrow: true
1034
+ })) ?? agent;
1035
+ let lockSrc;
1036
+ const targets = {
1037
+ browser: false,
1038
+ node: true
1039
+ };
1040
+ let isPrivate = false;
1041
+ let isWorkspace = false;
1042
+ if (pkgJson) {
1043
+ const pkgPath = _nodePath$3.dirname(pkgJsonPath);
1044
+ isPrivate = !!pkgJson['private'];
1045
+ isWorkspace = !!pkgJson['workspaces'] || agent === 'pnpm' && (0, _fs.existsSync)(_nodePath$3.join(pkgPath, 'pnpm-workspace.yaml'));
1046
+ let browser;
1047
+ let node;
1048
+ const browserField = (0, _objects$1.getOwn)(pkgJson, 'browser');
1049
+ if ((0, _strings.isNonEmptyString)(browserField) || (0, _objects$1.isObjectObject)(browserField)) {
1050
+ browser = true;
1051
+ }
1052
+ const nodeRange = (0, _objects$1.getOwn)(pkgJson['engines'], 'node');
1053
+ if ((0, _strings.isNonEmptyString)(nodeRange)) {
1054
+ node = MAINTAINED_NODE_VERSIONS.some(v => _semver.satisfies(v, nodeRange));
1055
+ }
1056
+ const browserslistQuery = (0, _objects$1.getOwn)(pkgJson, 'browserslist');
1057
+ if (Array.isArray(browserslistQuery)) {
1058
+ const browserslistTargets = _browserslist(browserslistQuery);
1059
+ const browserslistNodeTargets = browserslistTargets.filter(v => v.startsWith('node ')).map(v => v.slice(5));
1060
+ if (browser === undefined && browserslistTargets.length) {
1061
+ browser = browserslistTargets.length !== browserslistNodeTargets.length;
1062
+ }
1063
+ if (node === undefined && browserslistNodeTargets.length) {
1064
+ node = MAINTAINED_NODE_VERSIONS.some(r => browserslistNodeTargets.some(v => _semver.satisfies(v, `^${r}`)));
1065
+ }
1066
+ }
1067
+ if (browser !== undefined) {
1068
+ targets.browser = browser;
1069
+ }
1070
+ if (node !== undefined) {
1071
+ targets.node = node;
1072
+ }
1073
+ lockSrc = typeof lockPath === 'string' ? await readLockFileByAgent[agent](lockPath, agentExecPath) : undefined;
1074
+ }
1075
+ return {
1076
+ agent,
1077
+ agentExecPath,
1078
+ agentVersion,
1079
+ isPrivate,
1080
+ isWorkspace,
1081
+ lockPath,
1082
+ lockSrc,
1083
+ pkgJson,
1084
+ pkgJsonPath,
1085
+ pkgJsonStr,
1086
+ supported: targets.browser || targets.node,
1087
+ targets
1088
+ };
1089
+ }
1090
+
1091
+ var regexps = {};
1092
+
1093
+ Object.defineProperty(regexps, "__esModule", {
1094
+ value: true
1095
+ });
1096
+ regexps.escapeRegExp = escapeRegExp;
1097
+ // Inlined "escape-string-regexp":
1098
+ // https://socket.dev/npm/package/escape-string-regexp/overview/5.0.0
1099
+ // MIT License
1100
+ // Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
1101
+ function escapeRegExp(string) {
1102
+ // Escape characters with special meaning either inside or outside character sets.
1103
+ // Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
1104
+ return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
1105
+ }
1106
+
1107
+ var sorts = {};
1108
+
1109
+ Object.defineProperty(sorts, "__esModule", {
1110
+ value: true
1111
+ });
1112
+ sorts.localeCompare = void 0;
1113
+ sorts.toSortedObject = toSortedObject;
1114
+ const {
1115
+ compare: localeCompare
1116
+ } = new Intl.Collator();
1117
+ sorts.localeCompare = localeCompare;
1118
+ function toSortedObject(object, comparator = localeCompare) {
1119
+ return Object.fromEntries(Object.entries(object).sort((a, b) => comparator(a[0], b[0])));
1120
+ }
1121
+
1122
+ var _interopRequireDefault$n = vendor.interopRequireDefault.default;
1123
+ Object.defineProperty(optimize$1, "__esModule", {
1124
+ value: true
1125
+ });
1126
+ optimize$1.optimize = void 0;
1127
+ var _nodePath$2 = require$$1;
1128
+ var _promiseSpawn$2 = require$$1$1;
1129
+ var _packageJson = require$$3$2;
1130
+ var _registry = require$$4;
1131
+ var _meow$m = _interopRequireDefault$n(vendor.build);
1132
+ var _ora$i = _interopRequireDefault$n(vendor.ora);
1133
+ var _formatting$k = formatting;
1134
+ var _objects = objects;
1135
+ var _packageManagerDetector = packageManagerDetector;
1136
+ var _regexps = regexps;
1137
+ var _sorts$1 = sorts;
1138
+ const distPath$1 = __dirname;
1139
+ const OVERRIDES_FIELD_NAME = 'overrides';
1140
+ const RESOLUTIONS_FIELD_NAME = 'resolutions';
1141
+ const SOCKET_REGISTRY_NAME = '@socketregistry';
1142
+ const SOCKET_REGISTRY_MAJOR_VERSION = '^1';
1143
+ const allPackages = (0, _registry.getManifestData)('npm').map(({
1144
+ 1: d
1145
+ }) => d.package);
1146
+ const getManifestOverridesByAgent = {
1147
+ // npm overrides documentation:
1148
+ // https://docs.npmjs.com/cli/v10/configuring-npm/package-json#overrides
1149
+ npm: pkgJson => pkgJson?.overrides ?? undefined,
1150
+ // pnpm overrides documentation:
1151
+ // https://pnpm.io/package_json#pnpmoverrides
1152
+ pnpm: pkgJson => pkgJson?.pnpm?.overrides ?? undefined,
1153
+ // Yarn resolutions documentation:
1154
+ // https://yarnpkg.com/configuration/manifest#resolutions
1155
+ yarn: pkgJson => pkgJson?.resolutions ?? undefined
1156
+ };
1157
+ const lockIncludesByAgent = {
1158
+ npm: (lockSrc, name) => {
1159
+ // Detects the package name in the following cases:
1160
+ // "name":
1161
+ return lockSrc.includes(`"${name}":`);
1162
+ },
1163
+ pnpm: (lockSrc, name) => {
1164
+ const escapedName = (0, _regexps.escapeRegExp)(name);
1165
+ return new RegExp(
1166
+ // Detects the package name in the following cases:
1167
+ // /name/version:
1168
+ // 'name': version
1169
+ // name: version
1170
+ `(?<=^\\s*)(?:(['/])${escapedName}\\1|${escapedName}(?=:))`, 'm').test(lockSrc);
1171
+ },
1172
+ yarn: (lockSrc, name) => {
1173
+ const escapedName = (0, _regexps.escapeRegExp)(name);
1174
+ return new RegExp(
1175
+ // Detects the package name in the following cases:
1176
+ // "name@
1177
+ // , "name@
1178
+ // name@
1179
+ // , name@
1180
+ `(?<=(?:^\\s*|,\\s*)"?)${escapedName}(?=@)`, 'm').test(lockSrc);
1181
+ }
1182
+ };
1183
+ const updateManifestByAgent = {
1184
+ __proto__: null,
1185
+ npm(editablePkgJson, overrides) {
1186
+ editablePkgJson.update({
1187
+ [OVERRIDES_FIELD_NAME]: overrides
1188
+ });
1189
+ },
1190
+ pnpm(editablePkgJson, overrides) {
1191
+ editablePkgJson.update({
1192
+ [OVERRIDES_FIELD_NAME]: overrides
1193
+ });
1194
+ },
1195
+ yarn(editablePkgJson, overrides) {
1196
+ editablePkgJson.update({
1197
+ [RESOLUTIONS_FIELD_NAME]: overrides
1198
+ });
1199
+ }
1200
+ };
1201
+ async function addOverrides({
1202
+ agent,
1203
+ isPrivate,
1204
+ isWorkspace,
1205
+ lockSrc,
1206
+ lockIncludes,
1207
+ pkgJsonPath,
1208
+ overrides
1209
+ }, aoState) {
1210
+ const {
1211
+ packageNames
1212
+ } = aoState;
1213
+ let addedCount = 0;
1214
+ let clonedOverrides;
1215
+ for (const name of allPackages) {
1216
+ if (!(0, _objects.hasOwn)(overrides, name) && lockIncludes(lockSrc, name)) {
1217
+ if (clonedOverrides === undefined) {
1218
+ clonedOverrides = {
1219
+ __proto__: null,
1220
+ ...overrides
1221
+ };
1222
+ }
1223
+ addedCount += 1;
1224
+ packageNames.add(name);
1225
+ clonedOverrides[name] = `npm:${SOCKET_REGISTRY_NAME}/${name}@${SOCKET_REGISTRY_MAJOR_VERSION}`;
1226
+ }
1227
+ }
1228
+ if (addedCount) {
1229
+ const editablePkgJson = await _packageJson.load(_nodePath$2.dirname(pkgJsonPath));
1230
+ const sortedOverrides = (0, _sorts$1.toSortedObject)(clonedOverrides);
1231
+ updateManifestByAgent[agent](editablePkgJson, sortedOverrides);
1232
+ if (!isPrivate && !isWorkspace) {
1233
+ if ((0, _objects.hasOwn)(editablePkgJson.content, 'pnpm') && (0, _objects.isObjectObject)(editablePkgJson.content['pnpm'])) {
1234
+ const pnpmKeys = Object.keys(editablePkgJson.content['pnpm']);
1235
+ editablePkgJson.update(pnpmKeys.length === 1 && pnpmKeys[0] === 'overrides' ?
1236
+ // Properties with undefined values are omitted when saved as JSON.
1237
+ {
1238
+ pnpm: undefined
1239
+ } : {
1240
+ pnpm: {
1241
+ __proto__: null,
1242
+ ...editablePkgJson.content['pnpm'],
1243
+ overrides: undefined
1244
+ }
1245
+ });
1246
+ }
1247
+ updateManifestByAgent.npm(editablePkgJson, sortedOverrides);
1248
+ updateManifestByAgent.yarn(editablePkgJson, sortedOverrides);
1249
+ }
1250
+ await editablePkgJson.save();
1251
+ }
1252
+ return aoState;
1253
+ }
1254
+ const optimize = optimize$1.optimize = {
1255
+ description: 'Optimize dependencies with @socketregistry overrides',
1256
+ async run(argv, importMeta, {
1257
+ parentName
1258
+ }) {
1259
+ const commandContext = setupCommand$l(`${parentName} dependency optimize`, optimize.description, argv, importMeta);
1260
+ if (commandContext) {
1261
+ const {
1262
+ agent,
1263
+ agentExecPath,
1264
+ isPrivate,
1265
+ isWorkspace,
1266
+ lockSrc,
1267
+ lockPath,
1268
+ pkgJsonPath,
1269
+ pkgJsonStr,
1270
+ pkgJson,
1271
+ supported
1272
+ } = await (0, _packageManagerDetector.detect)({
1273
+ cwd: process.cwd(),
1274
+ onUnknown(pkgManager) {
1275
+ console.log(`⚠️ Unknown package manager${pkgManager ? ` ${pkgManager}` : ''}: Defaulting to npm`);
1276
+ }
1277
+ });
1278
+ if (!supported) {
1279
+ console.log('✘ The engines.node range is not supported.');
1280
+ return;
1281
+ }
1282
+ if (pkgJson === undefined) {
1283
+ console.log('✘ No package.json found.');
1284
+ return;
1285
+ }
1286
+ const aoState = {
1287
+ output: pkgJsonStr,
1288
+ packageNames: new Set()
1289
+ };
1290
+ if (lockSrc) {
1291
+ const configs = agent === 'bun' ? [{
1292
+ agent: 'npm',
1293
+ lockIncludes: lockIncludesByAgent.yarn,
1294
+ overrides: getManifestOverridesByAgent.npm(pkgJson)
1295
+ }, {
1296
+ agent: 'yarn',
1297
+ lockIncludes: lockIncludesByAgent.yarn,
1298
+ overrides: getManifestOverridesByAgent.yarn(pkgJson)
1299
+ }] : [{
1300
+ agent,
1301
+ lockIncludes: lockIncludesByAgent[agent],
1302
+ overrides: getManifestOverridesByAgent[agent](pkgJson)
1303
+ }];
1304
+ for (const config of configs) {
1305
+ await addOverrides({
1306
+ __proto__: null,
1307
+ isPrivate,
1308
+ isWorkspace,
1309
+ lockSrc,
1310
+ pkgJsonPath,
1311
+ pkgJsonStr,
1312
+ pkgJson,
1313
+ ...config
1314
+ }, aoState);
1315
+ }
1316
+ }
1317
+ const {
1318
+ size: count
1319
+ } = aoState.packageNames;
1320
+ if (count) {
1321
+ console.log(`Added ${count} Socket.dev optimized overrides 🚀`);
1322
+ } else {
1323
+ console.log('Congratulations! Already Socket.dev optimized 🎉');
1324
+ }
1325
+ const lockName = lockPath ? _nodePath$2.basename(lockPath) : 'lock file';
1326
+ const isNpm = agent === 'npm';
1327
+ if (isNpm || count) {
1328
+ // Always update package-lock.json until the npm overrides PR lands:
1329
+ // https://github.com/npm/cli/pull/7025
1330
+ const spinner = (0, _ora$i.default)(`Updating ${lockName}...`).start();
1331
+ try {
1332
+ if (isNpm) {
1333
+ const wrapperPath = _nodePath$2.join(distPath$1, 'npm-cli.js');
1334
+ await _promiseSpawn$2(process.execPath, [wrapperPath, 'install'], {
1335
+ stdio: 'pipe',
1336
+ env: {
1337
+ __proto__: null,
1338
+ ...process.env,
1339
+ UPDATE_SOCKET_OVERRIDES_IN_PACKAGE_LOCK_FILE: '1'
1340
+ }
1341
+ });
1342
+ } else {
1343
+ await _promiseSpawn$2(agentExecPath, ['install'], {
1344
+ stdio: 'pipe'
1345
+ });
1346
+ }
1347
+ spinner.stop();
1348
+ } catch {
1349
+ spinner.stop();
1350
+ console.log(`✘ socket ${agent} install: Failed to update ${lockName}`);
1351
+ }
1352
+ }
1353
+ }
1354
+ }
1355
+ };
1356
+
1357
+ // Internal functions
1358
+
1359
+ function setupCommand$l(name, description, argv, importMeta) {
1360
+ const flags = {};
1361
+ const cli = (0, _meow$m.default)(`
1362
+ Usage
1363
+ $ ${name}
1364
+
1365
+ Options
1366
+ ${(0, _formatting$k.printFlagList)(flags, 6)}
1367
+
1368
+ Examples
1369
+ $ ${name}
1370
+ `, {
1371
+ argv,
1372
+ description,
1373
+ importMeta,
1374
+ flags
1375
+ });
1376
+ const {
1377
+ json: outputJson,
1378
+ markdown: outputMarkdown,
1379
+ limit,
1380
+ offset
1381
+ } = cli.flags;
1382
+ return {
1383
+ outputJson,
1384
+ outputMarkdown,
1385
+ limit,
1386
+ offset
1387
+ };
1388
+ }
1389
+
1390
+ var organization = {};
1391
+
1392
+ var _interopRequireDefault$m = vendor.interopRequireDefault.default;
1393
+ Object.defineProperty(organization, "__esModule", {
1394
+ value: true
1395
+ });
1396
+ organization.organizations = void 0;
1397
+ var _chalk$g = _interopRequireDefault$m(vendor.source);
1398
+ var _meow$l = _interopRequireDefault$m(vendor.build);
1399
+ var _ora$h = _interopRequireDefault$m(vendor.ora);
1400
+ var _apiHelpers$h = apiHelpers;
1401
+ var _errors$i = sdk.errors;
1402
+ var _sdk$h = sdk.sdk;
1403
+ const organizations = organization.organizations = {
1404
+ description: 'List organizations associated with the API key used',
1405
+ async run(argv, importMeta, {
1406
+ parentName
1407
+ }) {
1408
+ setupCommand$k(`${parentName} organizations`, organizations.description, argv, importMeta);
1409
+ await fetchOrganizations();
1410
+ }
1411
+ };
1412
+
1413
+ // Internal functions
1414
+
1415
+ function setupCommand$k(name, description, argv, importMeta) {
1416
+ (0, _meow$l.default)(`
1417
+ Usage
1418
+ $ ${name}
1419
+ `, {
1420
+ argv,
1421
+ description,
1422
+ importMeta
1423
+ });
1424
+ }
1425
+ async function fetchOrganizations() {
1426
+ const apiKey = (0, _sdk$h.getDefaultKey)();
1427
+ if (!apiKey) {
1428
+ throw new _errors$i.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
1429
+ }
1430
+ const socketSdk = await (0, _sdk$h.setupSdk)(apiKey);
1431
+ const spinner = (0, _ora$h.default)('Fetching organizations...').start();
1432
+ const result = await (0, _apiHelpers$h.handleApiCall)(socketSdk.getOrganizations(), 'looking up organizations');
1433
+ if (result.success === false) {
1434
+ (0, _apiHelpers$h.handleUnsuccessfulApiResponse)('getOrganizations', result, spinner);
1435
+ return;
1436
+ }
1437
+ spinner.stop();
1438
+ const organizations = Object.values(result.data.organizations);
1439
+ console.log(`List of organizations associated with your API key: ${_chalk$g.default.italic(apiKey)}`);
1440
+ for (const o of organizations) {
1441
+ console.log(`
1442
+ Name: ${o?.name}
1443
+ ID: ${o?.id}
1444
+ Plan: ${o?.plan}
1445
+ `);
1446
+ }
1447
+ }
1448
+
1449
+ var rawNpm$1 = {};
1450
+
1451
+ var _interopRequireDefault$l = vendor.interopRequireDefault.default;
1452
+ Object.defineProperty(rawNpm$1, "__esModule", {
1453
+ value: true
1454
+ });
1455
+ rawNpm$1.rawNpm = void 0;
1456
+ var _promiseSpawn$1 = require$$1$1;
1457
+ var _meow$k = _interopRequireDefault$l(vendor.build);
1458
+ var _flags$h = flags$1;
1459
+ var _formatting$j = formatting;
1460
+ const rawNpm = rawNpm$1.rawNpm = {
1461
+ description: 'Temporarily disable the Socket npm wrapper',
1462
+ async run(argv, importMeta, {
1463
+ parentName
1464
+ }) {
1465
+ await setupCommand$j(`${parentName} raw-npm`, rawNpm.description, argv, importMeta);
1466
+ }
1467
+ };
1468
+ async function setupCommand$j(name, description, argv, importMeta) {
1469
+ const flags = _flags$h.validationFlags;
1470
+ const cli = (0, _meow$k.default)(`
1471
+ Usage
1472
+ $ ${name} <npm command>
1473
+
1474
+ Options
1475
+ ${(0, _formatting$j.printFlagList)(flags, 6)}
1476
+
1477
+ Examples
1478
+ $ ${name} install
1479
+ `, {
1480
+ argv,
1481
+ description,
1482
+ importMeta,
1483
+ flags
1484
+ });
1485
+ if (!argv[0]) {
1486
+ cli.showHelp();
1487
+ return;
1488
+ }
1489
+ const spawnPromise = _promiseSpawn$1('npm', [argv.join(' ')], {
1490
+ stdio: 'inherit'
1491
+ });
1492
+ spawnPromise.process.on('exit', (code, signal) => {
1493
+ if (signal) {
1494
+ process.kill(process.pid, signal);
1495
+ } else if (code !== null) {
1496
+ process.exit(code);
1497
+ }
1498
+ });
1499
+ await spawnPromise;
1500
+ }
1501
+
1502
+ var rawNpx$1 = {};
1503
+
1504
+ var _interopRequireDefault$k = vendor.interopRequireDefault.default;
1505
+ Object.defineProperty(rawNpx$1, "__esModule", {
1506
+ value: true
1507
+ });
1508
+ rawNpx$1.rawNpx = void 0;
1509
+ var _promiseSpawn = require$$1$1;
1510
+ var _meow$j = _interopRequireDefault$k(vendor.build);
1511
+ var _flags$g = flags$1;
1512
+ var _formatting$i = formatting;
1513
+ const rawNpx = rawNpx$1.rawNpx = {
1514
+ description: 'Temporarily disable the Socket npm/npx wrapper',
1515
+ async run(argv, importMeta, {
1516
+ parentName
1517
+ }) {
1518
+ await setupCommand$i(`${parentName} raw-npx`, rawNpx.description, argv, importMeta);
1519
+ }
1520
+ };
1521
+ async function setupCommand$i(name, description, argv, importMeta) {
1522
+ const flags = _flags$g.validationFlags;
1523
+ const cli = (0, _meow$j.default)(`
1524
+ Usage
1525
+ $ ${name} <npx command>
1526
+
1527
+ Options
1528
+ ${(0, _formatting$i.printFlagList)(flags, 6)}
1529
+
1530
+ Examples
1531
+ $ ${name} install
1532
+ `, {
1533
+ argv,
1534
+ description,
1535
+ importMeta,
1536
+ flags
1537
+ });
1538
+ if (!argv[0]) {
1539
+ cli.showHelp();
1540
+ return;
1541
+ }
1542
+ const spawnPromise = _promiseSpawn('npx', [argv.join(' ')], {
1543
+ stdio: 'inherit'
1544
+ });
1545
+ spawnPromise.process.on('exit', (code, signal) => {
1546
+ if (signal) {
1547
+ process.kill(process.pid, signal);
1548
+ } else if (code !== null) {
1549
+ process.exit(code);
1550
+ }
1551
+ });
1552
+ await spawnPromise;
1553
+ }
1554
+
1555
+ var report = {};
1556
+
1557
+ var create$5 = {};
1558
+
1559
+ var view$3 = {};
1560
+
1561
+ var _interopRequireDefault$j = vendor.interopRequireDefault.default;
1562
+ Object.defineProperty(view$3, "__esModule", {
1563
+ value: true
1564
+ });
1565
+ view$3.fetchReportData = fetchReportData;
1566
+ view$3.formatReportDataOutput = formatReportDataOutput;
1567
+ view$3.view = void 0;
1568
+ var _chalk$f = _interopRequireDefault$j(vendor.source);
1569
+ var _meow$i = _interopRequireDefault$j(vendor.build);
1570
+ var _ora$g = _interopRequireDefault$j(vendor.ora);
1571
+ var _ponyCause$3 = require$$6;
1572
+ var _flags$f = flags$1;
1573
+ var _apiHelpers$g = apiHelpers;
1574
+ var _chalkMarkdown$2 = sdk.chalkMarkdown;
1575
+ var _errors$h = sdk.errors;
1576
+ var _formatIssues = formatIssues;
1577
+ var _formatting$h = formatting;
1578
+ var _sdk$g = sdk.sdk;
1579
+ const view$2 = view$3.view = {
1580
+ description: 'View a project report',
1581
+ async run(argv, importMeta, {
1582
+ parentName
1583
+ }) {
1584
+ const name = `${parentName} view`;
1585
+ const commandContext = setupCommand$h(name, view$2.description, argv, importMeta);
1586
+ const result = commandContext ? await fetchReportData(commandContext.reportId, commandContext) : undefined;
1587
+ if (result) {
1588
+ formatReportDataOutput(result, {
1589
+ name,
1590
+ ...(commandContext ?? {})
1591
+ });
1592
+ }
1593
+ }
1594
+ };
1595
+
1596
+ // Internal functions
1597
+
1598
+ function setupCommand$h(name, description, argv, importMeta) {
1599
+ const flags = {
1600
+ __proto__: null,
1601
+ ..._flags$f.outputFlags,
1602
+ ..._flags$f.validationFlags
1603
+ };
1604
+ const cli = (0, _meow$i.default)(`
1605
+ Usage
1606
+ $ ${name} <report-identifier>
1607
+
1608
+ Options
1609
+ ${(0, _formatting$h.printFlagList)(flags, 6)}
1610
+
1611
+ Examples
1612
+ $ ${name} QXU8PmK7LfH608RAwfIKdbcHgwEd_ZeWJ9QEGv05FJUQ
1613
+ `, {
1614
+ argv,
1615
+ description,
1616
+ importMeta,
1617
+ flags
1618
+ });
1619
+
1620
+ // Extract the input
1621
+
1622
+ const {
1623
+ all: includeAllIssues,
1624
+ json: outputJson,
1625
+ markdown: outputMarkdown,
1626
+ strict
1627
+ } = cli.flags;
1628
+ const [reportId, ...extraInput] = cli.input;
1629
+ if (!reportId) {
1630
+ cli.showHelp();
1631
+ return;
1632
+ }
1633
+
1634
+ // Validate the input
1635
+
1636
+ if (extraInput.length) {
1637
+ throw new _errors$h.InputError(`Can only handle a single report ID at a time, but got ${cli.input.length} report ID:s: ${cli.input.join(', ')}`);
1638
+ }
1639
+ return {
1640
+ includeAllIssues,
1641
+ outputJson,
1642
+ outputMarkdown,
1643
+ reportId,
1644
+ strict
1645
+ };
1646
+ }
1647
+ const MAX_TIMEOUT_RETRY = 5;
1648
+ async function fetchReportData(reportId, {
1649
+ includeAllIssues,
1650
+ strict
1651
+ }) {
1652
+ // Do the API call
1653
+
1654
+ const socketSdk = await (0, _sdk$g.setupSdk)();
1655
+ const spinner = (0, _ora$g.default)(`Fetching report with ID ${reportId} (this could take a while)`).start();
1656
+ let result;
1657
+ for (let retry = 1; !result; ++retry) {
1658
+ try {
1659
+ result = await (0, _apiHelpers$g.handleApiCall)(socketSdk.getReport(reportId), 'fetching report');
1660
+ } catch (err) {
1661
+ if (retry >= MAX_TIMEOUT_RETRY || !(err instanceof _ponyCause$3.ErrorWithCause) || err.cause?.cause?.response?.statusCode !== 524) {
1662
+ throw err;
1663
+ }
1664
+ }
1665
+ }
1666
+ if (result.success === false) {
1667
+ return (0, _apiHelpers$g.handleUnsuccessfulApiResponse)('getReport', result, spinner);
1668
+ }
1669
+
1670
+ // Conclude the status of the API call
1671
+
1672
+ if (strict) {
1673
+ if (result.data.healthy) {
1674
+ spinner.succeed('Report result is healthy and great!');
1675
+ } else {
1676
+ spinner.fail('Report result deemed unhealthy for project');
1677
+ }
1678
+ } else if (result.data.healthy === false) {
1679
+ const severityCount = (0, _formatIssues.getSeverityCount)(result.data.issues, includeAllIssues ? undefined : 'high');
1680
+ const issueSummary = (0, _formatIssues.formatSeverityCount)(severityCount);
1681
+ spinner.succeed(`Report has these issues: ${issueSummary}`);
1682
+ } else {
1683
+ spinner.succeed('Report has no issues');
1684
+ }
1685
+ return result.data;
1686
+ }
1687
+ function formatReportDataOutput(data, {
1688
+ name,
1689
+ outputJson,
1690
+ outputMarkdown,
1691
+ reportId,
1692
+ strict
1693
+ }) {
1694
+ if (outputJson) {
1695
+ console.log(JSON.stringify(data, undefined, 2));
1696
+ } else {
1697
+ const format = new _chalkMarkdown$2.ChalkOrMarkdown(!!outputMarkdown);
1698
+ console.log('\nDetailed info on socket.dev: ' + format.hyperlink(reportId, data.url, {
1699
+ fallbackToUrl: true
1700
+ }));
1701
+ if (!outputMarkdown) {
1702
+ console.log(_chalk$f.default.dim('\nOr rerun', _chalk$f.default.italic(name), 'using the', _chalk$f.default.italic('--json'), 'flag to get full JSON output'));
1703
+ }
1704
+ }
1705
+ if (strict && data.healthy === false) {
1706
+ process.exit(1);
1707
+ }
1708
+ }
1709
+
1710
+ var _interopRequireDefault$i = vendor.interopRequireDefault.default;
1711
+ Object.defineProperty(create$5, "__esModule", {
1712
+ value: true
1713
+ });
1714
+ create$5.create = void 0;
1715
+ var _nodePath$1 = require$$1;
1716
+ var _betterAjvErrors = require$$2;
1717
+ var _config = require$$3$3;
1718
+ var _meow$h = _interopRequireDefault$i(vendor.build);
1719
+ var _ora$f = _interopRequireDefault$i(vendor.ora);
1720
+ var _ponyCause$2 = require$$6;
1721
+ var _view$2 = view$3;
1722
+ var _flags$e = flags$1;
1723
+ var _apiHelpers$f = apiHelpers;
1724
+ var _chalkMarkdown$1 = sdk.chalkMarkdown;
1725
+ var _errors$g = sdk.errors;
1726
+ var _formatting$g = formatting;
1727
+ var _misc$1 = sdk.misc;
1728
+ var _pathResolve$1 = pathResolve.pathResolve;
1729
+ var _sdk$f = sdk.sdk;
1730
+ const create$4 = create$5.create = {
1731
+ description: 'Create a project report',
1732
+ async run(argv, importMeta, {
1733
+ parentName
1734
+ }) {
1735
+ const name = `${parentName} create`;
1736
+ const input = await setupCommand$g(name, create$4.description, argv, importMeta);
1737
+ if (input) {
1738
+ const {
1739
+ config,
1740
+ cwd,
1741
+ debugLog,
1742
+ dryRun,
1743
+ includeAllIssues,
1744
+ outputJson,
1745
+ outputMarkdown,
1746
+ packagePaths,
1747
+ strict,
1748
+ view
1749
+ } = input;
1750
+ const result = input && (await createReport(packagePaths, {
1751
+ config,
1752
+ cwd,
1753
+ debugLog,
1754
+ dryRun
1755
+ }));
1756
+ if (result && view) {
1757
+ const reportId = result.data.id;
1758
+ const reportData = input && (await (0, _view$2.fetchReportData)(reportId, {
1759
+ includeAllIssues,
1760
+ strict
1761
+ }));
1762
+ if (reportData) {
1763
+ (0, _view$2.formatReportDataOutput)(reportData, {
1764
+ includeAllIssues,
1765
+ name,
1766
+ outputJson,
1767
+ outputMarkdown,
1768
+ reportId,
1769
+ strict
1770
+ });
1771
+ }
1772
+ } else if (result) {
1773
+ formatReportCreationOutput(result.data, {
1774
+ outputJson,
1775
+ outputMarkdown
1776
+ });
1777
+ }
1778
+ }
1779
+ }
1780
+ };
1781
+
1782
+ // Internal functions
1783
+
1784
+ async function setupCommand$g(name, description, argv, importMeta) {
1785
+ const flags = {
1786
+ __proto__: null,
1787
+ ..._flags$e.outputFlags,
1788
+ ..._flags$e.validationFlags,
1789
+ debug: {
1790
+ type: 'boolean',
1791
+ shortFlag: 'd',
1792
+ default: false,
1793
+ description: 'Output debug information'
1794
+ },
1795
+ dryRun: {
1796
+ type: 'boolean',
1797
+ default: false,
1798
+ description: 'Only output what will be done without actually doing it'
1799
+ },
1800
+ view: {
1801
+ type: 'boolean',
1802
+ shortFlag: 'v',
1803
+ default: false,
1804
+ description: 'Will wait for and return the created report'
1805
+ }
1806
+ };
1807
+ const cli = (0, _meow$h.default)(`
1808
+ Usage
1809
+ $ ${name} <paths-to-package-folders-and-files>
1810
+
1811
+ Uploads the specified "package.json" and lock files for JavaScript, Python, and Go dependency manifests.
1812
+ If any folder is specified, the ones found in there recursively are uploaded.
1813
+
1814
+ Supports globbing such as "**/package.json", "**/requirements.txt", "**/pyproject.toml", and "**/go.mod".
1815
+
1816
+ Ignores any file specified in your project's ".gitignore", your project's
1817
+ "socket.yml" file's "projectIgnorePaths" and also has a sensible set of
1818
+ default ignores from the "ignore-by-default" module.
1819
+
1820
+ Options
1821
+ ${(0, _formatting$g.printFlagList)({
1822
+ all: 'Include all issues',
1823
+ debug: 'Output debug information',
1824
+ 'dry-run': 'Only output what will be done without actually doing it',
1825
+ json: 'Output result as json',
1826
+ markdown: 'Output result as markdown',
1827
+ strict: 'Exits with an error code if any matching issues are found',
1828
+ view: 'Will wait for and return the created report'
1829
+ }, 6)}
1830
+
1831
+ Examples
1832
+ $ ${name} .
1833
+ $ ${name} '**/package.json'
1834
+ $ ${name} /path/to/a/package.json /path/to/another/package.json
1835
+ $ ${name} . --view --json
1836
+ `, {
1837
+ argv,
1838
+ description,
1839
+ importMeta,
1840
+ flags
1841
+ });
1842
+ const {
1843
+ all: includeAllIssues,
1844
+ dryRun,
1845
+ json: outputJson,
1846
+ markdown: outputMarkdown,
1847
+ strict,
1848
+ view
1849
+ } = cli.flags;
1850
+ if (!cli.input[0]) {
1851
+ cli.showHelp();
1852
+ return;
1853
+ }
1854
+ const debugLog = (0, _misc$1.createDebugLogger)(!dryRun || cli.flags['debug']);
1855
+
1856
+ // TODO: Allow setting a custom cwd and/or configFile path?
1857
+ const cwd = process.cwd();
1858
+ const absoluteConfigPath = _nodePath$1.join(cwd, 'socket.yml');
1859
+ const config = await (0, _config.readSocketConfig)(absoluteConfigPath).catch(cause => {
1860
+ if (cause && typeof cause === 'object' && cause instanceof _config.SocketValidationError) {
1861
+ // Inspired by workbox-build:
1862
+ // https://github.com/GoogleChrome/workbox/blob/95f97a207fd51efb3f8a653f6e3e58224183a778/packages/workbox-build/src/lib/validate-options.ts#L68-L71
1863
+ const betterErrors = (0, _betterAjvErrors.betterAjvErrors)({
1864
+ basePath: 'config',
1865
+ data: cause.data,
1866
+ errors: cause.validationErrors,
1867
+ schema: cause.schema
1868
+ });
1869
+ throw new _errors$g.InputError('The socket.yml config is not valid', betterErrors.map(err => `[${err.path}] ${err.message}.${err.suggestion ? err.suggestion : ''}`).join('\n'));
1870
+ } else {
1871
+ throw new _ponyCause$2.ErrorWithCause('Failed to read socket.yml config', {
1872
+ cause
1873
+ });
1874
+ }
1875
+ });
1876
+ const socketSdk = await (0, _sdk$f.setupSdk)();
1877
+ const supportedFiles = await socketSdk.getReportSupportedFiles().then(res => {
1878
+ if (!res.success) (0, _apiHelpers$f.handleUnsuccessfulApiResponse)('getReportSupportedFiles', res, (0, _ora$f.default)());
1879
+ return res.data;
1880
+ }).catch(cause => {
1881
+ throw new _ponyCause$2.ErrorWithCause('Failed getting supported files for report', {
1882
+ cause
1883
+ });
1884
+ });
1885
+ const packagePaths = await (0, _pathResolve$1.getPackageFiles)(cwd, cli.input, config, supportedFiles, debugLog);
1886
+ return {
1887
+ config,
1888
+ cwd,
1889
+ debugLog,
1890
+ dryRun,
1891
+ includeAllIssues,
1892
+ outputJson,
1893
+ outputMarkdown,
1894
+ packagePaths,
1895
+ strict,
1896
+ view
1897
+ };
1898
+ }
1899
+ async function createReport(packagePaths, {
1900
+ config,
1901
+ cwd,
1902
+ debugLog,
1903
+ dryRun
1904
+ }) {
1905
+ debugLog('Uploading:', packagePaths.join(`\n${_chalkMarkdown$1.logSymbols.info} Uploading: `));
1906
+ if (dryRun) {
1907
+ return;
1908
+ }
1909
+ const socketSdk = await (0, _sdk$f.setupSdk)();
1910
+ const spinner = (0, _ora$f.default)(`Creating report with ${packagePaths.length} package files`).start();
1911
+ const apiCall = socketSdk.createReportFromFilePaths(packagePaths, cwd, config?.issueRules);
1912
+ const result = await (0, _apiHelpers$f.handleApiCall)(apiCall, 'creating report');
1913
+ if (result.success === false) {
1914
+ return (0, _apiHelpers$f.handleUnsuccessfulApiResponse)('createReport', result, spinner);
1915
+ }
1916
+
1917
+ // Conclude the status of the API call
1918
+
1919
+ spinner.succeed();
1920
+ return result;
1921
+ }
1922
+ function formatReportCreationOutput(data, {
1923
+ outputJson,
1924
+ outputMarkdown
1925
+ }) {
1926
+ if (outputJson) {
1927
+ console.log(JSON.stringify(data, undefined, 2));
1928
+ return;
1929
+ }
1930
+ const format = new _chalkMarkdown$1.ChalkOrMarkdown(!!outputMarkdown);
1931
+ console.log('\nNew report: ' + format.hyperlink(data.id, data.url, {
1932
+ fallbackToUrl: true
1933
+ }));
1934
+ }
1935
+
1936
+ var meowWithSubcommands$1 = {};
1937
+
1938
+ var _interopRequireDefault$h = vendor.interopRequireDefault.default;
1939
+ Object.defineProperty(meowWithSubcommands$1, "__esModule", {
1940
+ value: true
1941
+ });
1942
+ meowWithSubcommands$1.meowWithSubcommands = meowWithSubcommands;
1943
+ var _meow$g = _interopRequireDefault$h(vendor.build);
1944
+ var _formatting$f = formatting;
1945
+ var _sorts = sorts;
1946
+ async function meowWithSubcommands(subcommands, options) {
1947
+ const {
1948
+ aliases = {},
1949
+ argv,
1950
+ name,
1951
+ importMeta,
1952
+ ...additionalOptions
1953
+ } = options;
1954
+ const [commandOrAliasName, ...rawCommandArgv] = argv;
1955
+
1956
+ // If we got at least some args, then lets find out if we can find a command
1957
+ if (commandOrAliasName) {
1958
+ const alias = aliases[commandOrAliasName];
1959
+
1960
+ // First: Resolve argv data from alias if its an alias that's been given
1961
+ const [commandName, ...commandArgv] = alias ? [...alias.argv, ...rawCommandArgv] : [commandOrAliasName, ...rawCommandArgv];
1962
+
1963
+ // Second: Find a command definition using that data
1964
+ const commandDefinition = commandName ? subcommands[commandName] : undefined;
1965
+
1966
+ // Third: If a valid command has been found, then we run it...
1967
+ if (commandDefinition) {
1968
+ return await commandDefinition.run(commandArgv, importMeta, {
1969
+ parentName: name
1970
+ });
1971
+ }
1972
+ }
1973
+
1974
+ // ...else we provide basic instructions and help
1975
+ const cli = (0, _meow$g.default)(`
1976
+ Usage
1977
+ $ ${name} <command>
1978
+
1979
+ Commands
1980
+ ${(0, _formatting$f.printHelpList)({
1981
+ ...(0, _sorts.toSortedObject)(subcommands),
1982
+ ...(0, _sorts.toSortedObject)(aliases)
1983
+ }, 6)}
1984
+
1985
+ Options
1986
+ ${(0, _formatting$f.printFlagList)({}, 6)}
1987
+
1988
+ Examples
1989
+ $ ${name} --help
1990
+ `, {
1991
+ argv,
1992
+ importMeta,
1993
+ ...additionalOptions
1994
+ });
1995
+ cli.showHelp();
1996
+ }
1997
+
1998
+ Object.defineProperty(report, "__esModule", {
1999
+ value: true
2000
+ });
2001
+ report.report = void 0;
2002
+ var _create$2 = create$5;
2003
+ var _view$1 = view$3;
2004
+ var _meowWithSubcommands$4 = meowWithSubcommands$1;
2005
+ const description$3 = '[Deprecated] Project report related commands';
2006
+ report.report = {
2007
+ description: description$3,
2008
+ async run(argv, importMeta, {
2009
+ parentName
2010
+ }) {
2011
+ await (0, _meowWithSubcommands$4.meowWithSubcommands)({
2012
+ create: _create$2.create,
2013
+ view: _view$1.view
2014
+ }, {
2015
+ argv,
2016
+ description: description$3,
2017
+ importMeta,
2018
+ name: parentName + ' report'
2019
+ });
2020
+ }
2021
+ };
2022
+
2023
+ var wrapper$1 = {};
2024
+
2025
+ var _interopRequireDefault$g = vendor.interopRequireDefault.default;
2026
+ Object.defineProperty(wrapper$1, "__esModule", {
2027
+ value: true
2028
+ });
2029
+ wrapper$1.wrapper = void 0;
2030
+ var _nodeFs$3 = require$$0;
2031
+ var _nodeOs = require$$2$1;
2032
+ var _nodeReadline = require$$3$4;
2033
+ var _meow$f = _interopRequireDefault$g(vendor.build);
2034
+ var _flags$d = flags$1;
2035
+ var _formatting$e = formatting;
2036
+ const BASH_FILE = `${_nodeOs.homedir()}/.bashrc`;
2037
+ const ZSH_BASH_FILE = `${_nodeOs.homedir()}/.zshrc`;
2038
+ const wrapper = wrapper$1.wrapper = {
2039
+ description: 'Enable or disable the Socket npm/npx wrapper',
2040
+ async run(argv, importMeta, {
2041
+ parentName
2042
+ }) {
2043
+ setupCommand$f(`${parentName} wrapper`, wrapper.description, argv, importMeta);
2044
+ }
2045
+ };
2046
+ function setupCommand$f(name, description, argv, importMeta) {
2047
+ const flags = _flags$d.commandFlags;
2048
+ const cli = (0, _meow$f.default)(`
2049
+ Usage
2050
+ $ ${name} <flag>
2051
+
2052
+ Options
2053
+ ${(0, _formatting$e.printFlagList)(flags, 6)}
2054
+
2055
+ Examples
2056
+ $ ${name} --enable
2057
+ $ ${name} --disable
2058
+ `, {
2059
+ argv,
2060
+ description,
2061
+ importMeta,
2062
+ flags
2063
+ });
2064
+ const {
2065
+ enable,
2066
+ disable
2067
+ } = cli.flags;
2068
+ if (argv[0] === '--postinstall') {
2069
+ const socketWrapperEnabled = _nodeFs$3.existsSync(BASH_FILE) && checkSocketWrapperAlreadySetup(BASH_FILE) || _nodeFs$3.existsSync(ZSH_BASH_FILE) && checkSocketWrapperAlreadySetup(ZSH_BASH_FILE);
2070
+ if (!socketWrapperEnabled) {
2071
+ installSafeNpm(`The Socket CLI is now successfully installed! 🎉
2072
+
2073
+ To better protect yourself against supply-chain attacks, our "safe npm" wrapper can warn you about malicious packages whenever you run 'npm install'.
2074
+
2075
+ Do you want to install "safe npm" (this will create an alias to the socket-npm command)? (y/n)`);
2076
+ }
2077
+ return;
2078
+ }
2079
+ if (!enable && !disable) {
2080
+ cli.showHelp();
2081
+ return;
2082
+ }
2083
+ if (enable) {
2084
+ if (_nodeFs$3.existsSync(BASH_FILE)) {
2085
+ const socketWrapperEnabled = checkSocketWrapperAlreadySetup(BASH_FILE);
2086
+ !socketWrapperEnabled && addAlias(BASH_FILE);
2087
+ }
2088
+ if (_nodeFs$3.existsSync(ZSH_BASH_FILE)) {
2089
+ const socketWrapperEnabled = checkSocketWrapperAlreadySetup(ZSH_BASH_FILE);
2090
+ !socketWrapperEnabled && addAlias(ZSH_BASH_FILE);
2091
+ }
2092
+ } else if (disable) {
2093
+ if (_nodeFs$3.existsSync(BASH_FILE)) {
2094
+ removeAlias(BASH_FILE);
2095
+ }
2096
+ if (_nodeFs$3.existsSync(ZSH_BASH_FILE)) {
2097
+ removeAlias(ZSH_BASH_FILE);
2098
+ }
2099
+ }
2100
+ if (!_nodeFs$3.existsSync(BASH_FILE) && !_nodeFs$3.existsSync(ZSH_BASH_FILE)) {
2101
+ console.error('There was an issue setting up the alias in your bash profile');
2102
+ }
2103
+ return;
2104
+ }
2105
+ const installSafeNpm = query => {
2106
+ console.log(`
2107
+ _____ _ _
2108
+ | __|___ ___| |_ ___| |_
2109
+ |__ | . | _| '_| -_| _|
2110
+ |_____|___|___|_,_|___|_|
2111
+
2112
+ `);
2113
+ const rl = _nodeReadline.createInterface({
2114
+ input: process.stdin,
2115
+ output: process.stdout
2116
+ });
2117
+ return askQuestion(rl, query);
2118
+ };
2119
+ const askQuestion = (rl, query) => {
2120
+ rl.question(query, ans => {
2121
+ if (ans.toLowerCase() === 'y') {
2122
+ try {
2123
+ if (_nodeFs$3.existsSync(BASH_FILE)) {
2124
+ addAlias(BASH_FILE);
2125
+ }
2126
+ if (_nodeFs$3.existsSync(ZSH_BASH_FILE)) {
2127
+ addAlias(ZSH_BASH_FILE);
2128
+ }
2129
+ } catch (e) {
2130
+ throw new Error(`There was an issue setting up the alias: ${e}`);
2131
+ }
2132
+ rl.close();
2133
+ } else if (ans.toLowerCase() !== 'n') {
2134
+ askQuestion(rl, 'Incorrect input: please enter either y (yes) or n (no): ');
2135
+ } else {
2136
+ rl.close();
2137
+ }
2138
+ });
2139
+ };
2140
+ const addAlias = file => {
2141
+ return _nodeFs$3.appendFile(file, 'alias npm="socket npm"\nalias npx="socket npx"\n', err => {
2142
+ if (err) {
2143
+ return new Error(`There was an error setting up the alias: ${err}`);
2144
+ }
2145
+ console.log(`
2146
+ The alias was added to ${file}. Running 'npm install' will now be wrapped in Socket's "safe npm" 🎉
2147
+ If you want to disable it at any time, run \`socket wrapper --disable\`
2148
+ `);
2149
+ });
2150
+ };
2151
+ const removeAlias = file => {
2152
+ return _nodeFs$3.readFile(file, 'utf8', function (err, data) {
2153
+ if (err) {
2154
+ console.error(`There was an error removing the alias: ${err}`);
2155
+ return;
2156
+ }
2157
+ const linesWithoutSocketAlias = data.split('\n').filter(l => l !== 'alias npm="socket npm"' && l !== 'alias npx="socket npx"');
2158
+ const updatedFileContent = linesWithoutSocketAlias.join('\n');
2159
+ _nodeFs$3.writeFile(file, updatedFileContent, function (err) {
2160
+ if (err) {
2161
+ console.log(err);
2162
+ return;
2163
+ } else {
2164
+ console.log(`\nThe alias was removed from ${file}. Running 'npm install' will now run the standard npm command.\n`);
2165
+ }
2166
+ });
2167
+ });
2168
+ };
2169
+ const checkSocketWrapperAlreadySetup = file => {
2170
+ const fileContent = _nodeFs$3.readFileSync(file, 'utf-8');
2171
+ const linesWithSocketAlias = fileContent.split('\n').filter(l => l === 'alias npm="socket npm"' || l === 'alias npx="socket npx"');
2172
+ if (linesWithSocketAlias.length) {
2173
+ console.log(`The Socket npm/npx wrapper is set up in your bash profile (${file}).`);
2174
+ return true;
2175
+ }
2176
+ return false;
2177
+ };
2178
+
2179
+ var scan = {};
2180
+
2181
+ var create$3 = {};
2182
+
2183
+ var _interopRequireDefault$f = vendor.interopRequireDefault.default;
2184
+ Object.defineProperty(create$3, "__esModule", {
2185
+ value: true
2186
+ });
2187
+ create$3.create = void 0;
2188
+ var _nodeProcess = require$$0$1;
2189
+ var _promises = require$$2$2;
2190
+ var _chalk$e = _interopRequireDefault$f(vendor.source);
2191
+ var _meow$e = _interopRequireDefault$f(vendor.build);
2192
+ var _open = _interopRequireDefault$f(vendor.open);
2193
+ var _ora$e = _interopRequireDefault$f(vendor.ora);
2194
+ var _ponyCause$1 = require$$6;
2195
+ var _apiHelpers$e = apiHelpers;
2196
+ var _errors$f = sdk.errors;
2197
+ var _formatting$d = formatting;
2198
+ var _misc = sdk.misc;
2199
+ var _pathResolve = pathResolve.pathResolve;
2200
+ var _sdk$e = sdk.sdk;
2201
+ const create$2 = create$3.create = {
2202
+ description: 'Create a scan',
2203
+ async run(argv, importMeta, {
2204
+ parentName
2205
+ }) {
2206
+ const name = `${parentName} create`;
2207
+ const input = await setupCommand$e(name, create$2.description, argv, importMeta);
2208
+ if (input) {
2209
+ const apiKey = (0, _sdk$e.getDefaultKey)();
2210
+ if (!apiKey) {
2211
+ throw new _errors$f.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
2212
+ }
2213
+ const spinnerText = 'Creating a scan... \n';
2214
+ const spinner = (0, _ora$e.default)(spinnerText).start();
2215
+ await createFullScan(input, spinner, apiKey);
2216
+ }
2217
+ }
2218
+ };
2219
+ const createFullScanFlags = {
2220
+ repo: {
2221
+ type: 'string',
2222
+ shortFlag: 'r',
2223
+ default: '',
2224
+ description: 'Repository name'
2225
+ },
2226
+ branch: {
2227
+ type: 'string',
2228
+ shortFlag: 'b',
2229
+ default: '',
2230
+ description: 'Branch name'
2231
+ },
2232
+ commitMessage: {
2233
+ type: 'string',
2234
+ shortFlag: 'm',
2235
+ default: '',
2236
+ description: 'Commit message'
2237
+ },
2238
+ commitHash: {
2239
+ type: 'string',
2240
+ shortFlag: 'ch',
2241
+ default: '',
2242
+ description: 'Commit hash'
2243
+ },
2244
+ pullRequest: {
2245
+ type: 'number',
2246
+ shortFlag: 'pr',
2247
+ description: 'Commit hash'
2248
+ },
2249
+ committers: {
2250
+ type: 'string',
2251
+ shortFlag: 'c',
2252
+ default: '',
2253
+ description: 'Committers'
2254
+ },
2255
+ defaultBranch: {
2256
+ type: 'boolean',
2257
+ shortFlag: 'db',
2258
+ default: false,
2259
+ description: 'Make default branch'
2260
+ },
2261
+ pendingHead: {
2262
+ type: 'boolean',
2263
+ shortFlag: 'ph',
2264
+ default: false,
2265
+ description: 'Set as pending head'
2266
+ },
2267
+ tmp: {
2268
+ type: 'boolean',
2269
+ shortFlag: 't',
2270
+ default: false,
2271
+ description: 'Set the visibility (true/false) of the scan in your dashboard'
2272
+ }
2273
+ };
2274
+
2275
+ // Internal functions
2276
+
2277
+ async function setupCommand$e(name, description, argv, importMeta) {
2278
+ const flags = {
2279
+ ...createFullScanFlags
2280
+ };
2281
+ const cli = (0, _meow$e.default)(`
2282
+ Usage
2283
+ $ ${name} [...options]
2284
+
2285
+ Options
2286
+ ${(0, _formatting$d.printFlagList)(flags, 6)}
2287
+
2288
+ Examples
2289
+ $ ${name} --org=FakeOrg --repo=test-repo --branch=main ./package.json
2290
+ `, {
2291
+ argv,
2292
+ description,
2293
+ importMeta,
2294
+ flags
2295
+ });
2296
+ const {
2297
+ repo: repoName,
2298
+ branch: branchName,
2299
+ commitMessage,
2300
+ defaultBranch,
2301
+ pendingHead,
2302
+ tmp,
2303
+ committers,
2304
+ commitHash,
2305
+ pullRequest
2306
+ } = cli.flags;
2307
+ if (!cli.input[0]) {
2308
+ cli.showHelp();
2309
+ return;
2310
+ }
2311
+ const {
2312
+ 0: orgSlug = ''
2313
+ } = cli.input;
2314
+ const cwd = process.cwd();
2315
+ const socketSdk = await (0, _sdk$e.setupSdk)();
2316
+ const supportedFiles = await socketSdk.getReportSupportedFiles().then(res => {
2317
+ if (!res.success) (0, _apiHelpers$e.handleUnsuccessfulApiResponse)('getReportSupportedFiles', res, (0, _ora$e.default)());
2318
+ return res.data;
2319
+ }).catch(/** @type {(cause: Error) => never} */
2320
+ cause => {
2321
+ throw new _ponyCause$1.ErrorWithCause('Failed getting supported files for report', {
2322
+ cause
2323
+ });
2324
+ });
2325
+ const debugLog = (0, _misc.createDebugLogger)(false);
2326
+ const packagePaths = await (0, _pathResolve.getPackageFilesFullScans)(cwd, cli.input, supportedFiles, debugLog);
2327
+ if (!repoName || !branchName || !packagePaths.length) {
2328
+ console.error(`${_chalk$e.default.white.bgRed('Input error')}: Please provide the required fields:\n
2329
+ - Repository name using --repo,\n
2330
+ - Branch name using --branch\n
2331
+ - At least one file path (e.g. ./package.json).\n`);
2332
+ cli.showHelp();
2333
+ return;
2334
+ }
2335
+ return {
2336
+ orgSlug,
2337
+ repoName,
2338
+ branchName,
2339
+ commitMessage,
2340
+ defaultBranch,
2341
+ pendingHead,
2342
+ tmp,
2343
+ packagePaths,
2344
+ commitHash,
2345
+ committers,
2346
+ pullRequest
2347
+ };
2348
+ }
2349
+ async function createFullScan(input, spinner, apiKey) {
2350
+ const socketSdk = await (0, _sdk$e.setupSdk)(apiKey);
2351
+ const {
2352
+ orgSlug,
2353
+ repoName,
2354
+ branchName,
2355
+ commitMessage,
2356
+ defaultBranch,
2357
+ pendingHead,
2358
+ tmp,
2359
+ packagePaths
2360
+ } = input;
2361
+ const result = await (0, _apiHelpers$e.handleApiCall)(socketSdk.createOrgFullScan(orgSlug, {
2362
+ repo: repoName,
2363
+ branch: branchName,
2364
+ commit_message: commitMessage,
2365
+ make_default_branch: defaultBranch,
2366
+ set_as_pending_head: pendingHead,
2367
+ tmp
2368
+ }, packagePaths), 'Creating scan');
2369
+ if (!result.success) {
2370
+ (0, _apiHelpers$e.handleUnsuccessfulApiResponse)('CreateOrgFullScan', result, spinner);
2371
+ return;
2372
+ }
2373
+ spinner.stop();
2374
+ console.log('\n✅ Scan created successfully\n');
2375
+ const link = _chalk$e.default.hex('#00FFFF').underline(`${result.data.html_report_url}`);
2376
+ console.log(`Available at: ${link}\n`);
2377
+ const rl = _promises.createInterface({
2378
+ input: _nodeProcess.stdin,
2379
+ output: _nodeProcess.stdout
2380
+ });
2381
+ const answer = await rl.question('Would you like to open it in your browser? (y/n)');
2382
+ if (answer.toLowerCase() === 'y') {
2383
+ await (0, _open.default)(`${result.data.html_report_url}`);
2384
+ }
2385
+ rl.close();
2386
+ }
2387
+
2388
+ var _delete$3 = {};
2389
+
2390
+ var _interopRequireDefault$e = vendor.interopRequireDefault.default;
2391
+ Object.defineProperty(_delete$3, "__esModule", {
2392
+ value: true
2393
+ });
2394
+ _delete$3.del = void 0;
2395
+ var _chalk$d = _interopRequireDefault$e(vendor.source);
2396
+ var _meow$d = _interopRequireDefault$e(vendor.build);
2397
+ var _ora$d = _interopRequireDefault$e(vendor.ora);
2398
+ var _flags$c = flags$1;
2399
+ var _apiHelpers$d = apiHelpers;
2400
+ var _errors$e = sdk.errors;
2401
+ var _formatting$c = formatting;
2402
+ var _sdk$d = sdk.sdk;
2403
+ const del$1 = _delete$3.del = {
2404
+ description: 'Delete a scan',
2405
+ async run(argv, importMeta, {
2406
+ parentName
2407
+ }) {
2408
+ const name = `${parentName} del`;
2409
+ const input = setupCommand$d(name, del$1.description, argv, importMeta);
2410
+ if (input) {
2411
+ const apiKey = (0, _sdk$d.getDefaultKey)();
2412
+ if (!apiKey) {
2413
+ throw new _errors$e.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
2414
+ }
2415
+ const spinnerText = 'Deleting scan...';
2416
+ const spinner = (0, _ora$d.default)(spinnerText).start();
2417
+ await deleteOrgFullScan(input.orgSlug, input.fullScanId, spinner, apiKey);
2418
+ }
2419
+ }
2420
+ };
2421
+
2422
+ // Internal functions
2423
+
2424
+ function setupCommand$d(name, description, argv, importMeta) {
2425
+ const flags = {
2426
+ ..._flags$c.outputFlags
2427
+ };
2428
+ const cli = (0, _meow$d.default)(`
2429
+ Usage
2430
+ $ ${name} <org slug> <scan ID>
2431
+
2432
+ Options
2433
+ ${(0, _formatting$c.printFlagList)(flags, 6)}
2434
+
2435
+ Examples
2436
+ $ ${name} FakeOrg 000aaaa1-0000-0a0a-00a0-00a0000000a0
2437
+ `, {
2438
+ argv,
2439
+ description,
2440
+ importMeta,
2441
+ flags
2442
+ });
2443
+ const {
2444
+ json: outputJson,
2445
+ markdown: outputMarkdown
2446
+ } = cli.flags;
2447
+ if (cli.input.length < 2) {
2448
+ console.error(`${_chalk$d.default.white.bgRed('Input error')}: Please specify an organization slug and a scan ID.\n`);
2449
+ cli.showHelp();
2450
+ return;
2451
+ }
2452
+ const {
2453
+ 0: orgSlug = '',
2454
+ 1: fullScanId = ''
2455
+ } = cli.input;
2456
+ return {
2457
+ outputJson,
2458
+ outputMarkdown,
2459
+ orgSlug,
2460
+ fullScanId
2461
+ };
2462
+ }
2463
+ async function deleteOrgFullScan(orgSlug, fullScanId, spinner, apiKey) {
2464
+ const socketSdk = await (0, _sdk$d.setupSdk)(apiKey);
2465
+ const result = await (0, _apiHelpers$d.handleApiCall)(socketSdk.deleteOrgFullScan(orgSlug, fullScanId), 'Deleting scan');
2466
+ if (!result.success) {
2467
+ (0, _apiHelpers$d.handleUnsuccessfulApiResponse)('deleteOrgFullScan', result, spinner);
2468
+ return;
2469
+ }
2470
+ spinner.stop();
2471
+ console.log('\n ✅ Scan deleted successfully\n');
2472
+ }
2473
+
2474
+ var list$3 = {};
2475
+
2476
+ var _interopRequireDefault$d = vendor.interopRequireDefault.default;
2477
+ Object.defineProperty(list$3, "__esModule", {
2478
+ value: true
2479
+ });
2480
+ list$3.list = void 0;
2481
+ var _chalk$c = _interopRequireDefault$d(vendor.source);
2482
+ var _chalkTable$3 = require$$2$3;
2483
+ var _meow$c = _interopRequireDefault$d(vendor.build);
2484
+ var _ora$c = _interopRequireDefault$d(vendor.ora);
2485
+ var _flags$b = flags$1;
2486
+ var _apiHelpers$c = apiHelpers;
2487
+ var _errors$d = sdk.errors;
2488
+ var _formatting$b = formatting;
2489
+ var _sdk$c = sdk.sdk;
2490
+ // @ts-ignore
2491
+
2492
+ const list$2 = list$3.list = {
2493
+ description: 'List scans for an organization',
2494
+ async run(argv, importMeta, {
2495
+ parentName
2496
+ }) {
2497
+ const name = `${parentName} list`;
2498
+ const input = setupCommand$c(name, list$2.description, argv, importMeta);
2499
+ if (input) {
2500
+ const apiKey = (0, _sdk$c.getDefaultKey)();
2501
+ if (!apiKey) {
2502
+ throw new _errors$d.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
2503
+ }
2504
+ const spinnerText = 'Listing scans... \n';
2505
+ const spinner = (0, _ora$c.default)(spinnerText).start();
2506
+ await listOrgFullScan(input.orgSlug, input, spinner, apiKey);
2507
+ }
2508
+ }
2509
+ };
2510
+ const listFullScanFlags = {
2511
+ sort: {
2512
+ type: 'string',
2513
+ shortFlag: 's',
2514
+ default: 'created_at',
2515
+ description: 'Sorting option (`name` or `created_at`) - default is `created_at`'
2516
+ },
2517
+ direction: {
2518
+ type: 'string',
2519
+ shortFlag: 'd',
2520
+ default: 'desc',
2521
+ description: 'Direction option (`desc` or `asc`) - Default is `desc`'
2522
+ },
2523
+ perPage: {
2524
+ type: 'number',
2525
+ shortFlag: 'pp',
2526
+ default: 30,
2527
+ description: 'Results per page - Default is 30'
2528
+ },
2529
+ page: {
2530
+ type: 'number',
2531
+ shortFlag: 'p',
2532
+ default: 1,
2533
+ description: 'Page number - Default is 1'
2534
+ },
2535
+ fromTime: {
2536
+ type: 'string',
2537
+ shortFlag: 'f',
2538
+ default: '',
2539
+ description: 'From time - as a unix timestamp'
2540
+ },
2541
+ untilTime: {
2542
+ type: 'string',
2543
+ shortFlag: 'u',
2544
+ default: '',
2545
+ description: 'Until time - as a unix timestamp'
2546
+ }
2547
+ };
2548
+
2549
+ // Internal functions
2550
+
2551
+ function setupCommand$c(name, description, argv, importMeta) {
2552
+ const flags = {
2553
+ ..._flags$b.outputFlags,
2554
+ ...listFullScanFlags
2555
+ };
2556
+ const cli = (0, _meow$c.default)(`
2557
+ Usage
2558
+ $ ${name} <org slug>
2559
+
2560
+ Options
2561
+ ${(0, _formatting$b.printFlagList)(flags, 6)}
2562
+
2563
+ Examples
2564
+ $ ${name} FakeOrg
2565
+ `, {
2566
+ argv,
2567
+ description,
2568
+ importMeta,
2569
+ flags
2570
+ });
2571
+ const {
2572
+ json: outputJson,
2573
+ markdown: outputMarkdown,
2574
+ sort,
2575
+ direction,
2576
+ perPage,
2577
+ page,
2578
+ fromTime,
2579
+ untilTime
2580
+ } = cli.flags;
2581
+ if (!cli.input[0]) {
2582
+ console.error(`${_chalk$c.default.white.bgRed('Input error')}: Please specify an organization slug.\n`);
2583
+ cli.showHelp();
2584
+ return;
2585
+ }
2586
+ const {
2587
+ 0: orgSlug = ''
2588
+ } = cli.input;
2589
+ return {
2590
+ outputJson,
2591
+ outputMarkdown,
2592
+ orgSlug,
2593
+ sort,
2594
+ direction,
2595
+ per_page: perPage,
2596
+ page,
2597
+ from_time: fromTime,
2598
+ until_time: untilTime
2599
+ };
2600
+ }
2601
+ async function listOrgFullScan(orgSlug, input, spinner, apiKey) {
2602
+ const socketSdk = await (0, _sdk$c.setupSdk)(apiKey);
2603
+ const result = await (0, _apiHelpers$c.handleApiCall)(socketSdk.getOrgFullScanList(orgSlug, input), 'Listing scans');
2604
+ if (!result.success) {
2605
+ (0, _apiHelpers$c.handleUnsuccessfulApiResponse)('getOrgFullScanList', result, spinner);
2606
+ return;
2607
+ }
2608
+ spinner.stop();
2609
+ console.log(`\n Listing scans for: ${orgSlug}\n`);
2610
+ const options = {
2611
+ columns: [{
2612
+ field: 'id',
2613
+ name: _chalk$c.default.magenta('ID')
2614
+ }, {
2615
+ field: 'report_url',
2616
+ name: _chalk$c.default.magenta('Scan URL')
2617
+ }, {
2618
+ field: 'branch',
2619
+ name: _chalk$c.default.magenta('Branch')
2620
+ }, {
2621
+ field: 'created_at',
2622
+ name: _chalk$c.default.magenta('Created at')
2623
+ }]
2624
+ };
2625
+ const formattedResults = result.data.results.map(d => {
2626
+ return {
2627
+ id: d.id,
2628
+ report_url: _chalk$c.default.underline(`${d.html_report_url}`),
2629
+ created_at: d.created_at ? new Date(d.created_at).toLocaleDateString('en-us', {
2630
+ year: 'numeric',
2631
+ month: 'numeric',
2632
+ day: 'numeric'
2633
+ }) : '',
2634
+ branch: d.branch
2635
+ };
2636
+ });
2637
+ console.log(`${_chalkTable$3(options, formattedResults)}\n`);
2638
+ }
2639
+
2640
+ var metadata$1 = {};
2641
+
2642
+ var _interopRequireDefault$c = vendor.interopRequireDefault.default;
2643
+ Object.defineProperty(metadata$1, "__esModule", {
2644
+ value: true
2645
+ });
2646
+ metadata$1.metadata = void 0;
2647
+ var _chalk$b = _interopRequireDefault$c(vendor.source);
2648
+ var _meow$b = _interopRequireDefault$c(vendor.build);
2649
+ var _ora$b = _interopRequireDefault$c(vendor.ora);
2650
+ var _flags$a = flags$1;
2651
+ var _apiHelpers$b = apiHelpers;
2652
+ var _errors$c = sdk.errors;
2653
+ var _formatting$a = formatting;
2654
+ var _sdk$b = sdk.sdk;
2655
+ const metadata = metadata$1.metadata = {
2656
+ description: "Get a scan's metadata",
2657
+ async run(argv, importMeta, {
2658
+ parentName
2659
+ }) {
2660
+ const name = `${parentName} metadata`;
2661
+ const input = setupCommand$b(name, metadata.description, argv, importMeta);
2662
+ if (input) {
2663
+ const apiKey = (0, _sdk$b.getDefaultKey)();
2664
+ if (!apiKey) {
2665
+ throw new _errors$c.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
2666
+ }
2667
+ const spinnerText = "Getting scan's metadata... \n";
2668
+ const spinner = (0, _ora$b.default)(spinnerText).start();
2669
+ await getOrgScanMetadata(input.orgSlug, input.scanID, spinner, apiKey);
2670
+ }
2671
+ }
2672
+ };
2673
+
2674
+ // Internal functions
2675
+
2676
+ function setupCommand$b(name, description, argv, importMeta) {
2677
+ const flags = {
2678
+ ..._flags$a.outputFlags
2679
+ };
2680
+ const cli = (0, _meow$b.default)(`
2681
+ Usage
2682
+ $ ${name} <org slug> <scan id>
2683
+
2684
+ Options
2685
+ ${(0, _formatting$a.printFlagList)(flags, 6)}
2686
+
2687
+ Examples
2688
+ $ ${name} FakeOrg 000aaaa1-0000-0a0a-00a0-00a0000000a0
2689
+ `, {
2690
+ argv,
2691
+ description,
2692
+ importMeta,
2693
+ flags
2694
+ });
2695
+ const {
2696
+ json: outputJson,
2697
+ markdown: outputMarkdown
2698
+ } = cli.flags;
2699
+ if (cli.input.length < 2) {
2700
+ console.error(`${_chalk$b.default.white.bgRed('Input error')}: Please specify an organization slug and a scan ID.\n`);
2701
+ cli.showHelp();
2702
+ return;
2703
+ }
2704
+ const {
2705
+ 0: orgSlug = '',
2706
+ 1: scanID = ''
2707
+ } = cli.input;
2708
+ return {
2709
+ outputJson,
2710
+ outputMarkdown,
2711
+ orgSlug,
2712
+ scanID
2713
+ };
2714
+ }
2715
+ async function getOrgScanMetadata(orgSlug, scanId, spinner, apiKey) {
2716
+ const socketSdk = await (0, _sdk$b.setupSdk)(apiKey);
2717
+ const result = await (0, _apiHelpers$b.handleApiCall)(socketSdk.getOrgFullScanMetadata(orgSlug, scanId), 'Listing scans');
2718
+ if (!result.success) {
2719
+ (0, _apiHelpers$b.handleUnsuccessfulApiResponse)('getOrgFullScanMetadata', result, spinner);
2720
+ return;
2721
+ }
2722
+ spinner.stop();
2723
+ console.log('\nScan metadata:\n');
2724
+ console.log(result.data);
2725
+ }
2726
+
2727
+ var stream$1 = {};
2728
+
2729
+ var _interopRequireDefault$b = vendor.interopRequireDefault.default;
2730
+ Object.defineProperty(stream$1, "__esModule", {
2731
+ value: true
2732
+ });
2733
+ stream$1.stream = void 0;
2734
+ var _chalk$a = _interopRequireDefault$b(vendor.source);
2735
+ var _meow$a = _interopRequireDefault$b(vendor.build);
2736
+ var _ora$a = _interopRequireDefault$b(vendor.ora);
2737
+ var _flags$9 = flags$1;
2738
+ var _apiHelpers$a = apiHelpers;
2739
+ var _errors$b = sdk.errors;
2740
+ var _formatting$9 = formatting;
2741
+ var _sdk$a = sdk.sdk;
2742
+ const stream = stream$1.stream = {
2743
+ description: 'Stream the output of a scan',
2744
+ async run(argv, importMeta, {
2745
+ parentName
2746
+ }) {
2747
+ const name = `${parentName} stream`;
2748
+ const input = setupCommand$a(name, stream.description, argv, importMeta);
2749
+ if (input) {
2750
+ const apiKey = (0, _sdk$a.getDefaultKey)();
2751
+ if (!apiKey) {
2752
+ throw new _errors$b.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
2753
+ }
2754
+ const spinnerText = 'Streaming scan...\n';
2755
+ const spinner = (0, _ora$a.default)(spinnerText).start();
2756
+ await getOrgFullScan(input.orgSlug, input.fullScanId, input.file, spinner, apiKey);
2757
+ }
2758
+ }
2759
+ };
2760
+
2761
+ // Internal functions
2762
+
2763
+ function setupCommand$a(name, description, argv, importMeta) {
2764
+ const flags = {
2765
+ ..._flags$9.outputFlags
2766
+ };
2767
+ const cli = (0, _meow$a.default)(`
2768
+ Usage
2769
+ $ ${name} <org slug> <scan ID> <path to output file>
2770
+
2771
+ Options
2772
+ ${(0, _formatting$9.printFlagList)(flags, 6)}
2773
+
2774
+ Examples
2775
+ $ ${name} FakeOrg 000aaaa1-0000-0a0a-00a0-00a0000000a0 ./stream.txt
2776
+ `, {
2777
+ argv,
2778
+ description,
2779
+ importMeta,
2780
+ flags
2781
+ });
2782
+ const {
2783
+ json: outputJson,
2784
+ markdown: outputMarkdown
2785
+ } = cli.flags;
2786
+ if (cli.input.length < 2) {
2787
+ console.error(`${_chalk$a.default.white.bgRed('Input error')}: Please specify an organization slug and a scan ID.\n`);
2788
+ cli.showHelp();
2789
+ return;
2790
+ }
2791
+ const {
2792
+ 0: orgSlug = '',
2793
+ 1: fullScanId = '',
2794
+ 2: file
2795
+ } = cli.input;
2796
+ return {
2797
+ outputJson,
2798
+ outputMarkdown,
2799
+ orgSlug,
2800
+ fullScanId,
2801
+ file
2802
+ };
2803
+ }
2804
+ async function getOrgFullScan(orgSlug, fullScanId, file, spinner, apiKey) {
2805
+ const socketSdk = await (0, _sdk$a.setupSdk)(apiKey);
2806
+ const result = await (0, _apiHelpers$a.handleApiCall)(socketSdk.getOrgFullScan(orgSlug, fullScanId, file), 'Streaming a scan');
2807
+ if (!result?.success) {
2808
+ (0, _apiHelpers$a.handleUnsuccessfulApiResponse)('getOrgFullScan', result, spinner);
2809
+ return;
2810
+ }
2811
+ spinner.stop();
2812
+ console.log(file ? `\nFull scan details written to ${file}\n` : '\nFull scan details:\n');
2813
+ }
2814
+
2815
+ Object.defineProperty(scan, "__esModule", {
2816
+ value: true
2817
+ });
2818
+ scan.scan = void 0;
2819
+ var _create$1 = create$3;
2820
+ var _delete$2 = _delete$3;
2821
+ var _list$1 = list$3;
2822
+ var _metadata = metadata$1;
2823
+ var _stream = stream$1;
2824
+ var _meowWithSubcommands$3 = meowWithSubcommands$1;
2825
+ const description$2 = 'Scans related commands';
2826
+ scan.scan = {
2827
+ description: description$2,
2828
+ async run(argv, importMeta, {
2829
+ parentName
2830
+ }) {
2831
+ await (0, _meowWithSubcommands$3.meowWithSubcommands)({
2832
+ create: _create$1.create,
2833
+ stream: _stream.stream,
2834
+ list: _list$1.list,
2835
+ del: _delete$2.del,
2836
+ metadata: _metadata.metadata
2837
+ }, {
2838
+ argv,
2839
+ description: description$2,
2840
+ importMeta,
2841
+ name: parentName + ' scan'
2842
+ });
2843
+ }
2844
+ };
2845
+
2846
+ var auditLog$1 = {};
2847
+
2848
+ var _interopRequireDefault$a = vendor.interopRequireDefault.default;
2849
+ Object.defineProperty(auditLog$1, "__esModule", {
2850
+ value: true
2851
+ });
2852
+ auditLog$1.auditLog = void 0;
2853
+ var _prompts = require$$1$2;
2854
+ var _chalk$9 = _interopRequireDefault$a(vendor.source);
2855
+ var _meow$9 = _interopRequireDefault$a(vendor.build);
2856
+ var _ora$9 = _interopRequireDefault$a(vendor.ora);
2857
+ var _flags$8 = flags$1;
2858
+ var _apiHelpers$9 = apiHelpers;
2859
+ var _errors$a = sdk.errors;
2860
+ var _formatting$8 = formatting;
2861
+ var _sdk$9 = sdk.sdk;
2862
+ const auditLog = auditLog$1.auditLog = {
2863
+ description: 'Look up the audit log for an organization',
2864
+ async run(argv, importMeta, {
2865
+ parentName
2866
+ }) {
2867
+ const name = parentName + ' audit-log';
2868
+ const input = setupCommand$9(name, auditLog.description, argv, importMeta);
2869
+ if (input) {
2870
+ const apiKey = (0, _sdk$9.getDefaultKey)();
2871
+ if (!apiKey) {
2872
+ throw new _errors$a.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
2873
+ }
2874
+ const spinner = (0, _ora$9.default)(`Looking up audit log for ${input.orgSlug}\n`).start();
2875
+ await fetchOrgAuditLog(input.orgSlug, input, spinner, apiKey);
2876
+ }
2877
+ }
2878
+ };
2879
+ const auditLogFlags = {
2880
+ type: {
2881
+ type: 'string',
2882
+ shortFlag: 't',
2883
+ default: '',
2884
+ description: 'Type of log event'
2885
+ },
2886
+ perPage: {
2887
+ type: 'number',
2888
+ shortFlag: 'pp',
2889
+ default: 30,
2890
+ description: 'Results per page - default is 30'
2891
+ },
2892
+ page: {
2893
+ type: 'number',
2894
+ shortFlag: 'p',
2895
+ default: 1,
2896
+ description: 'Page number - default is 1'
2897
+ }
2898
+ };
2899
+
2900
+ // Internal functions
2901
+
2902
+ function setupCommand$9(name, description, argv, importMeta) {
2903
+ const flags = {
2904
+ __proto__: null,
2905
+ ...auditLogFlags,
2906
+ ..._flags$8.outputFlags
2907
+ };
2908
+ const cli = (0, _meow$9.default)(`
2909
+ Usage
2910
+ $ ${name} <org slug>
2911
+
2912
+ Options
2913
+ ${(0, _formatting$8.printFlagList)(flags, 6)}
2914
+
2915
+ Examples
2916
+ $ ${name} FakeOrg
2917
+ `, {
2918
+ argv,
2919
+ description,
2920
+ importMeta,
2921
+ flags
2922
+ });
2923
+ const {
2924
+ json: outputJson,
2925
+ markdown: outputMarkdown,
2926
+ page,
2927
+ perPage
2928
+ } = cli.flags;
2929
+ const type = cli.flags['type'];
2930
+ if (cli.input.length < 1) {
2931
+ console.error(`${_chalk$9.default.white.bgRed('Input error')}: Please provide an organization slug\n`);
2932
+ cli.showHelp();
2933
+ return;
2934
+ }
2935
+ const {
2936
+ 0: orgSlug = ''
2937
+ } = cli.input;
2938
+ return {
2939
+ outputJson,
2940
+ outputMarkdown,
2941
+ orgSlug,
2942
+ type: type && type.charAt(0).toUpperCase() + type.slice(1),
2943
+ page,
2944
+ per_page: perPage
2945
+ };
2946
+ }
2947
+ async function fetchOrgAuditLog(orgSlug, input, spinner, apiKey) {
2948
+ const socketSdk = await (0, _sdk$9.setupSdk)(apiKey);
2949
+ const result = await (0, _apiHelpers$9.handleApiCall)(socketSdk.getAuditLogEvents(orgSlug, input), `Looking up audit log for ${orgSlug}\n`);
2950
+ if (!result.success) {
2951
+ (0, _apiHelpers$9.handleUnsuccessfulApiResponse)('getAuditLogEvents', result, spinner);
2952
+ return;
2953
+ }
2954
+ spinner.stop();
2955
+ const data = [];
2956
+ const logDetails = {};
2957
+ for (const d of result.data.results) {
2958
+ const {
2959
+ created_at
2960
+ } = d;
2961
+ if (created_at) {
2962
+ const name = `${new Date(created_at).toLocaleDateString('en-us', {
2963
+ year: 'numeric',
2964
+ month: 'numeric',
2965
+ day: 'numeric'
2966
+ })} - ${d.user_email} - ${d.type} - ${d.ip_address} - ${d.user_agent}`;
2967
+ data.push({
2968
+ name
2969
+ }, new _prompts.Separator());
2970
+ logDetails[name] = JSON.stringify(d.payload);
2971
+ }
2972
+ }
2973
+ console.log(logDetails[await (0, _prompts.select)({
2974
+ message: input.type ? `\n Audit log for: ${orgSlug} with type: ${input.type}\n` : `\n Audit log for: ${orgSlug}\n`,
2975
+ choices: data,
2976
+ pageSize: 30
2977
+ })]);
2978
+ }
2979
+
2980
+ var repos = {};
2981
+
2982
+ var create$1 = {};
2983
+
2984
+ var _interopRequireDefault$9 = vendor.interopRequireDefault.default;
2985
+ Object.defineProperty(create$1, "__esModule", {
2986
+ value: true
2987
+ });
2988
+ create$1.create = void 0;
2989
+ var _chalk$8 = _interopRequireDefault$9(vendor.source);
2990
+ var _meow$8 = _interopRequireDefault$9(vendor.build);
2991
+ var _ora$8 = _interopRequireDefault$9(vendor.ora);
2992
+ var _flags$7 = flags$1;
2993
+ var _apiHelpers$8 = apiHelpers;
2994
+ var _errors$9 = sdk.errors;
2995
+ var _formatting$7 = formatting;
2996
+ var _sdk$8 = sdk.sdk;
2997
+ const create = create$1.create = {
2998
+ description: 'Create a repository in an organization',
2999
+ async run(argv, importMeta, {
3000
+ parentName
3001
+ }) {
3002
+ const name = `${parentName} create`;
3003
+ const input = setupCommand$8(name, create.description, argv, importMeta);
3004
+ if (input) {
3005
+ const apiKey = (0, _sdk$8.getDefaultKey)();
3006
+ if (!apiKey) {
3007
+ throw new _errors$9.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
3008
+ }
3009
+ const spinnerText = 'Creating repository... \n';
3010
+ const spinner = (0, _ora$8.default)(spinnerText).start();
3011
+ await createRepo(input.orgSlug, input, spinner, apiKey);
3012
+ }
3013
+ }
3014
+ };
3015
+ const repositoryCreationFlags = {
3016
+ repoName: {
3017
+ type: 'string',
3018
+ shortFlag: 'n',
3019
+ default: '',
3020
+ description: 'Repository name'
3021
+ },
3022
+ repoDescription: {
3023
+ type: 'string',
3024
+ shortFlag: 'd',
3025
+ default: '',
3026
+ description: 'Repository description'
3027
+ },
3028
+ homepage: {
3029
+ type: 'string',
3030
+ shortFlag: 'h',
3031
+ default: '',
3032
+ description: 'Repository url'
3033
+ },
3034
+ defaultBranch: {
3035
+ type: 'string',
3036
+ shortFlag: 'b',
3037
+ default: 'main',
3038
+ description: 'Repository default branch'
3039
+ },
3040
+ visibility: {
3041
+ type: 'string',
3042
+ shortFlag: 'v',
3043
+ default: 'private',
3044
+ description: 'Repository visibility (Default Private)'
3045
+ }
3046
+ };
3047
+
3048
+ // Internal functions
3049
+
3050
+ function setupCommand$8(name, description, argv, importMeta) {
3051
+ const flags = {
3052
+ __proto__: null,
3053
+ ..._flags$7.outputFlags,
3054
+ ...repositoryCreationFlags
3055
+ };
3056
+ const cli = (0, _meow$8.default)(`
3057
+ Usage
3058
+ $ ${name} <org slug>
3059
+
3060
+ Options
3061
+ ${(0, _formatting$7.printFlagList)(flags, 6)}
3062
+
3063
+ Examples
3064
+ $ ${name} FakeOrg --repoName=test-repo
3065
+ `, {
3066
+ argv,
3067
+ description,
3068
+ importMeta,
3069
+ flags
3070
+ });
3071
+ const {
3072
+ json: outputJson,
3073
+ markdown: outputMarkdown,
3074
+ repoName,
3075
+ repoDescription,
3076
+ homepage,
3077
+ defaultBranch,
3078
+ visibility
3079
+ } = cli.flags;
3080
+ const [orgSlug = ''] = cli.input;
3081
+ if (!orgSlug) {
3082
+ console.error(`${_chalk$8.default.white.bgRed('Input error')}: Please provide an organization slug\n`);
3083
+ cli.showHelp();
3084
+ return;
3085
+ }
3086
+ if (!repoName) {
3087
+ console.error(`${_chalk$8.default.white.bgRed('Input error')}: Repository name is required.\n`);
3088
+ cli.showHelp();
3089
+ return;
3090
+ }
3091
+ return {
3092
+ outputJson,
3093
+ outputMarkdown,
3094
+ orgSlug,
3095
+ name: repoName,
3096
+ description: repoDescription,
3097
+ homepage,
3098
+ default_branch: defaultBranch,
3099
+ visibility
3100
+ };
3101
+ }
3102
+ async function createRepo(orgSlug, input, spinner, apiKey) {
3103
+ const socketSdk = await (0, _sdk$8.setupSdk)(apiKey);
3104
+ const result = await (0, _apiHelpers$8.handleApiCall)(socketSdk.createOrgRepo(orgSlug, input), 'creating repository');
3105
+ if (!result.success) {
3106
+ (0, _apiHelpers$8.handleUnsuccessfulApiResponse)('createOrgRepo', result, spinner);
3107
+ return;
3108
+ }
3109
+ spinner.stop();
3110
+ console.log('\n✅ Repository created successfully\n');
3111
+ }
3112
+
3113
+ var _delete$1 = {};
3114
+
3115
+ var _interopRequireDefault$8 = vendor.interopRequireDefault.default;
3116
+ Object.defineProperty(_delete$1, "__esModule", {
3117
+ value: true
3118
+ });
3119
+ _delete$1.del = void 0;
3120
+ var _chalk$7 = _interopRequireDefault$8(vendor.source);
3121
+ var _meow$7 = _interopRequireDefault$8(vendor.build);
3122
+ var _ora$7 = _interopRequireDefault$8(vendor.ora);
3123
+ var _apiHelpers$7 = apiHelpers;
3124
+ var _errors$8 = sdk.errors;
3125
+ var _sdk$7 = sdk.sdk;
3126
+ const del = _delete$1.del = {
3127
+ description: 'Delete a repository in an organization',
3128
+ async run(argv, importMeta, {
3129
+ parentName
3130
+ }) {
3131
+ const name = `${parentName} del`;
3132
+ const input = setupCommand$7(name, del.description, argv, importMeta);
3133
+ if (input) {
3134
+ const apiKey = (0, _sdk$7.getDefaultKey)();
3135
+ if (!apiKey) {
3136
+ throw new _errors$8.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
3137
+ }
3138
+ const spinnerText = 'Deleting repository... \n';
3139
+ const spinner = (0, _ora$7.default)(spinnerText).start();
3140
+ await deleteRepository(input.orgSlug, input.repoName, spinner, apiKey);
3141
+ }
3142
+ }
3143
+ };
3144
+
3145
+ // Internal functions
3146
+
3147
+ function setupCommand$7(name, description, argv, importMeta) {
3148
+ const cli = (0, _meow$7.default)(`
3149
+ Usage
3150
+ $ ${name} <org slug> <repo slug>
3151
+
3152
+ Examples
3153
+ $ ${name} FakeOrg test-repo
3154
+ `, {
3155
+ argv,
3156
+ description,
3157
+ importMeta
3158
+ });
3159
+ const {
3160
+ 0: orgSlug = '',
3161
+ 1: repoName = ''
3162
+ } = cli.input;
3163
+ if (!orgSlug || !repoName) {
3164
+ console.error(`${_chalk$7.default.white.bgRed('Input error')}: Please provide an organization slug and repository slug\n`);
3165
+ cli.showHelp();
3166
+ return;
3167
+ }
3168
+ return {
3169
+ orgSlug,
3170
+ repoName
3171
+ };
3172
+ }
3173
+ async function deleteRepository(orgSlug, repoName, spinner, apiKey) {
3174
+ const socketSdk = await (0, _sdk$7.setupSdk)(apiKey);
3175
+ const result = await (0, _apiHelpers$7.handleApiCall)(socketSdk.deleteOrgRepo(orgSlug, repoName), 'deleting repository');
3176
+ if (!result.success) {
3177
+ (0, _apiHelpers$7.handleUnsuccessfulApiResponse)('deleteOrgRepo', result, spinner);
3178
+ return;
3179
+ }
3180
+ spinner.stop();
3181
+ console.log('\n✅ Repository deleted successfully\n');
3182
+ }
3183
+
3184
+ var list$1 = {};
3185
+
3186
+ var _interopRequireDefault$7 = vendor.interopRequireDefault.default;
3187
+ Object.defineProperty(list$1, "__esModule", {
3188
+ value: true
3189
+ });
3190
+ list$1.list = void 0;
3191
+ var _chalk$6 = _interopRequireDefault$7(vendor.source);
3192
+ var _chalkTable$2 = require$$2$3;
3193
+ var _meow$6 = _interopRequireDefault$7(vendor.build);
3194
+ var _ora$6 = _interopRequireDefault$7(vendor.ora);
3195
+ var _flags$6 = flags$1;
3196
+ var _apiHelpers$6 = apiHelpers;
3197
+ var _errors$7 = sdk.errors;
3198
+ var _formatting$6 = formatting;
3199
+ var _sdk$6 = sdk.sdk;
3200
+ // @ts-ignore
3201
+
3202
+ const list = list$1.list = {
3203
+ description: 'List repositories in an organization',
3204
+ async run(argv, importMeta, {
3205
+ parentName
3206
+ }) {
3207
+ const name = `${parentName} list`;
3208
+ const input = setupCommand$6(name, list.description, argv, importMeta);
3209
+ if (input) {
3210
+ const apiKey = (0, _sdk$6.getDefaultKey)();
3211
+ if (!apiKey) {
3212
+ throw new _errors$7.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
3213
+ }
3214
+ const spinnerText = 'Listing repositories... \n';
3215
+ const spinner = (0, _ora$6.default)(spinnerText).start();
3216
+ await listOrgRepos(input.orgSlug, input, spinner, apiKey);
3217
+ }
3218
+ }
3219
+ };
3220
+ const listRepoFlags = {
3221
+ sort: {
3222
+ type: 'string',
3223
+ shortFlag: 's',
3224
+ default: 'created_at',
3225
+ description: 'Sorting option'
3226
+ },
3227
+ direction: {
3228
+ type: 'string',
3229
+ default: 'desc',
3230
+ description: 'Direction option'
3231
+ },
3232
+ perPage: {
3233
+ type: 'number',
3234
+ shortFlag: 'pp',
3235
+ default: 30,
3236
+ description: 'Number of results per page'
3237
+ },
3238
+ page: {
3239
+ type: 'number',
3240
+ shortFlag: 'p',
3241
+ default: 1,
3242
+ description: 'Page number'
3243
+ }
3244
+ };
3245
+
3246
+ // Internal functions
3247
+
3248
+ function setupCommand$6(name, description, argv, importMeta) {
3249
+ const flags = {
3250
+ ..._flags$6.outputFlags,
3251
+ ...listRepoFlags
3252
+ };
3253
+ const cli = (0, _meow$6.default)(`
3254
+ Usage
3255
+ $ ${name} <org slug>
3256
+
3257
+ Options
3258
+ ${(0, _formatting$6.printFlagList)(flags, 6)}
3259
+
3260
+ Examples
3261
+ $ ${name} FakeOrg
3262
+ `, {
3263
+ argv,
3264
+ description,
3265
+ importMeta,
3266
+ flags
3267
+ });
3268
+ const {
3269
+ json: outputJson,
3270
+ markdown: outputMarkdown,
3271
+ perPage,
3272
+ sort,
3273
+ direction,
3274
+ page
3275
+ } = cli.flags;
3276
+ if (!cli.input[0]) {
3277
+ console.error(`${_chalk$6.default.white.bgRed('Input error')}: Please provide an organization slug\n`);
3278
+ cli.showHelp();
3279
+ return;
3280
+ }
3281
+ const {
3282
+ 0: orgSlug = ''
3283
+ } = cli.input;
3284
+ return {
3285
+ outputJson,
3286
+ outputMarkdown,
3287
+ orgSlug,
3288
+ sort,
3289
+ direction,
3290
+ page,
3291
+ per_page: perPage
3292
+ };
3293
+ }
3294
+ async function listOrgRepos(orgSlug, input, spinner, apiKey) {
3295
+ const socketSdk = await (0, _sdk$6.setupSdk)(apiKey);
3296
+ const result = await (0, _apiHelpers$6.handleApiCall)(socketSdk.getOrgRepoList(orgSlug, input), 'listing repositories');
3297
+ if (!result.success) {
3298
+ (0, _apiHelpers$6.handleUnsuccessfulApiResponse)('getOrgRepoList', result, spinner);
3299
+ return;
3300
+ }
3301
+ spinner.stop();
3302
+ const options = {
3303
+ columns: [{
3304
+ field: 'id',
3305
+ name: _chalk$6.default.magenta('ID')
3306
+ }, {
3307
+ field: 'name',
3308
+ name: _chalk$6.default.magenta('Name')
3309
+ }, {
3310
+ field: 'visibility',
3311
+ name: _chalk$6.default.magenta('Visibility')
3312
+ }, {
3313
+ field: 'default_branch',
3314
+ name: _chalk$6.default.magenta('Default branch')
3315
+ }, {
3316
+ field: 'archived',
3317
+ name: _chalk$6.default.magenta('Archived')
3318
+ }]
3319
+ };
3320
+ console.log(`${_chalkTable$2(options, result.data.results)}\n`);
3321
+ }
3322
+
3323
+ var update$1 = {};
3324
+
3325
+ var _interopRequireDefault$6 = vendor.interopRequireDefault.default;
3326
+ Object.defineProperty(update$1, "__esModule", {
3327
+ value: true
3328
+ });
3329
+ update$1.update = void 0;
3330
+ var _chalk$5 = _interopRequireDefault$6(vendor.source);
3331
+ var _meow$5 = _interopRequireDefault$6(vendor.build);
3332
+ var _ora$5 = _interopRequireDefault$6(vendor.ora);
3333
+ var _flags$5 = flags$1;
3334
+ var _apiHelpers$5 = apiHelpers;
3335
+ var _errors$6 = sdk.errors;
3336
+ var _formatting$5 = formatting;
3337
+ var _sdk$5 = sdk.sdk;
3338
+ const update = update$1.update = {
3339
+ description: 'Update a repository in an organization',
3340
+ async run(argv, importMeta, {
3341
+ parentName
3342
+ }) {
3343
+ const name = `${parentName} update`;
3344
+ const input = setupCommand$5(name, update.description, argv, importMeta);
3345
+ if (input) {
3346
+ const apiKey = (0, _sdk$5.getDefaultKey)();
3347
+ if (!apiKey) {
3348
+ throw new _errors$6.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
3349
+ }
3350
+ const spinnerText = 'Updating repository... \n';
3351
+ const spinner = (0, _ora$5.default)(spinnerText).start();
3352
+ await updateRepository(input.orgSlug, input, spinner, apiKey);
3353
+ }
3354
+ }
3355
+ };
3356
+ const repositoryUpdateFlags = {
3357
+ repoName: {
3358
+ type: 'string',
3359
+ shortFlag: 'n',
3360
+ default: '',
3361
+ description: 'Repository name'
3362
+ },
3363
+ repoDescription: {
3364
+ type: 'string',
3365
+ shortFlag: 'd',
3366
+ default: '',
3367
+ description: 'Repository description'
3368
+ },
3369
+ homepage: {
3370
+ type: 'string',
3371
+ shortFlag: 'h',
3372
+ default: '',
3373
+ description: 'Repository url'
3374
+ },
3375
+ defaultBranch: {
3376
+ type: 'string',
3377
+ shortFlag: 'b',
3378
+ default: 'main',
3379
+ description: 'Repository default branch'
3380
+ },
3381
+ visibility: {
3382
+ type: 'string',
3383
+ shortFlag: 'v',
3384
+ default: 'private',
3385
+ description: 'Repository visibility (Default Private)'
3386
+ }
3387
+ };
3388
+
3389
+ // Internal functions
3390
+
3391
+ function setupCommand$5(name, description, argv, importMeta) {
3392
+ const flags = {
3393
+ ..._flags$5.outputFlags,
3394
+ ...repositoryUpdateFlags
3395
+ };
3396
+ const cli = (0, _meow$5.default)(`
3397
+ Usage
3398
+ $ ${name} <org slug>
3399
+
3400
+ Options
3401
+ ${(0, _formatting$5.printFlagList)(flags, 6)}
3402
+
3403
+ Examples
3404
+ $ ${name} FakeOrg
3405
+ `, {
3406
+ argv,
3407
+ description,
3408
+ importMeta,
3409
+ flags
3410
+ });
3411
+ const {
3412
+ json: outputJson,
3413
+ markdown: outputMarkdown,
3414
+ repoName,
3415
+ repoDescription,
3416
+ homepage,
3417
+ defaultBranch,
3418
+ visibility
3419
+ } = cli.flags;
3420
+ const [orgSlug = ''] = cli.input;
3421
+ if (!orgSlug) {
3422
+ console.error(`${_chalk$5.default.white.bgRed('Input error')}: Please provide an organization slug and repository name\n`);
3423
+ cli.showHelp();
3424
+ return;
3425
+ }
3426
+ if (!repoName) {
3427
+ console.error(`${_chalk$5.default.white.bgRed('Input error')}: Repository name is required.\n`);
3428
+ cli.showHelp();
3429
+ return;
3430
+ }
3431
+ return {
3432
+ outputJson,
3433
+ outputMarkdown,
3434
+ orgSlug,
3435
+ name: repoName,
3436
+ description: repoDescription,
3437
+ homepage,
3438
+ default_branch: defaultBranch,
3439
+ visibility
3440
+ };
3441
+ }
3442
+ async function updateRepository(orgSlug, input, spinner, apiKey) {
3443
+ const socketSdk = await (0, _sdk$5.setupSdk)(apiKey);
3444
+ const result = await (0, _apiHelpers$5.handleApiCall)(socketSdk.updateOrgRepo(orgSlug, input.name, input), 'updating repository');
3445
+ if (!result.success) {
3446
+ (0, _apiHelpers$5.handleUnsuccessfulApiResponse)('updateOrgRepo', result, spinner);
3447
+ return;
3448
+ }
3449
+ spinner.stop();
3450
+ console.log('\n✅ Repository updated successfully\n');
3451
+ }
3452
+
3453
+ var view$1 = {};
3454
+
3455
+ var _interopRequireDefault$5 = vendor.interopRequireDefault.default;
3456
+ Object.defineProperty(view$1, "__esModule", {
3457
+ value: true
3458
+ });
3459
+ view$1.view = void 0;
3460
+ var _chalk$4 = _interopRequireDefault$5(vendor.source);
3461
+ var _chalkTable$1 = require$$2$3;
3462
+ var _meow$4 = _interopRequireDefault$5(vendor.build);
3463
+ var _ora$4 = _interopRequireDefault$5(vendor.ora);
3464
+ var _flags$4 = flags$1;
3465
+ var _apiHelpers$4 = apiHelpers;
3466
+ var _errors$5 = sdk.errors;
3467
+ var _formatting$4 = formatting;
3468
+ var _sdk$4 = sdk.sdk;
3469
+ // @ts-ignore
3470
+
3471
+ const view = view$1.view = {
3472
+ description: 'View repositories in an organization',
3473
+ async run(argv, importMeta, {
3474
+ parentName
3475
+ }) {
3476
+ const name = `${parentName} view`;
3477
+ const input = setupCommand$4(name, view.description, argv, importMeta);
3478
+ if (input) {
3479
+ const apiKey = (0, _sdk$4.getDefaultKey)();
3480
+ if (!apiKey) {
3481
+ throw new _errors$5.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
3482
+ }
3483
+ const spinnerText = 'Fetching repository... \n';
3484
+ const spinner = (0, _ora$4.default)(spinnerText).start();
3485
+ await viewRepository(input.orgSlug, input.repositoryName, spinner, apiKey);
3486
+ }
3487
+ }
3488
+ };
3489
+
3490
+ // Internal functions
3491
+
3492
+ function setupCommand$4(name, description, argv, importMeta) {
3493
+ const flags = {
3494
+ ..._flags$4.outputFlags
3495
+ };
3496
+ const cli = (0, _meow$4.default)(`
3497
+ Usage
3498
+ $ ${name} <org slug>
3499
+
3500
+ Options
3501
+ ${(0, _formatting$4.printFlagList)(flags, 6)}
3502
+
3503
+ Examples
3504
+ $ ${name} FakeOrg
3505
+ `, {
3506
+ argv,
3507
+ description,
3508
+ importMeta,
3509
+ flags
3510
+ });
3511
+ const {
3512
+ json: outputJson,
3513
+ markdown: outputMarkdown
3514
+ } = cli.flags;
3515
+ if (!cli.input[0]) {
3516
+ console.error(`${_chalk$4.default.white.bgRed('Input error')}: Please provide an organization slug and repository name\n`);
3517
+ cli.showHelp();
3518
+ return;
3519
+ }
3520
+ const {
3521
+ 0: orgSlug = '',
3522
+ 1: repositoryName = ''
3523
+ } = cli.input;
3524
+ return {
3525
+ outputJson,
3526
+ outputMarkdown,
3527
+ orgSlug,
3528
+ repositoryName
3529
+ };
3530
+ }
3531
+ async function viewRepository(orgSlug, repoName, spinner, apiKey) {
3532
+ const socketSdk = await (0, _sdk$4.setupSdk)(apiKey);
3533
+ const result = await (0, _apiHelpers$4.handleApiCall)(socketSdk.getOrgRepo(orgSlug, repoName), 'fetching repository');
3534
+ if (!result.success) {
3535
+ (0, _apiHelpers$4.handleUnsuccessfulApiResponse)('getOrgRepo', result, spinner);
3536
+ return;
3537
+ }
3538
+ spinner.stop();
3539
+ const options = {
3540
+ columns: [{
3541
+ field: 'id',
3542
+ name: _chalk$4.default.magenta('ID')
3543
+ }, {
3544
+ field: 'name',
3545
+ name: _chalk$4.default.magenta('Name')
3546
+ }, {
3547
+ field: 'visibility',
3548
+ name: _chalk$4.default.magenta('Visibility')
3549
+ }, {
3550
+ field: 'default_branch',
3551
+ name: _chalk$4.default.magenta('Default branch')
3552
+ }, {
3553
+ field: 'homepage',
3554
+ name: _chalk$4.default.magenta('Homepage')
3555
+ }, {
3556
+ field: 'archived',
3557
+ name: _chalk$4.default.magenta('Archived')
3558
+ }, {
3559
+ field: 'created_at',
3560
+ name: _chalk$4.default.magenta('Created at')
3561
+ }]
3562
+ };
3563
+ console.log(`${_chalkTable$1(options, [result.data])}\n`);
3564
+ }
3565
+
3566
+ Object.defineProperty(repos, "__esModule", {
3567
+ value: true
3568
+ });
3569
+ repos.repo = void 0;
3570
+ var _create = create$1;
3571
+ var _delete = _delete$1;
3572
+ var _list = list$1;
3573
+ var _update = update$1;
3574
+ var _view = view$1;
3575
+ var _meowWithSubcommands$2 = meowWithSubcommands$1;
3576
+ const description$1 = 'Repositories related commands';
3577
+ repos.repo = {
3578
+ description: description$1,
3579
+ run: async (argv, importMeta, {
3580
+ parentName
3581
+ }) => {
3582
+ await (0, _meowWithSubcommands$2.meowWithSubcommands)({
3583
+ create: _create.create,
3584
+ view: _view.view,
3585
+ list: _list.list,
3586
+ del: _delete.del,
3587
+ update: _update.update
3588
+ }, {
3589
+ argv,
3590
+ description: description$1,
3591
+ importMeta,
3592
+ name: `${parentName} repo`
3593
+ });
3594
+ }
3595
+ };
3596
+
3597
+ var dependencies$1 = {};
3598
+
3599
+ var _interopRequireDefault$4 = vendor.interopRequireDefault.default;
3600
+ Object.defineProperty(dependencies$1, "__esModule", {
3601
+ value: true
3602
+ });
3603
+ dependencies$1.dependencies = void 0;
3604
+ var _chalk$3 = _interopRequireDefault$4(vendor.source);
3605
+ var _chalkTable = require$$2$3;
3606
+ var _meow$3 = _interopRequireDefault$4(vendor.build);
3607
+ var _ora$3 = _interopRequireDefault$4(vendor.ora);
3608
+ var _flags$3 = flags$1;
3609
+ var _apiHelpers$3 = apiHelpers;
3610
+ var _errors$4 = sdk.errors;
3611
+ var _formatting$3 = formatting;
3612
+ var _sdk$3 = sdk.sdk;
3613
+ // @ts-ignore
3614
+
3615
+ const dependencies = dependencies$1.dependencies = {
3616
+ description: 'Search for any dependency that is being used in your organization',
3617
+ async run(argv, importMeta, {
3618
+ parentName
3619
+ }) {
3620
+ const name = parentName + ' dependencies';
3621
+ const input = setupCommand$3(name, dependencies.description, argv, importMeta);
3622
+ if (input) {
3623
+ await searchDeps(input);
3624
+ }
3625
+ }
3626
+ };
3627
+ const dependenciesFlags = {
3628
+ limit: {
3629
+ type: 'number',
3630
+ shortFlag: 'l',
3631
+ default: 50,
3632
+ description: 'Maximum number of dependencies returned'
3633
+ },
3634
+ offset: {
3635
+ type: 'number',
3636
+ shortFlag: 'o',
3637
+ default: 0,
3638
+ description: 'Page number'
3639
+ }
3640
+ };
3641
+
3642
+ // Internal functions
3643
+
3644
+ function setupCommand$3(name, description, argv, importMeta) {
3645
+ const flags = {
3646
+ __proto__: null,
3647
+ ..._flags$3.outputFlags,
3648
+ ...dependenciesFlags
3649
+ };
3650
+ const cli = (0, _meow$3.default)(`
3651
+ Usage
3652
+ $ ${name}
3653
+
3654
+ Options
3655
+ ${(0, _formatting$3.printFlagList)(flags, 6)}
3656
+
3657
+ Examples
3658
+ $ ${name}
3659
+ `, {
3660
+ argv,
3661
+ description,
3662
+ importMeta,
3663
+ flags
3664
+ });
3665
+ const {
3666
+ json: outputJson,
3667
+ markdown: outputMarkdown,
3668
+ limit,
3669
+ offset
3670
+ } = cli.flags;
3671
+ return {
3672
+ outputJson,
3673
+ outputMarkdown,
3674
+ limit,
3675
+ offset
3676
+ };
3677
+ }
3678
+ async function searchDeps({
3679
+ limit,
3680
+ offset,
3681
+ outputJson
3682
+ }) {
3683
+ const apiKey = (0, _sdk$3.getDefaultKey)();
3684
+ if (!apiKey) {
3685
+ throw new _errors$4.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
3686
+ }
3687
+ const spinnerText = 'Searching dependencies...';
3688
+ const spinner = (0, _ora$3.default)(spinnerText).start();
3689
+ const socketSdk = await (0, _sdk$3.setupSdk)(apiKey);
3690
+ const result = await (0, _apiHelpers$3.handleApiCall)(socketSdk.searchDependencies({
3691
+ limit,
3692
+ offset
3693
+ }), 'Searching dependencies');
3694
+ if (!result.success) {
3695
+ (0, _apiHelpers$3.handleUnsuccessfulApiResponse)('searchDependencies', result, spinner);
3696
+ return;
3697
+ }
3698
+ spinner.stop();
3699
+ console.log('Organization dependencies:\n');
3700
+ if (outputJson) {
3701
+ console.log(result.data);
3702
+ return;
3703
+ }
3704
+ const options = {
3705
+ columns: [{
3706
+ field: 'namespace',
3707
+ name: _chalk$3.default.cyan('Namespace')
3708
+ }, {
3709
+ field: 'name',
3710
+ name: _chalk$3.default.cyan('Name')
3711
+ }, {
3712
+ field: 'version',
3713
+ name: _chalk$3.default.cyan('Version')
3714
+ }, {
3715
+ field: 'repository',
3716
+ name: _chalk$3.default.cyan('Repository')
3717
+ }, {
3718
+ field: 'branch',
3719
+ name: _chalk$3.default.cyan('Branch')
3720
+ }, {
3721
+ field: 'type',
3722
+ name: _chalk$3.default.cyan('Type')
3723
+ }, {
3724
+ field: 'direct',
3725
+ name: _chalk$3.default.cyan('Direct')
3726
+ }]
3727
+ };
3728
+ console.log(`${_chalkTable(options, result.data.rows)}\n`);
3729
+ }
3730
+
3731
+ var analytics$1 = {};
3732
+
3733
+ var _interopRequireDefault$3 = vendor.interopRequireDefault.default;
3734
+ Object.defineProperty(analytics$1, "__esModule", {
3735
+ value: true
3736
+ });
3737
+ analytics$1.analytics = void 0;
3738
+ var _nodeFs$2 = require$$0;
3739
+ var _blessed$1 = require$$2$4;
3740
+ var _blessedContrib$1 = require$$3$5;
3741
+ var _chalk$2 = _interopRequireDefault$3(vendor.source);
3742
+ var _meow$2 = _interopRequireDefault$3(vendor.build);
3743
+ var _ora$2 = _interopRequireDefault$3(vendor.ora);
3744
+ var _flags$2 = flags$1;
3745
+ var _apiHelpers$2 = apiHelpers;
3746
+ var _errors$3 = sdk.errors;
3747
+ var _formatting$2 = formatting;
3748
+ var _sdk$2 = sdk.sdk;
3749
+ // @ts-ignore
3750
+
3751
+ const analytics = analytics$1.analytics = {
3752
+ description: `Look up analytics data \n
3753
+ Default parameters are set to show the organization-level analytics over the last 7 days.`,
3754
+ async run(argv, importMeta, {
3755
+ parentName
3756
+ }) {
3757
+ const name = parentName + ' analytics';
3758
+ const input = setupCommand$2(name, analytics.description, argv, importMeta);
3759
+ if (input) {
3760
+ const apiKey = (0, _sdk$2.getDefaultKey)();
3761
+ if (!apiKey) {
3762
+ throw new _errors$3.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
3763
+ }
3764
+ const spinner = (0, _ora$2.default)('Fetching analytics data').start();
3765
+ if (input.scope === 'org') {
3766
+ await fetchOrgAnalyticsData(input.time, spinner, apiKey, input.outputJson, input.file);
3767
+ } else {
3768
+ if (input.repo) {
3769
+ await fetchRepoAnalyticsData(input.repo, input.time, spinner, apiKey, input.outputJson, input.file);
3770
+ }
3771
+ }
3772
+ }
3773
+ }
3774
+ };
3775
+ const analyticsFlags = {
3776
+ scope: {
3777
+ type: 'string',
3778
+ shortFlag: 's',
3779
+ default: 'org',
3780
+ description: "Scope of the analytics data - either 'org' or 'repo'"
3781
+ },
3782
+ time: {
3783
+ type: 'number',
3784
+ shortFlag: 't',
3785
+ default: 7,
3786
+ description: 'Time filter - either 7, 30 or 90'
3787
+ },
3788
+ repo: {
3789
+ type: 'string',
3790
+ shortFlag: 'r',
3791
+ default: '',
3792
+ description: 'Name of the repository'
3793
+ },
3794
+ file: {
3795
+ type: 'string',
3796
+ shortFlag: 'f',
3797
+ default: '',
3798
+ description: 'Path to a local file to save the output'
3799
+ }
3800
+ };
3801
+
3802
+ // Internal functions
3803
+
3804
+ function setupCommand$2(name, description, argv, importMeta) {
3805
+ const flags = {
3806
+ __proto__: null,
3807
+ ..._flags$2.outputFlags,
3808
+ ...analyticsFlags
3809
+ };
3810
+ const cli = (0, _meow$2.default)(`
3811
+ Usage
3812
+ $ ${name} --scope=<scope> --time=<time filter>
3813
+
3814
+ Options
3815
+ ${(0, _formatting$2.printFlagList)(flags, 6)}
3816
+
3817
+ Examples
3818
+ $ ${name} --scope=org --time=7
3819
+ $ ${name} --scope=org --time=30
3820
+ $ ${name} --scope=repo --repo=test-repo --time=30
3821
+ `, {
3822
+ argv,
3823
+ description,
3824
+ importMeta,
3825
+ flags
3826
+ });
3827
+ const {
3828
+ json: outputJson,
3829
+ scope,
3830
+ time,
3831
+ repo,
3832
+ file
3833
+ } = cli.flags;
3834
+ if (scope !== 'org' && scope !== 'repo') {
3835
+ throw new _errors$3.InputError("The scope must either be 'org' or 'repo'");
3836
+ }
3837
+ if (time !== 7 && time !== 30 && time !== 90) {
3838
+ throw new _errors$3.InputError('The time filter must either be 7, 30 or 90');
3839
+ }
3840
+ if (scope === 'repo' && !repo) {
3841
+ console.error(`${_chalk$2.default.bgRed.white('Input error')}: Please provide a repository name when using the repository scope. \n`);
3842
+ cli.showHelp();
3843
+ return;
3844
+ }
3845
+ return {
3846
+ scope,
3847
+ time,
3848
+ repo,
3849
+ outputJson,
3850
+ file
3851
+ };
3852
+ }
3853
+ const METRICS = ['total_critical_alerts', 'total_high_alerts', 'total_medium_alerts', 'total_low_alerts', 'total_critical_added', 'total_medium_added', 'total_low_added', 'total_high_added', 'total_critical_prevented', 'total_high_prevented', 'total_medium_prevented', 'total_low_prevented'];
3854
+ async function fetchOrgAnalyticsData(time, spinner, apiKey, outputJson, filePath) {
3855
+ const socketSdk = await (0, _sdk$2.setupSdk)(apiKey);
3856
+ const result = await (0, _apiHelpers$2.handleApiCall)(socketSdk.getOrgAnalytics(time.toString()), 'fetching analytics data');
3857
+ if (result.success === false) {
3858
+ return (0, _apiHelpers$2.handleUnsuccessfulApiResponse)('getOrgAnalytics', result, spinner);
3859
+ }
3860
+ spinner.stop();
3861
+ if (!result.data.length) {
3862
+ return console.log('No analytics data is available for this organization yet.');
3863
+ }
3864
+ const data = formatData(result.data, 'org');
3865
+ if (outputJson && !filePath) {
3866
+ return console.log(result.data);
3867
+ }
3868
+ if (filePath) {
3869
+ _nodeFs$2.writeFile(filePath, JSON.stringify(result.data), err => {
3870
+ err ? console.error(err) : console.log(`Data successfully written to ${filePath}`);
3871
+ });
3872
+ return;
3873
+ }
3874
+ return displayAnalyticsScreen(data);
3875
+ }
3876
+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
3877
+ const formatDate = date => {
3878
+ return `${months[new Date(date).getMonth()]} ${new Date(date).getDate()}`;
3879
+ };
3880
+ const formatData = (data, scope) => {
3881
+ let formattedData, sortedTopFiveAlerts;
3882
+ if (scope === 'org') {
3883
+ const topFiveAlerts = data.map(d => d['top_five_alert_types']);
3884
+ const totalTopAlerts = topFiveAlerts.reduce((acc, current) => {
3885
+ const alertTypes = Object.keys(current);
3886
+ alertTypes.map(type => {
3887
+ if (!acc[type]) {
3888
+ acc[type] = current[type];
3889
+ } else {
3890
+ acc[type] += current[type];
3891
+ }
3892
+ return acc;
3893
+ });
3894
+ return acc;
3895
+ }, {});
3896
+ sortedTopFiveAlerts = Object.entries(totalTopAlerts).sort(({
3897
+ 1: a
3898
+ }, {
3899
+ 1: b
3900
+ }) => b - a).slice(0, 5).reduce((r, {
3901
+ 0: k,
3902
+ 1: v
3903
+ }) => {
3904
+ r[k] = v;
3905
+ return r;
3906
+ }, {});
3907
+ const formatData = label => {
3908
+ return data.reduce((acc, current) => {
3909
+ const date = formatDate(current['created_at']);
3910
+ if (!acc[date]) {
3911
+ acc[date] = current[label];
3912
+ } else {
3913
+ acc[date] += current[label];
3914
+ }
3915
+ return acc;
3916
+ }, {});
3917
+ };
3918
+ formattedData = METRICS.reduce((acc, current) => {
3919
+ acc[current] = formatData(current);
3920
+ return acc;
3921
+ }, {});
3922
+ } else if (scope === 'repo') {
3923
+ const topAlerts = data.reduce((acc, current) => {
3924
+ const alertTypes = Object.keys(current['top_five_alert_types']);
3925
+ alertTypes.map(type => {
3926
+ if (!acc[type]) {
3927
+ acc[type] = current['top_five_alert_types'][type];
3928
+ } else {
3929
+ if (current['top_five_alert_types'][type] > (acc[type] || 0)) {
3930
+ acc[type] = current['top_five_alert_types'][type];
3931
+ }
3932
+ }
3933
+ return acc;
3934
+ });
3935
+ return acc;
3936
+ }, {});
3937
+ sortedTopFiveAlerts = Object.entries(topAlerts).sort(({
3938
+ 1: a
3939
+ }, {
3940
+ 1: b
3941
+ }) => b - a).slice(0, 5).reduce((r, {
3942
+ 0: k,
3943
+ 1: v
3944
+ }) => {
3945
+ r[k] = v;
3946
+ return r;
3947
+ }, {});
3948
+ formattedData = data.reduce((acc, current) => {
3949
+ METRICS.forEach(m => {
3950
+ if (!acc[m]) {
3951
+ acc[m] = {};
3952
+ }
3953
+ acc[m][formatDate(current['created_at'])] = current[m];
3954
+ return acc;
3955
+ });
3956
+ return acc;
3957
+ }, {});
3958
+ }
3959
+ return {
3960
+ ...formattedData,
3961
+ top_five_alert_types: sortedTopFiveAlerts
3962
+ };
3963
+ };
3964
+ async function fetchRepoAnalyticsData(repo, time, spinner, apiKey, outputJson, filePath) {
3965
+ const socketSdk = await (0, _sdk$2.setupSdk)(apiKey);
3966
+ const result = await (0, _apiHelpers$2.handleApiCall)(socketSdk.getRepoAnalytics(repo, time.toString()), 'fetching analytics data');
3967
+ if (result.success === false) {
3968
+ return (0, _apiHelpers$2.handleUnsuccessfulApiResponse)('getRepoAnalytics', result, spinner);
3969
+ }
3970
+ spinner.stop();
3971
+ if (!result.data.length) {
3972
+ return console.log('No analytics data is available for this organization yet.');
3973
+ }
3974
+ const data = formatData(result.data, 'repo');
3975
+ if (outputJson && !filePath) {
3976
+ return console.log(result.data);
3977
+ }
3978
+ if (filePath) {
3979
+ _nodeFs$2.writeFile(filePath, JSON.stringify(result.data), err => {
3980
+ err ? console.error(err) : console.log(`Data successfully written to ${filePath}`);
3981
+ });
3982
+ return;
3983
+ }
3984
+ return displayAnalyticsScreen(data);
3985
+ }
3986
+ const displayAnalyticsScreen = data => {
3987
+ const screen = _blessed$1.screen();
3988
+ const grid = new _blessedContrib$1.grid({
3989
+ rows: 5,
3990
+ cols: 4,
3991
+ screen
3992
+ });
3993
+ renderLineCharts(grid, screen, 'Total critical alerts', [0, 0, 1, 2], data['total_critical_alerts']);
3994
+ renderLineCharts(grid, screen, 'Total high alerts', [0, 2, 1, 2], data['total_high_alerts']);
3995
+ renderLineCharts(grid, screen, 'Total critical alerts added to the main branch', [1, 0, 1, 2], data['total_critical_added']);
3996
+ renderLineCharts(grid, screen, 'Total high alerts added to the main branch', [1, 2, 1, 2], data['total_high_added']);
3997
+ renderLineCharts(grid, screen, 'Total critical alerts prevented from the main branch', [2, 0, 1, 2], data['total_critical_prevented']);
3998
+ renderLineCharts(grid, screen, 'Total high alerts prevented from the main branch', [2, 2, 1, 2], data['total_high_prevented']);
3999
+ renderLineCharts(grid, screen, 'Total medium alerts prevented from the main branch', [3, 0, 1, 2], data['total_medium_prevented']);
4000
+ renderLineCharts(grid, screen, 'Total low alerts prevented from the main branch', [3, 2, 1, 2], data['total_low_prevented']);
4001
+ const bar = grid.set(4, 0, 1, 2, _blessedContrib$1.bar, {
4002
+ label: 'Top 5 alert types',
4003
+ barWidth: 10,
4004
+ barSpacing: 17,
4005
+ xOffset: 0,
4006
+ maxHeight: 9,
4007
+ barBgColor: 'magenta'
4008
+ });
4009
+ screen.append(bar); //must append before setting data
4010
+
4011
+ bar.setData({
4012
+ titles: Object.keys(data.top_five_alert_types),
4013
+ data: Object.values(data.top_five_alert_types)
4014
+ });
4015
+ screen.render();
4016
+ screen.key(['escape', 'q', 'C-c'], () => process.exit(0));
4017
+ };
4018
+ const renderLineCharts = (grid, screen, title, coords, data) => {
4019
+ const line = grid.set(...coords, _blessedContrib$1.line, {
4020
+ style: {
4021
+ line: 'cyan',
4022
+ text: 'cyan',
4023
+ baseline: 'black'
4024
+ },
4025
+ xLabelPadding: 0,
4026
+ xPadding: 0,
4027
+ xOffset: 0,
4028
+ wholeNumbersOnly: true,
4029
+ legend: {
4030
+ width: 1
4031
+ },
4032
+ label: title
4033
+ });
4034
+ screen.append(line);
4035
+ const lineData = {
4036
+ x: Object.keys(data),
4037
+ y: Object.values(data)
4038
+ };
4039
+ line.setData([lineData]);
4040
+ };
4041
+
4042
+ var diffScan = {};
4043
+
4044
+ var get$1 = {};
4045
+
4046
+ var _interopRequireDefault$2 = vendor.interopRequireDefault.default;
4047
+ Object.defineProperty(get$1, "__esModule", {
4048
+ value: true
4049
+ });
4050
+ get$1.get = void 0;
4051
+ var _nodeFs$1 = require$$0;
4052
+ var _nodeUtil = require$$0$2;
4053
+ var _chalk$1 = _interopRequireDefault$2(vendor.source);
4054
+ var _meow$1 = _interopRequireDefault$2(vendor.build);
4055
+ var _ora$1 = _interopRequireDefault$2(vendor.ora);
4056
+ var _flags$1 = flags$1;
4057
+ var _apiHelpers$1 = apiHelpers;
4058
+ var _errors$2 = sdk.errors;
4059
+ var _formatting$1 = formatting;
4060
+ var _sdk$1 = sdk.sdk;
4061
+ const get = get$1.get = {
4062
+ description: 'Get a diff scan for an organization',
4063
+ async run(argv, importMeta, {
4064
+ parentName
4065
+ }) {
4066
+ const name = `${parentName} get`;
4067
+ const input = setupCommand$1(name, get.description, argv, importMeta);
4068
+ if (input) {
4069
+ const apiKey = (0, _sdk$1.getDefaultKey)();
4070
+ if (!apiKey) {
4071
+ throw new _errors$2.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
4072
+ }
4073
+ const spinnerText = 'Getting diff scan... \n';
4074
+ const spinner = (0, _ora$1.default)(spinnerText).start();
4075
+ await getDiffScan(input, spinner, apiKey);
4076
+ }
4077
+ }
4078
+ };
4079
+ const getDiffScanFlags = {
4080
+ before: {
4081
+ type: 'string',
4082
+ shortFlag: 'b',
4083
+ default: '',
4084
+ description: 'The full scan ID of the base scan'
4085
+ },
4086
+ after: {
4087
+ type: 'string',
4088
+ shortFlag: 'a',
4089
+ default: '',
4090
+ description: 'The full scan ID of the head scan'
4091
+ },
4092
+ preview: {
4093
+ type: 'boolean',
4094
+ shortFlag: 'p',
4095
+ default: true,
4096
+ description: 'A boolean flag to persist or not the diff scan result'
4097
+ },
4098
+ file: {
4099
+ type: 'string',
4100
+ shortFlag: 'f',
4101
+ default: '',
4102
+ description: 'Path to a local file where the output should be saved'
4103
+ }
4104
+ };
4105
+
4106
+ // Internal functions
4107
+
4108
+ function setupCommand$1(name, description, argv, importMeta) {
4109
+ const flags = {
4110
+ __proto__: null,
4111
+ ..._flags$1.outputFlags,
4112
+ ...getDiffScanFlags
4113
+ };
4114
+ const cli = (0, _meow$1.default)(`
4115
+ Usage
4116
+ $ ${name} <org slug> --before=<before> --after=<after>
4117
+
4118
+ Options
4119
+ ${(0, _formatting$1.printFlagList)(flags, 6)}
4120
+
4121
+ Examples
4122
+ $ ${name} FakeCorp --before=aaa0aa0a-aaaa-0000-0a0a-0000000a00a0 --after=aaa1aa1a-aaaa-1111-1a1a-1111111a11a1
4123
+ `, {
4124
+ argv,
4125
+ description,
4126
+ importMeta,
4127
+ flags
4128
+ });
4129
+ const {
4130
+ json: outputJson,
4131
+ markdown: outputMarkdown,
4132
+ before,
4133
+ after,
4134
+ preview,
4135
+ file
4136
+ } = cli.flags;
4137
+ if (!before || !after) {
4138
+ console.error(`${_chalk$1.default.bgRed.white('Input error')}: Please specify a before and after full scan ID. To get full scans IDs, you can run the command "socket scan list <your org slug>".\n`);
4139
+ cli.showHelp();
4140
+ return;
4141
+ }
4142
+ if (cli.input.length < 1) {
4143
+ console.error(`${_chalk$1.default.bgRed.white('Input error')}: Please provide an organization slug\n`);
4144
+ cli.showHelp();
4145
+ return;
4146
+ }
4147
+ const [orgSlug = ''] = cli.input;
4148
+ return {
4149
+ outputJson,
4150
+ outputMarkdown,
4151
+ before,
4152
+ after,
4153
+ preview,
4154
+ orgSlug,
4155
+ file
4156
+ };
4157
+ }
4158
+ async function getDiffScan({
4159
+ before,
4160
+ after,
4161
+ orgSlug,
4162
+ file,
4163
+ outputJson
4164
+ }, spinner, apiKey) {
4165
+ const response = await (0, _apiHelpers$1.queryAPI)(`${orgSlug}/full-scans/diff?before=${before}&after=${after}&preview`, apiKey);
4166
+ const data = await response.json();
4167
+ if (!response.ok) {
4168
+ spinner.stop();
4169
+ const err = await (0, _apiHelpers$1.handleAPIError)(response.status);
4170
+ console.error(`${_chalk$1.default.bgRed.white(response.statusText)}: ${err}\n`);
4171
+ return;
4172
+ }
4173
+ spinner.stop();
4174
+ if (file && !outputJson) {
4175
+ _nodeFs$1.writeFile(file, JSON.stringify(data), err => {
4176
+ err ? console.error(err) : console.log(`Data successfully written to ${file}`);
4177
+ });
4178
+ return;
4179
+ }
4180
+ if (outputJson) {
4181
+ console.log(`\n Diff scan result: \n`);
4182
+ console.log(_nodeUtil.inspect(data, {
4183
+ showHidden: false,
4184
+ depth: null,
4185
+ colors: true
4186
+ }));
4187
+ // @ts-ignore
4188
+ console.log(`\n View this diff scan in the Socket dashboard: ${_chalk$1.default.cyan(data?.['diff_report_url'])}\n`);
4189
+ return;
4190
+ }
4191
+ console.log('Diff scan result: ');
4192
+ console.log(data);
4193
+ console.log(`\n 📝 To display the detailed report in the terminal, use the --json flag \n`);
4194
+ // @ts-ignore
4195
+ console.log(`\n View this diff scan in the Socket dashboard: ${_chalk$1.default.cyan(data?.['diff_report_url'])}\n`);
4196
+ }
4197
+
4198
+ Object.defineProperty(diffScan, "__esModule", {
4199
+ value: true
4200
+ });
4201
+ diffScan.diffScan = void 0;
4202
+ var _get = get$1;
4203
+ var _meowWithSubcommands$1 = meowWithSubcommands$1;
4204
+ const description = 'Diff scans related commands';
4205
+ diffScan.diffScan = {
4206
+ description,
4207
+ run: async (argv, importMeta, {
4208
+ parentName
4209
+ }) => {
4210
+ await (0, _meowWithSubcommands$1.meowWithSubcommands)({
4211
+ get: _get.get
4212
+ }, {
4213
+ argv,
4214
+ description,
4215
+ importMeta,
4216
+ name: parentName + ' diff-scan'
4217
+ });
4218
+ }
4219
+ };
4220
+
4221
+ var threatFeed$1 = {};
4222
+
4223
+ var _interopRequireDefault$1 = vendor.interopRequireDefault.default;
4224
+ Object.defineProperty(threatFeed$1, "__esModule", {
4225
+ value: true
4226
+ });
4227
+ threatFeed$1.threatFeed = void 0;
4228
+ var _blessed = require$$2$4;
4229
+ var _blessedContrib = require$$3$5;
4230
+ var _meow = _interopRequireDefault$1(vendor.build);
4231
+ var _ora = _interopRequireDefault$1(vendor.ora);
4232
+ var _flags = flags$1;
4233
+ var _apiHelpers = apiHelpers;
4234
+ var _errors$1 = sdk.errors;
4235
+ var _formatting = formatting;
4236
+ var _sdk = sdk.sdk;
4237
+ // @ts-ignore
4238
+
4239
+ const threatFeed = threatFeed$1.threatFeed = {
4240
+ description: 'Look up the threat feed',
4241
+ async run(argv, importMeta, {
4242
+ parentName
4243
+ }) {
4244
+ const name = parentName + ' threat-feed';
4245
+ const input = setupCommand(name, threatFeed.description, argv, importMeta);
4246
+ if (input) {
4247
+ const apiKey = (0, _sdk.getDefaultKey)();
4248
+ if (!apiKey) {
4249
+ throw new _errors$1.AuthError('User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.');
4250
+ }
4251
+ const spinner = (0, _ora.default)(`Looking up the threat feed \n`).start();
4252
+ await fetchThreatFeed(input, spinner, apiKey);
4253
+ }
4254
+ }
4255
+ };
4256
+ const threatFeedFlags = {
4257
+ perPage: {
4258
+ type: 'number',
4259
+ shortFlag: 'pp',
4260
+ default: 30,
4261
+ description: 'Number of items per page'
4262
+ },
4263
+ page: {
4264
+ type: 'string',
4265
+ shortFlag: 'p',
4266
+ default: '1',
4267
+ description: 'Page token'
4268
+ },
4269
+ direction: {
4270
+ type: 'string',
4271
+ shortFlag: 'd',
4272
+ default: 'desc',
4273
+ description: 'Order asc or desc by the createdAt attribute.'
4274
+ },
4275
+ filter: {
4276
+ type: 'string',
4277
+ shortFlag: 'f',
4278
+ default: 'mal',
4279
+ description: 'Filter what type of threats to return'
4280
+ }
4281
+ };
4282
+
4283
+ // Internal functions
4284
+
4285
+ function setupCommand(name, description, argv, importMeta) {
4286
+ const flags = {
4287
+ __proto__: null,
4288
+ ...threatFeedFlags,
4289
+ ..._flags.outputFlags
4290
+ };
4291
+ const cli = (0, _meow.default)(`
4292
+ Usage
4293
+ $ ${name}
4294
+
4295
+ Options
4296
+ ${(0, _formatting.printFlagList)(flags, 6)}
4297
+
4298
+ Examples
4299
+ $ ${name}
4300
+ $ ${name} --perPage=5 --page=2 --direction=asc --filter=joke
4301
+ `, {
4302
+ argv,
4303
+ description,
4304
+ importMeta,
4305
+ flags
4306
+ });
4307
+ const {
4308
+ json: outputJson,
4309
+ markdown: outputMarkdown,
4310
+ perPage: per_page,
4311
+ page,
4312
+ direction,
4313
+ filter
4314
+ } = cli.flags;
4315
+ return {
4316
+ outputJson,
4317
+ outputMarkdown,
4318
+ per_page,
4319
+ page,
4320
+ direction,
4321
+ filter
4322
+ };
4323
+ }
4324
+ async function fetchThreatFeed({
4325
+ per_page,
4326
+ page,
4327
+ direction,
4328
+ filter,
4329
+ outputJson
4330
+ }, spinner, apiKey) {
4331
+ const formattedQueryParams = formatQueryParams({
4332
+ per_page,
4333
+ page,
4334
+ direction,
4335
+ filter
4336
+ }).join('&');
4337
+ const response = await (0, _apiHelpers.queryAPI)(`threat-feed?${formattedQueryParams}`, apiKey);
4338
+ const data = await response.json();
4339
+ spinner.stop();
4340
+ if (outputJson) {
4341
+ return console.log(data);
4342
+ }
4343
+ const screen = _blessed.screen();
4344
+ const table = _blessedContrib.table({
4345
+ keys: 'true',
4346
+ fg: 'white',
4347
+ selectedFg: 'white',
4348
+ selectedBg: 'magenta',
4349
+ interactive: 'true',
4350
+ label: 'Threat feed',
4351
+ width: '100%',
4352
+ height: '100%',
4353
+ border: {
4354
+ type: 'line',
4355
+ fg: 'cyan'
4356
+ },
4357
+ columnSpacing: 3,
4358
+ //in chars
4359
+ columnWidth: [9, 30, 10, 17, 13, 100] /*in chars*/
4360
+ });
4361
+
4362
+ // allow control the table with the keyboard
4363
+ table.focus();
4364
+ screen.append(table);
4365
+ const formattedOutput = formatResults(data.results);
4366
+ table.setData({
4367
+ headers: ['Ecosystem', 'Name', 'Version', 'Threat type', 'Detected at', 'Details'],
4368
+ data: formattedOutput
4369
+ });
4370
+ screen.render();
4371
+ screen.key(['escape', 'q', 'C-c'], () => process.exit(0));
4372
+ }
4373
+ const formatResults = data => {
4374
+ return data.map(d => {
4375
+ const ecosystem = d.purl.split('pkg:')[1].split('/')[0];
4376
+ const name = d.purl.split('/')[1].split('@')[0];
4377
+ const version = d.purl.split('@')[1];
4378
+ const timeStart = new Date(d.createdAt).getMilliseconds();
4379
+ const timeEnd = Date.now();
4380
+ const diff = getHourDiff(timeStart, timeEnd);
4381
+ const hourDiff = diff > 0 ? `${diff} hours ago` : `${getMinDiff(timeStart, timeEnd)} minutes ago`;
4382
+ return [ecosystem, decodeURIComponent(name), version, d.threatType, hourDiff, d.locationHtmlUrl];
4383
+ });
4384
+ };
4385
+ const formatQueryParams = params => Object.entries(params).map(entry => `${entry[0]}=${entry[1]}`);
4386
+ const getHourDiff = (start, end) => Math.floor((end - start) / 3600000);
4387
+ const getMinDiff = (start, end) => Math.floor((end - start) / 60000);
4388
+
4389
+ (function (exports) {
4390
+
4391
+ Object.defineProperty(exports, "__esModule", {
4392
+ value: true
4393
+ });
4394
+ var _cdxgen = cdxgen;
4395
+ Object.keys(_cdxgen).forEach(function (key) {
4396
+ if (key === "default" || key === "__esModule") return;
4397
+ if (key in exports && exports[key] === _cdxgen[key]) return;
4398
+ Object.defineProperty(exports, key, {
4399
+ enumerable: true,
4400
+ get: function () {
4401
+ return _cdxgen[key];
4402
+ }
4403
+ });
4404
+ });
4405
+ var _info = info$1;
4406
+ Object.keys(_info).forEach(function (key) {
4407
+ if (key === "default" || key === "__esModule") return;
4408
+ if (key in exports && exports[key] === _info[key]) return;
4409
+ Object.defineProperty(exports, key, {
4410
+ enumerable: true,
4411
+ get: function () {
4412
+ return _info[key];
4413
+ }
4414
+ });
4415
+ });
4416
+ var _login = login;
4417
+ Object.keys(_login).forEach(function (key) {
4418
+ if (key === "default" || key === "__esModule") return;
4419
+ if (key in exports && exports[key] === _login[key]) return;
4420
+ Object.defineProperty(exports, key, {
4421
+ enumerable: true,
4422
+ get: function () {
4423
+ return _login[key];
4424
+ }
4425
+ });
4426
+ });
4427
+ var _logout = logout;
4428
+ Object.keys(_logout).forEach(function (key) {
4429
+ if (key === "default" || key === "__esModule") return;
4430
+ if (key in exports && exports[key] === _logout[key]) return;
4431
+ Object.defineProperty(exports, key, {
4432
+ enumerable: true,
4433
+ get: function () {
4434
+ return _logout[key];
4435
+ }
4436
+ });
4437
+ });
4438
+ var _npm = npm;
4439
+ Object.keys(_npm).forEach(function (key) {
4440
+ if (key === "default" || key === "__esModule") return;
4441
+ if (key in exports && exports[key] === _npm[key]) return;
4442
+ Object.defineProperty(exports, key, {
4443
+ enumerable: true,
4444
+ get: function () {
4445
+ return _npm[key];
4446
+ }
4447
+ });
4448
+ });
4449
+ var _npx = npx;
4450
+ Object.keys(_npx).forEach(function (key) {
4451
+ if (key === "default" || key === "__esModule") return;
4452
+ if (key in exports && exports[key] === _npx[key]) return;
4453
+ Object.defineProperty(exports, key, {
4454
+ enumerable: true,
4455
+ get: function () {
4456
+ return _npx[key];
4457
+ }
4458
+ });
4459
+ });
4460
+ var _optimize = optimize$1;
4461
+ Object.keys(_optimize).forEach(function (key) {
4462
+ if (key === "default" || key === "__esModule") return;
4463
+ if (key in exports && exports[key] === _optimize[key]) return;
4464
+ Object.defineProperty(exports, key, {
4465
+ enumerable: true,
4466
+ get: function () {
4467
+ return _optimize[key];
4468
+ }
4469
+ });
4470
+ });
4471
+ var _organization = organization;
4472
+ Object.keys(_organization).forEach(function (key) {
4473
+ if (key === "default" || key === "__esModule") return;
4474
+ if (key in exports && exports[key] === _organization[key]) return;
4475
+ Object.defineProperty(exports, key, {
4476
+ enumerable: true,
4477
+ get: function () {
4478
+ return _organization[key];
4479
+ }
4480
+ });
4481
+ });
4482
+ var _rawNpm = rawNpm$1;
4483
+ Object.keys(_rawNpm).forEach(function (key) {
4484
+ if (key === "default" || key === "__esModule") return;
4485
+ if (key in exports && exports[key] === _rawNpm[key]) return;
4486
+ Object.defineProperty(exports, key, {
4487
+ enumerable: true,
4488
+ get: function () {
4489
+ return _rawNpm[key];
4490
+ }
4491
+ });
4492
+ });
4493
+ var _rawNpx = rawNpx$1;
4494
+ Object.keys(_rawNpx).forEach(function (key) {
4495
+ if (key === "default" || key === "__esModule") return;
4496
+ if (key in exports && exports[key] === _rawNpx[key]) return;
4497
+ Object.defineProperty(exports, key, {
4498
+ enumerable: true,
4499
+ get: function () {
4500
+ return _rawNpx[key];
4501
+ }
4502
+ });
4503
+ });
4504
+ var _report = report;
4505
+ Object.keys(_report).forEach(function (key) {
4506
+ if (key === "default" || key === "__esModule") return;
4507
+ if (key in exports && exports[key] === _report[key]) return;
4508
+ Object.defineProperty(exports, key, {
4509
+ enumerable: true,
4510
+ get: function () {
4511
+ return _report[key];
4512
+ }
4513
+ });
4514
+ });
4515
+ var _wrapper = wrapper$1;
4516
+ Object.keys(_wrapper).forEach(function (key) {
4517
+ if (key === "default" || key === "__esModule") return;
4518
+ if (key in exports && exports[key] === _wrapper[key]) return;
4519
+ Object.defineProperty(exports, key, {
4520
+ enumerable: true,
4521
+ get: function () {
4522
+ return _wrapper[key];
4523
+ }
4524
+ });
4525
+ });
4526
+ var _scan = scan;
4527
+ Object.keys(_scan).forEach(function (key) {
4528
+ if (key === "default" || key === "__esModule") return;
4529
+ if (key in exports && exports[key] === _scan[key]) return;
4530
+ Object.defineProperty(exports, key, {
4531
+ enumerable: true,
4532
+ get: function () {
4533
+ return _scan[key];
4534
+ }
4535
+ });
4536
+ });
4537
+ var _auditLog = auditLog$1;
4538
+ Object.keys(_auditLog).forEach(function (key) {
4539
+ if (key === "default" || key === "__esModule") return;
4540
+ if (key in exports && exports[key] === _auditLog[key]) return;
4541
+ Object.defineProperty(exports, key, {
4542
+ enumerable: true,
4543
+ get: function () {
4544
+ return _auditLog[key];
4545
+ }
4546
+ });
4547
+ });
4548
+ var _repos = repos;
4549
+ Object.keys(_repos).forEach(function (key) {
4550
+ if (key === "default" || key === "__esModule") return;
4551
+ if (key in exports && exports[key] === _repos[key]) return;
4552
+ Object.defineProperty(exports, key, {
4553
+ enumerable: true,
4554
+ get: function () {
4555
+ return _repos[key];
4556
+ }
4557
+ });
4558
+ });
4559
+ var _dependencies = dependencies$1;
4560
+ Object.keys(_dependencies).forEach(function (key) {
4561
+ if (key === "default" || key === "__esModule") return;
4562
+ if (key in exports && exports[key] === _dependencies[key]) return;
4563
+ Object.defineProperty(exports, key, {
4564
+ enumerable: true,
4565
+ get: function () {
4566
+ return _dependencies[key];
4567
+ }
4568
+ });
4569
+ });
4570
+ var _analytics = analytics$1;
4571
+ Object.keys(_analytics).forEach(function (key) {
4572
+ if (key === "default" || key === "__esModule") return;
4573
+ if (key in exports && exports[key] === _analytics[key]) return;
4574
+ Object.defineProperty(exports, key, {
4575
+ enumerable: true,
4576
+ get: function () {
4577
+ return _analytics[key];
4578
+ }
4579
+ });
4580
+ });
4581
+ var _diffScan = diffScan;
4582
+ Object.keys(_diffScan).forEach(function (key) {
4583
+ if (key === "default" || key === "__esModule") return;
4584
+ if (key in exports && exports[key] === _diffScan[key]) return;
4585
+ Object.defineProperty(exports, key, {
4586
+ enumerable: true,
4587
+ get: function () {
4588
+ return _diffScan[key];
4589
+ }
4590
+ });
4591
+ });
4592
+ var _threatFeed = threatFeed$1;
4593
+ Object.keys(_threatFeed).forEach(function (key) {
4594
+ if (key === "default" || key === "__esModule") return;
4595
+ if (key in exports && exports[key] === _threatFeed[key]) return;
4596
+ Object.defineProperty(exports, key, {
4597
+ enumerable: true,
4598
+ get: function () {
4599
+ return _threatFeed[key];
4600
+ }
4601
+ });
4602
+ });
4603
+ } (commands));
4604
+
4605
+ var _interopRequireWildcard = vendor.interopRequireWildcard.default;
4606
+ var _interopRequireDefault = vendor.interopRequireDefault.default;
4607
+ var _nodeFs = require$$0;
4608
+ var _nodePath = require$$1;
4609
+ var _nodeUrl = require$$2$5;
4610
+ var _chalk = _interopRequireDefault(vendor.source);
4611
+ var _ponyCause = require$$6;
4612
+ var _updateNotifier = _interopRequireDefault(vendor.updateNotifier);
4613
+ var cliCommands = _interopRequireWildcard(commands, true);
4614
+ var _chalkMarkdown = sdk.chalkMarkdown;
4615
+ var _errors = sdk.errors;
4616
+ var _meowWithSubcommands = meowWithSubcommands$1;
4617
+ const distPath = __dirname;
4618
+ const rootPath = _nodePath.resolve(distPath, '..');
4619
+ const formattedCliCommands = Object.fromEntries(Object.entries(cliCommands).map(entry => {
4620
+ entry[0] = camelToHyphen(entry[0]);
4621
+ return entry;
4622
+ }));
4623
+ function camelToHyphen(str) {
4624
+ return str.replace(/[A-Z]+/g, '-$&').toLowerCase();
4625
+ }
4626
+
4627
+ // TODO: Add autocompletion using https://socket.dev/npm/package/omelette
4628
+ void (async () => {
4629
+ try {
4630
+ (0, _updateNotifier.default)({
4631
+ pkg: JSON.parse((0, _nodeFs.readFileSync)(_nodePath.join(rootPath, 'package.json'), 'utf8'))
4632
+ }).notify();
4633
+ } catch {}
4634
+ try {
4635
+ await (0, _meowWithSubcommands.meowWithSubcommands)(formattedCliCommands, {
4636
+ aliases: {
4637
+ ci: {
4638
+ description: 'Alias for "report create --view --strict"',
4639
+ argv: ['report', 'create', '--view', '--strict']
4640
+ }
4641
+ },
4642
+ argv: process.argv.slice(2),
4643
+ name: 'socket',
4644
+ importMeta: {
4645
+ url: `${(0, _nodeUrl.pathToFileURL)(__filename)}`
4646
+ }
4647
+ });
4648
+ } catch (err) {
4649
+ let errorTitle;
4650
+ let errorMessage = '';
4651
+ let errorBody;
4652
+ if (err instanceof _errors.AuthError) {
4653
+ errorTitle = 'Authentication error';
4654
+ errorMessage = err.message;
4655
+ } else if (err instanceof _errors.InputError) {
4656
+ errorTitle = 'Invalid input';
4657
+ errorMessage = err.message;
4658
+ errorBody = err.body;
4659
+ } else if (err instanceof Error) {
4660
+ errorTitle = 'Unexpected error';
4661
+ errorMessage = (0, _ponyCause.messageWithCauses)(err);
4662
+ errorBody = (0, _ponyCause.stackWithCauses)(err);
4663
+ } else {
4664
+ errorTitle = 'Unexpected error with no details';
4665
+ }
4666
+ console.error(`${_chalkMarkdown.logSymbols.error} ${_chalk.default.white.bgRed(errorTitle + ':')} ${errorMessage}`);
4667
+ if (errorBody) {
4668
+ console.error(`\n${errorBody}`);
4669
+ }
4670
+ process.exit(1);
4671
+ }
4672
+ })();
4673
+
4674
+ (function (exports) {
4675
+
4676
+ var _interopRequireWildcard = vendor.interopRequireWildcard.default;
4677
+ Object.defineProperty(exports, "__esModule", {
4678
+ value: true
4679
+ });
4680
+ var _exportNames = {};
4681
+ Object.defineProperty(exports, "default", {
4682
+ enumerable: true,
4683
+ get: function () {
4684
+ return _cli.default;
4685
+ }
4686
+ });
4687
+ var _cli = _interopRequireWildcard(cli, true);
4688
+ Object.keys(_cli).forEach(function (key) {
4689
+ if (key === "default" || key === "__esModule") return;
4690
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
4691
+ if (key in exports && exports[key] === _cli[key]) return;
4692
+ Object.defineProperty(exports, key, {
4693
+ enumerable: true,
4694
+ get: function () {
4695
+ return _cli[key];
4696
+ }
4697
+ });
4698
+ });
4699
+ } (cli$1));
4700
+
4701
+ module.exports = cli$1;