socket 0.0.1 → 0.14.12

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,4777 @@
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$$3$1 = require('semver');
16
+ var require$$1$3 = require('@socketregistry/hyrious__bun.lockb');
17
+ var require$$3 = require('browserslist');
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
+ // eslint-disable-next-line no-await-in-loop
882
+ const stats = await _nodeFs$4.promises.stat(filePath);
883
+ if (stats.isFile()) {
884
+ return filePath;
885
+ }
886
+ } catch {}
887
+ }
888
+ dir = _nodePath$4.dirname(dir);
889
+ }
890
+ return undefined;
891
+ }
892
+ async function readFileBinary(filepath, options) {
893
+ return await _nodeFs$4.promises.readFile(filepath, {
894
+ ...options,
895
+ encoding: 'binary'
896
+ });
897
+ }
898
+ async function readFileUtf8(filepath, options) {
899
+ return await _nodeFs$4.promises.readFile(filepath, {
900
+ ...options,
901
+ encoding: 'utf8'
902
+ });
903
+ }
904
+
905
+ var json = {};
906
+
907
+ Object.defineProperty(json, "__esModule", {
908
+ value: true
909
+ });
910
+ json.parseJSONObject = parseJSONObject;
911
+ var _objects$2 = objects;
912
+ function parseJSONObject(jsonStr) {
913
+ try {
914
+ const value = JSON.parse(jsonStr);
915
+ if ((0, _objects$2.isObjectObject)(value)) {
916
+ return value;
917
+ }
918
+ } catch {}
919
+ return null;
920
+ }
921
+
922
+ var strings = {};
923
+
924
+ Object.defineProperty(strings, "__esModule", {
925
+ value: true
926
+ });
927
+ strings.isNonEmptyString = isNonEmptyString;
928
+ function isNonEmptyString(value) {
929
+ return typeof value === 'string' && value.length > 0;
930
+ }
931
+
932
+ Object.defineProperty(packageManagerDetector, "__esModule", {
933
+ value: true
934
+ });
935
+ packageManagerDetector.LOCKS = packageManagerDetector.AGENTS = void 0;
936
+ packageManagerDetector.detect = detect;
937
+ var _nodePath$3 = require$$1;
938
+ var _hyrious__bun = require$$1$3;
939
+ var _promiseSpawn$3 = require$$1$1;
940
+ var _browserslist = require$$3;
941
+ var _semver$1 = require$$3$1;
942
+ var _which = require$$5$1;
943
+ var _fs = fs;
944
+ var _json = json;
945
+ var _objects$1 = objects;
946
+ var _strings = strings;
947
+ const PNPM_WORKSPACE = 'pnpm-workspace';
948
+ const AGENTS = packageManagerDetector.AGENTS = ['bun', 'npm', 'pnpm', 'yarn'];
949
+ const LOCKS = packageManagerDetector.LOCKS = {
950
+ 'bun.lockb': 'bun',
951
+ 'pnpm-lock.yaml': 'pnpm',
952
+ 'pnpm-lock.yml': 'pnpm',
953
+ 'yarn.lock': 'yarn',
954
+ // If both package-lock.json and npm-shrinkwrap.json are present in the root
955
+ // of a project, npm-shrinkwrap.json will take precedence and package-lock.json
956
+ // will be ignored.
957
+ // https://docs.npmjs.com/cli/v10/configuring-npm/package-lock-json#package-lockjson-vs-npm-shrinkwrapjson
958
+ 'npm-shrinkwrap.json': 'npm',
959
+ 'package-lock.json': 'npm',
960
+ // Look for a hidden lock file if .npmrc has package-lock=false:
961
+ // https://docs.npmjs.com/cli/v10/configuring-npm/package-lock-json#hidden-lockfiles
962
+ //
963
+ // Unlike the other LOCKS keys this key contains a directory AND filename so
964
+ // it has to be handled differently.
965
+ 'node_modules/.package-lock.json': 'npm'
966
+ };
967
+ const MAINTAINED_NODE_VERSIONS = _browserslist('maintained node versions')
968
+ // Trim value, e.g. 'node 22.5.0' to '22.5.0'
969
+ .map(v => v.slice(5));
970
+ const readLockFileByAgent = (() => {
971
+ const wrapReader = reader => async (lockPath, agentExecPath) => {
972
+ try {
973
+ return await reader(lockPath, agentExecPath);
974
+ } catch {}
975
+ return undefined;
976
+ };
977
+ return {
978
+ bun: wrapReader(async (lockPath, agentExecPath) => {
979
+ let lockBuffer;
980
+ try {
981
+ lockBuffer = await (0, _fs.readFileBinary)(lockPath);
982
+ } catch {
983
+ return undefined;
984
+ }
985
+ try {
986
+ return (0, _hyrious__bun.parse)(lockBuffer);
987
+ } catch {}
988
+ // To print a Yarn lockfile to your console without writing it to disk use `bun bun.lockb`.
989
+ // https://bun.sh/guides/install/yarnlock
990
+ return (await _promiseSpawn$3(agentExecPath ?? 'bun', [lockPath])).stdout;
991
+ }),
992
+ npm: wrapReader(async lockPath => await (0, _fs.readFileUtf8)(lockPath)),
993
+ pnpm: wrapReader(async lockPath => await (0, _fs.readFileUtf8)(lockPath)),
994
+ yarn: wrapReader(async lockPath => await (0, _fs.readFileUtf8)(lockPath))
995
+ };
996
+ })();
997
+ async function detect({
998
+ cwd = process.cwd(),
999
+ onUnknown
1000
+ } = {}) {
1001
+ let lockPath = await (0, _fs.findUp)(Object.keys(LOCKS), {
1002
+ cwd
1003
+ });
1004
+ const isHiddenLockFile = lockPath?.endsWith('.package-lock.json') ?? false;
1005
+ const pkgJsonPath = lockPath ? _nodePath$3.resolve(lockPath, `${isHiddenLockFile ? '../' : ''}../package.json`) : await (0, _fs.findUp)('package.json', {
1006
+ cwd
1007
+ });
1008
+ // Read Corepack `packageManager` field in package.json:
1009
+ // https://nodejs.org/api/packages.html#packagemanager
1010
+ const pkgJsonStr = (0, _fs.existsSync)(pkgJsonPath) ? await (0, _fs.readFileUtf8)(pkgJsonPath) : undefined;
1011
+ const pkgJson = typeof pkgJsonStr === 'string' ? (0, _json.parseJSONObject)(pkgJsonStr) ?? undefined : undefined;
1012
+ const pkgManager = (0, _strings.isNonEmptyString)((0, _objects$1.getOwn)(pkgJson, 'packageManager')) ? pkgJson?.['packageManager'] : undefined;
1013
+ let agent;
1014
+ let agentVersion;
1015
+ if (pkgManager) {
1016
+ const atSignIndex = pkgManager.lastIndexOf('@');
1017
+ if (atSignIndex !== -1) {
1018
+ const name = pkgManager.slice(0, atSignIndex);
1019
+ const version = pkgManager.slice(atSignIndex + 1);
1020
+ if (version && AGENTS.includes(name)) {
1021
+ agent = name;
1022
+ agentVersion = version;
1023
+ }
1024
+ }
1025
+ }
1026
+ if (agent === undefined && !isHiddenLockFile && typeof pkgJsonPath === 'string' && typeof lockPath === 'string') {
1027
+ agent = LOCKS[_nodePath$3.basename(lockPath)];
1028
+ }
1029
+ if (agent === undefined) {
1030
+ agent = 'npm';
1031
+ onUnknown?.(pkgManager);
1032
+ }
1033
+ const agentExecPath = (await _which(agent, {
1034
+ nothrow: true
1035
+ })) ?? agent;
1036
+ let lockSrc;
1037
+ const targets = {
1038
+ browser: false,
1039
+ node: true
1040
+ };
1041
+ let isPrivate = false;
1042
+ let isWorkspace = false;
1043
+ if (pkgJson) {
1044
+ const pkgPath = _nodePath$3.dirname(pkgJsonPath);
1045
+ isPrivate = !!pkgJson['private'];
1046
+ isWorkspace = !!pkgJson['workspaces'] || (0, _fs.existsSync)(_nodePath$3.join(pkgPath, `${PNPM_WORKSPACE}.yaml`)) || (0, _fs.existsSync)(_nodePath$3.join(pkgPath, `${PNPM_WORKSPACE}.yml`));
1047
+ let browser;
1048
+ let node;
1049
+ const browserField = (0, _objects$1.getOwn)(pkgJson, 'browser');
1050
+ if ((0, _strings.isNonEmptyString)(browserField) || (0, _objects$1.isObjectObject)(browserField)) {
1051
+ browser = true;
1052
+ }
1053
+ const nodeRange = (0, _objects$1.getOwn)(pkgJson['engines'], 'node');
1054
+ if ((0, _strings.isNonEmptyString)(nodeRange)) {
1055
+ node = MAINTAINED_NODE_VERSIONS.some(v => {
1056
+ const coerced = _semver$1.coerce(nodeRange);
1057
+ return coerced && _semver$1.satisfies(coerced, `^${_semver$1.major(v)}`);
1058
+ });
1059
+ }
1060
+ const browserslistQuery = (0, _objects$1.getOwn)(pkgJson, 'browserslist');
1061
+ if (Array.isArray(browserslistQuery)) {
1062
+ const browserslistTargets = _browserslist(browserslistQuery);
1063
+ const browserslistNodeTargets = browserslistTargets.filter(v => v.startsWith('node ')).map(v => v.slice(5));
1064
+ if (browser === undefined && browserslistTargets.length) {
1065
+ browser = browserslistTargets.length !== browserslistNodeTargets.length;
1066
+ }
1067
+ if (node === undefined && browserslistNodeTargets.length) {
1068
+ node = MAINTAINED_NODE_VERSIONS.some(v => browserslistNodeTargets.some(t => {
1069
+ const coerced = _semver$1.coerce(t);
1070
+ return coerced && _semver$1.satisfies(coerced, `^${_semver$1.major(v)}`);
1071
+ }));
1072
+ }
1073
+ }
1074
+ if (browser !== undefined) {
1075
+ targets.browser = browser;
1076
+ }
1077
+ if (node !== undefined) {
1078
+ targets.node = node;
1079
+ }
1080
+ lockSrc = typeof lockPath === 'string' ? await readLockFileByAgent[agent](lockPath, agentExecPath) : undefined;
1081
+ } else {
1082
+ lockPath = undefined;
1083
+ }
1084
+ return {
1085
+ agent,
1086
+ agentExecPath,
1087
+ agentVersion,
1088
+ isPrivate,
1089
+ isWorkspace,
1090
+ lockPath,
1091
+ lockSrc,
1092
+ pkgJson,
1093
+ pkgJsonPath,
1094
+ pkgJsonStr,
1095
+ supported: targets.browser || targets.node,
1096
+ targets
1097
+ };
1098
+ }
1099
+
1100
+ var regexps = {};
1101
+
1102
+ Object.defineProperty(regexps, "__esModule", {
1103
+ value: true
1104
+ });
1105
+ regexps.escapeRegExp = escapeRegExp;
1106
+ // Inlined "escape-string-regexp":
1107
+ // https://socket.dev/npm/package/escape-string-regexp/overview/5.0.0
1108
+ // MIT License
1109
+ // Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
1110
+ function escapeRegExp(string) {
1111
+ // Escape characters with special meaning either inside or outside character sets.
1112
+ // 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.
1113
+ return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
1114
+ }
1115
+
1116
+ var sorts = {};
1117
+
1118
+ Object.defineProperty(sorts, "__esModule", {
1119
+ value: true
1120
+ });
1121
+ sorts.localeCompare = void 0;
1122
+ sorts.toSortedObject = toSortedObject;
1123
+ const {
1124
+ compare: localeCompare
1125
+ } = new Intl.Collator();
1126
+ sorts.localeCompare = localeCompare;
1127
+ function toSortedObject(object, comparator = localeCompare) {
1128
+ return Object.fromEntries(Object.entries(object).sort((a, b) => comparator(a[0], b[0])));
1129
+ }
1130
+
1131
+ var _interopRequireDefault$n = vendor.interopRequireDefault.default;
1132
+ Object.defineProperty(optimize$1, "__esModule", {
1133
+ value: true
1134
+ });
1135
+ optimize$1.optimize = void 0;
1136
+ var _nodePath$2 = require$$1;
1137
+ var _promiseSpawn$2 = require$$1$1;
1138
+ var _packageJson = require$$3$2;
1139
+ var _registry = require$$4;
1140
+ var _meow$m = _interopRequireDefault$n(vendor.build);
1141
+ var _ora$i = _interopRequireDefault$n(vendor.ora);
1142
+ var _semver = require$$3$1;
1143
+ var _formatting$k = formatting;
1144
+ var _objects = objects;
1145
+ var _packageManagerDetector = packageManagerDetector;
1146
+ var _regexps = regexps;
1147
+ var _sorts$1 = sorts;
1148
+ const distPath$1 = __dirname;
1149
+ const COMMAND_TITLE = 'Socket Optimize';
1150
+ const OVERRIDES_FIELD_NAME = 'overrides';
1151
+ const RESOLUTIONS_FIELD_NAME = 'resolutions';
1152
+ const availableOverrides = (0, _registry.getManifestData)('npm').filter(({
1153
+ 1: d
1154
+ }) => d.engines?.node?.startsWith('>=18'));
1155
+ const getOverridesDataByAgent = {
1156
+ // npm overrides documentation:
1157
+ // https://docs.npmjs.com/cli/v10/configuring-npm/package-json#overrides
1158
+ npm: pkgJson => {
1159
+ const overrides = pkgJson?.overrides ?? {};
1160
+ return {
1161
+ type: 'npm',
1162
+ overrides
1163
+ };
1164
+ },
1165
+ // pnpm overrides documentation:
1166
+ // https://pnpm.io/package_json#pnpmoverrides
1167
+ pnpm: pkgJson => {
1168
+ const overrides = pkgJson?.pnpm?.overrides ?? {};
1169
+ return {
1170
+ type: 'pnpm',
1171
+ overrides
1172
+ };
1173
+ },
1174
+ // Yarn resolutions documentation:
1175
+ // https://yarnpkg.com/configuration/manifest#resolutions
1176
+ yarn: pkgJson => {
1177
+ const overrides = pkgJson?.resolutions ?? {};
1178
+ return {
1179
+ type: 'yarn',
1180
+ overrides
1181
+ };
1182
+ }
1183
+ };
1184
+ const lockIncludesByAgent = {
1185
+ npm: (lockSrc, name) => {
1186
+ // Detects the package name in the following cases:
1187
+ // "name":
1188
+ return lockSrc.includes(`"${name}":`);
1189
+ },
1190
+ pnpm: (lockSrc, name) => {
1191
+ const escapedName = (0, _regexps.escapeRegExp)(name);
1192
+ return new RegExp(
1193
+ // Detects the package name in the following cases:
1194
+ // /name/
1195
+ // 'name'
1196
+ // name:
1197
+ // name@
1198
+ `(?<=^\\s*)(?:(['/])${escapedName}\\1|${escapedName}(?=[:@]))`, 'm').test(lockSrc);
1199
+ },
1200
+ yarn: (lockSrc, name) => {
1201
+ const escapedName = (0, _regexps.escapeRegExp)(name);
1202
+ return new RegExp(
1203
+ // Detects the package name in the following cases:
1204
+ // "name@
1205
+ // , "name@
1206
+ // name@
1207
+ // , name@
1208
+ `(?<=(?:^\\s*|,\\s*)"?)${escapedName}(?=@)`, 'm').test(lockSrc);
1209
+ }
1210
+ };
1211
+ const updateManifestByAgent = {
1212
+ __proto__: null,
1213
+ npm(editablePkgJson, overrides) {
1214
+ editablePkgJson.update({
1215
+ __proto__: null,
1216
+ [OVERRIDES_FIELD_NAME]: overrides
1217
+ });
1218
+ },
1219
+ pnpm(editablePkgJson, overrides) {
1220
+ editablePkgJson.update({
1221
+ pnpm: {
1222
+ __proto__: null,
1223
+ ...editablePkgJson.content['pnpm'],
1224
+ [OVERRIDES_FIELD_NAME]: overrides
1225
+ }
1226
+ });
1227
+ },
1228
+ yarn(editablePkgJson, overrides) {
1229
+ editablePkgJson.update({
1230
+ __proto__: null,
1231
+ [RESOLUTIONS_FIELD_NAME]: overrides
1232
+ });
1233
+ }
1234
+ };
1235
+ async function addOverrides({
1236
+ agent,
1237
+ isPrivate,
1238
+ isWorkspace,
1239
+ lockSrc,
1240
+ lockIncludes,
1241
+ pkgJsonPath
1242
+ }, aoState) {
1243
+ const {
1244
+ packageNames
1245
+ } = aoState;
1246
+ const editablePkgJson = await _packageJson.load(_nodePath$2.dirname(pkgJsonPath));
1247
+ const {
1248
+ dependencies,
1249
+ devDependencies,
1250
+ peerDependencies,
1251
+ optionalDependencies
1252
+ } = editablePkgJson.content;
1253
+ const depEntries = [['dependencies', dependencies ? {
1254
+ __proto__: null,
1255
+ ...dependencies
1256
+ } : undefined], ['devDependencies', devDependencies ? {
1257
+ __proto__: null,
1258
+ ...devDependencies
1259
+ } : undefined], ['peerDependencies', peerDependencies ? {
1260
+ __proto__: null,
1261
+ ...peerDependencies
1262
+ } : undefined], ['optionalDependencies', optionalDependencies ? {
1263
+ __proto__: null,
1264
+ ...optionalDependencies
1265
+ } : undefined]].filter(({
1266
+ 1: o
1267
+ }) => o);
1268
+ const overridesDataObjects = [];
1269
+ if (isPrivate || isWorkspace) {
1270
+ overridesDataObjects.push(getOverridesDataByAgent[agent](editablePkgJson.content));
1271
+ } else {
1272
+ overridesDataObjects.push(getOverridesDataByAgent['npm'](editablePkgJson.content), getOverridesDataByAgent['yarn'](editablePkgJson.content));
1273
+ }
1274
+ const aliasMap = new Map();
1275
+ for (const {
1276
+ 1: data
1277
+ } of availableOverrides) {
1278
+ const {
1279
+ name: regPkgName,
1280
+ package: origPkgName,
1281
+ version
1282
+ } = data;
1283
+ for (const {
1284
+ 1: depObj
1285
+ } of depEntries) {
1286
+ let pkgSpec = depObj[origPkgName];
1287
+ if (pkgSpec) {
1288
+ // Add package aliases for direct dependencies to avoid npm EOVERRIDE errors.
1289
+ // https://docs.npmjs.com/cli/v8/using-npm/package-spec#aliases
1290
+ const overrideSpecPrefix = `npm:${regPkgName}@`;
1291
+ if (!pkgSpec.startsWith(overrideSpecPrefix)) {
1292
+ aliasMap.set(regPkgName, pkgSpec);
1293
+ } else {
1294
+ packageNames.add(regPkgName);
1295
+ pkgSpec = `${overrideSpecPrefix}^${version}`;
1296
+ depObj[origPkgName] = pkgSpec;
1297
+ }
1298
+ aliasMap.set(origPkgName, pkgSpec);
1299
+ }
1300
+ }
1301
+ for (const {
1302
+ type,
1303
+ overrides
1304
+ } of overridesDataObjects) {
1305
+ if (!(0, _objects.hasOwn)(overrides, origPkgName) && lockIncludes(lockSrc, origPkgName)) {
1306
+ packageNames.add(regPkgName);
1307
+ overrides[origPkgName] =
1308
+ // With npm you may not set an override for a package that you directly
1309
+ // depend on unless both the dependency and the override itself share
1310
+ // the exact same spec. To make this limitation easier to deal with,
1311
+ // overrides may also be defined as a reference to a spec for a direct
1312
+ // dependency by prefixing the name of the package you wish the version
1313
+ // to match with a $.
1314
+ // https://docs.npmjs.com/cli/v8/configuring-npm/package-json#overrides
1315
+ type === 'npm' && aliasMap.has(origPkgName) && `$${origPkgName}` || `npm:${regPkgName}@^${_semver.major(version)}`;
1316
+ }
1317
+ }
1318
+ }
1319
+ if (packageNames.size) {
1320
+ editablePkgJson.update(Object.fromEntries(depEntries));
1321
+ for (const {
1322
+ type,
1323
+ overrides
1324
+ } of overridesDataObjects) {
1325
+ updateManifestByAgent[type](editablePkgJson, (0, _sorts$1.toSortedObject)(overrides));
1326
+ }
1327
+ await editablePkgJson.save();
1328
+ }
1329
+ return aoState;
1330
+ }
1331
+ const optimize = optimize$1.optimize = {
1332
+ description: 'Optimize dependencies with @socketregistry overrides',
1333
+ async run(argv, importMeta, {
1334
+ parentName
1335
+ }) {
1336
+ const commandContext = setupCommand$l(`${parentName} dependency optimize`, optimize.description, argv, importMeta);
1337
+ if (commandContext) {
1338
+ const cwd = process.cwd();
1339
+ const {
1340
+ agent,
1341
+ agentExecPath,
1342
+ isPrivate,
1343
+ isWorkspace,
1344
+ lockSrc,
1345
+ lockPath,
1346
+ pkgJsonPath,
1347
+ pkgJsonStr,
1348
+ pkgJson,
1349
+ supported
1350
+ } = await (0, _packageManagerDetector.detect)({
1351
+ cwd,
1352
+ onUnknown(pkgManager) {
1353
+ console.log(`⚠️ ${COMMAND_TITLE}: Unknown package manager${pkgManager ? ` ${pkgManager}` : ''}, defaulting to npm`);
1354
+ }
1355
+ });
1356
+ if (!supported) {
1357
+ console.log(`✘ ${COMMAND_TITLE}: Package engines.node range is not supported`);
1358
+ return;
1359
+ }
1360
+ const lockName = lockPath ? _nodePath$2.basename(lockPath) : 'lock file';
1361
+ if (lockSrc === undefined) {
1362
+ console.log(`✘ ${COMMAND_TITLE}: No ${lockName} found`);
1363
+ return;
1364
+ }
1365
+ if (pkgJson === undefined) {
1366
+ console.log(`✘ ${COMMAND_TITLE}: No package.json found`);
1367
+ return;
1368
+ }
1369
+ if (lockPath && _nodePath$2.relative(cwd, lockPath).startsWith('.')) {
1370
+ console.log(`⚠️ ${COMMAND_TITLE}: Package ${lockName} found at ${lockPath}`);
1371
+ }
1372
+ const aoState = {
1373
+ output: pkgJsonStr,
1374
+ packageNames: new Set()
1375
+ };
1376
+ if (lockSrc) {
1377
+ const lockIncludes = agent === 'bun' ? lockIncludesByAgent.yarn : lockIncludesByAgent[agent];
1378
+ await addOverrides({
1379
+ __proto__: null,
1380
+ agent: agent === 'bun' ? 'yarn' : agent,
1381
+ isPrivate,
1382
+ isWorkspace,
1383
+ lockIncludes,
1384
+ lockSrc,
1385
+ pkgJsonPath,
1386
+ pkgJsonStr,
1387
+ pkgJson
1388
+ }, aoState);
1389
+ }
1390
+ const {
1391
+ size: count
1392
+ } = aoState.packageNames;
1393
+ if (count) {
1394
+ console.log(`Added ${count} Socket.dev optimized overrides 🚀`);
1395
+ } else {
1396
+ console.log('Congratulations! Already Socket.dev optimized 🎉');
1397
+ }
1398
+ const isNpm = agent === 'npm';
1399
+ if (isNpm || count) {
1400
+ // Always update package-lock.json until the npm overrides PR lands:
1401
+ // https://github.com/npm/cli/pull/7025
1402
+ const spinner = (0, _ora$i.default)(`Updating ${lockName}...`).start();
1403
+ try {
1404
+ if (isNpm) {
1405
+ const wrapperPath = _nodePath$2.join(distPath$1, 'npm-cli.js');
1406
+ await _promiseSpawn$2(process.execPath, [wrapperPath, 'install'], {
1407
+ stdio: 'pipe',
1408
+ env: {
1409
+ __proto__: null,
1410
+ ...process.env,
1411
+ UPDATE_SOCKET_OVERRIDES_IN_PACKAGE_LOCK_FILE: '1'
1412
+ }
1413
+ });
1414
+ } else {
1415
+ await _promiseSpawn$2(agentExecPath, ['install'], {
1416
+ stdio: 'pipe'
1417
+ });
1418
+ }
1419
+ spinner.stop();
1420
+ if (isNpm) {
1421
+ console.log(`💡 Re-run ${COMMAND_TITLE} whenever ${lockName} changes.\n This can be skipped once npm ships https://github.com/npm/cli/pull/7025.`);
1422
+ }
1423
+ } catch {
1424
+ spinner.stop();
1425
+ console.log(`✘ ${COMMAND_TITLE}: ${agent} install failed to update ${lockName}`);
1426
+ }
1427
+ }
1428
+ }
1429
+ }
1430
+ };
1431
+
1432
+ // Internal functions
1433
+
1434
+ function setupCommand$l(name, description, argv, importMeta) {
1435
+ const flags = {};
1436
+ const cli = (0, _meow$m.default)(`
1437
+ Usage
1438
+ $ ${name}
1439
+
1440
+ Options
1441
+ ${(0, _formatting$k.printFlagList)(flags, 6)}
1442
+
1443
+ Examples
1444
+ $ ${name}
1445
+ `, {
1446
+ argv,
1447
+ description,
1448
+ importMeta,
1449
+ flags
1450
+ });
1451
+ const {
1452
+ json: outputJson,
1453
+ markdown: outputMarkdown,
1454
+ limit,
1455
+ offset
1456
+ } = cli.flags;
1457
+ return {
1458
+ outputJson,
1459
+ outputMarkdown,
1460
+ limit,
1461
+ offset
1462
+ };
1463
+ }
1464
+
1465
+ var organization = {};
1466
+
1467
+ var _interopRequireDefault$m = vendor.interopRequireDefault.default;
1468
+ Object.defineProperty(organization, "__esModule", {
1469
+ value: true
1470
+ });
1471
+ organization.organizations = void 0;
1472
+ var _chalk$g = _interopRequireDefault$m(vendor.source);
1473
+ var _meow$l = _interopRequireDefault$m(vendor.build);
1474
+ var _ora$h = _interopRequireDefault$m(vendor.ora);
1475
+ var _apiHelpers$h = apiHelpers;
1476
+ var _errors$i = sdk.errors;
1477
+ var _sdk$h = sdk.sdk;
1478
+ const organizations = organization.organizations = {
1479
+ description: 'List organizations associated with the API key used',
1480
+ async run(argv, importMeta, {
1481
+ parentName
1482
+ }) {
1483
+ setupCommand$k(`${parentName} organizations`, organizations.description, argv, importMeta);
1484
+ await fetchOrganizations();
1485
+ }
1486
+ };
1487
+
1488
+ // Internal functions
1489
+
1490
+ function setupCommand$k(name, description, argv, importMeta) {
1491
+ (0, _meow$l.default)(`
1492
+ Usage
1493
+ $ ${name}
1494
+ `, {
1495
+ argv,
1496
+ description,
1497
+ importMeta
1498
+ });
1499
+ }
1500
+ async function fetchOrganizations() {
1501
+ const apiKey = (0, _sdk$h.getDefaultKey)();
1502
+ if (!apiKey) {
1503
+ 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.');
1504
+ }
1505
+ const socketSdk = await (0, _sdk$h.setupSdk)(apiKey);
1506
+ const spinner = (0, _ora$h.default)('Fetching organizations...').start();
1507
+ const result = await (0, _apiHelpers$h.handleApiCall)(socketSdk.getOrganizations(), 'looking up organizations');
1508
+ if (result.success === false) {
1509
+ (0, _apiHelpers$h.handleUnsuccessfulApiResponse)('getOrganizations', result, spinner);
1510
+ return;
1511
+ }
1512
+ spinner.stop();
1513
+ const organizations = Object.values(result.data.organizations);
1514
+ console.log(`List of organizations associated with your API key: ${_chalk$g.default.italic(apiKey)}`);
1515
+ for (const o of organizations) {
1516
+ console.log(`
1517
+ Name: ${o?.name}
1518
+ ID: ${o?.id}
1519
+ Plan: ${o?.plan}
1520
+ `);
1521
+ }
1522
+ }
1523
+
1524
+ var rawNpm$1 = {};
1525
+
1526
+ var _interopRequireDefault$l = vendor.interopRequireDefault.default;
1527
+ Object.defineProperty(rawNpm$1, "__esModule", {
1528
+ value: true
1529
+ });
1530
+ rawNpm$1.rawNpm = void 0;
1531
+ var _promiseSpawn$1 = require$$1$1;
1532
+ var _meow$k = _interopRequireDefault$l(vendor.build);
1533
+ var _flags$h = flags$1;
1534
+ var _formatting$j = formatting;
1535
+ const rawNpm = rawNpm$1.rawNpm = {
1536
+ description: 'Temporarily disable the Socket npm wrapper',
1537
+ async run(argv, importMeta, {
1538
+ parentName
1539
+ }) {
1540
+ await setupCommand$j(`${parentName} raw-npm`, rawNpm.description, argv, importMeta);
1541
+ }
1542
+ };
1543
+ async function setupCommand$j(name, description, argv, importMeta) {
1544
+ const flags = _flags$h.validationFlags;
1545
+ const cli = (0, _meow$k.default)(`
1546
+ Usage
1547
+ $ ${name} <npm command>
1548
+
1549
+ Options
1550
+ ${(0, _formatting$j.printFlagList)(flags, 6)}
1551
+
1552
+ Examples
1553
+ $ ${name} install
1554
+ `, {
1555
+ argv,
1556
+ description,
1557
+ importMeta,
1558
+ flags
1559
+ });
1560
+ if (!argv[0]) {
1561
+ cli.showHelp();
1562
+ return;
1563
+ }
1564
+ const spawnPromise = _promiseSpawn$1('npm', [argv.join(' ')], {
1565
+ stdio: 'inherit'
1566
+ });
1567
+ spawnPromise.process.on('exit', (code, signal) => {
1568
+ if (signal) {
1569
+ process.kill(process.pid, signal);
1570
+ } else if (code !== null) {
1571
+ process.exit(code);
1572
+ }
1573
+ });
1574
+ await spawnPromise;
1575
+ }
1576
+
1577
+ var rawNpx$1 = {};
1578
+
1579
+ var _interopRequireDefault$k = vendor.interopRequireDefault.default;
1580
+ Object.defineProperty(rawNpx$1, "__esModule", {
1581
+ value: true
1582
+ });
1583
+ rawNpx$1.rawNpx = void 0;
1584
+ var _promiseSpawn = require$$1$1;
1585
+ var _meow$j = _interopRequireDefault$k(vendor.build);
1586
+ var _flags$g = flags$1;
1587
+ var _formatting$i = formatting;
1588
+ const rawNpx = rawNpx$1.rawNpx = {
1589
+ description: 'Temporarily disable the Socket npm/npx wrapper',
1590
+ async run(argv, importMeta, {
1591
+ parentName
1592
+ }) {
1593
+ await setupCommand$i(`${parentName} raw-npx`, rawNpx.description, argv, importMeta);
1594
+ }
1595
+ };
1596
+ async function setupCommand$i(name, description, argv, importMeta) {
1597
+ const flags = _flags$g.validationFlags;
1598
+ const cli = (0, _meow$j.default)(`
1599
+ Usage
1600
+ $ ${name} <npx command>
1601
+
1602
+ Options
1603
+ ${(0, _formatting$i.printFlagList)(flags, 6)}
1604
+
1605
+ Examples
1606
+ $ ${name} install
1607
+ `, {
1608
+ argv,
1609
+ description,
1610
+ importMeta,
1611
+ flags
1612
+ });
1613
+ if (!argv[0]) {
1614
+ cli.showHelp();
1615
+ return;
1616
+ }
1617
+ const spawnPromise = _promiseSpawn('npx', [argv.join(' ')], {
1618
+ stdio: 'inherit'
1619
+ });
1620
+ spawnPromise.process.on('exit', (code, signal) => {
1621
+ if (signal) {
1622
+ process.kill(process.pid, signal);
1623
+ } else if (code !== null) {
1624
+ process.exit(code);
1625
+ }
1626
+ });
1627
+ await spawnPromise;
1628
+ }
1629
+
1630
+ var report = {};
1631
+
1632
+ var create$5 = {};
1633
+
1634
+ var view$3 = {};
1635
+
1636
+ var _interopRequireDefault$j = vendor.interopRequireDefault.default;
1637
+ Object.defineProperty(view$3, "__esModule", {
1638
+ value: true
1639
+ });
1640
+ view$3.fetchReportData = fetchReportData;
1641
+ view$3.formatReportDataOutput = formatReportDataOutput;
1642
+ view$3.view = void 0;
1643
+ var _chalk$f = _interopRequireDefault$j(vendor.source);
1644
+ var _meow$i = _interopRequireDefault$j(vendor.build);
1645
+ var _ora$g = _interopRequireDefault$j(vendor.ora);
1646
+ var _ponyCause$3 = require$$6;
1647
+ var _flags$f = flags$1;
1648
+ var _apiHelpers$g = apiHelpers;
1649
+ var _chalkMarkdown$2 = sdk.chalkMarkdown;
1650
+ var _errors$h = sdk.errors;
1651
+ var _formatIssues = formatIssues;
1652
+ var _formatting$h = formatting;
1653
+ var _sdk$g = sdk.sdk;
1654
+ const view$2 = view$3.view = {
1655
+ description: 'View a project report',
1656
+ async run(argv, importMeta, {
1657
+ parentName
1658
+ }) {
1659
+ const name = `${parentName} view`;
1660
+ const commandContext = setupCommand$h(name, view$2.description, argv, importMeta);
1661
+ const result = commandContext ? await fetchReportData(commandContext.reportId, commandContext) : undefined;
1662
+ if (result) {
1663
+ formatReportDataOutput(result, {
1664
+ name,
1665
+ ...(commandContext ?? {})
1666
+ });
1667
+ }
1668
+ }
1669
+ };
1670
+
1671
+ // Internal functions
1672
+
1673
+ function setupCommand$h(name, description, argv, importMeta) {
1674
+ const flags = {
1675
+ __proto__: null,
1676
+ ..._flags$f.outputFlags,
1677
+ ..._flags$f.validationFlags
1678
+ };
1679
+ const cli = (0, _meow$i.default)(`
1680
+ Usage
1681
+ $ ${name} <report-identifier>
1682
+
1683
+ Options
1684
+ ${(0, _formatting$h.printFlagList)(flags, 6)}
1685
+
1686
+ Examples
1687
+ $ ${name} QXU8PmK7LfH608RAwfIKdbcHgwEd_ZeWJ9QEGv05FJUQ
1688
+ `, {
1689
+ argv,
1690
+ description,
1691
+ importMeta,
1692
+ flags
1693
+ });
1694
+
1695
+ // Extract the input
1696
+
1697
+ const {
1698
+ all: includeAllIssues,
1699
+ json: outputJson,
1700
+ markdown: outputMarkdown,
1701
+ strict
1702
+ } = cli.flags;
1703
+ const [reportId, ...extraInput] = cli.input;
1704
+ if (!reportId) {
1705
+ cli.showHelp();
1706
+ return;
1707
+ }
1708
+
1709
+ // Validate the input
1710
+
1711
+ if (extraInput.length) {
1712
+ 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(', ')}`);
1713
+ }
1714
+ return {
1715
+ includeAllIssues,
1716
+ outputJson,
1717
+ outputMarkdown,
1718
+ reportId,
1719
+ strict
1720
+ };
1721
+ }
1722
+ const MAX_TIMEOUT_RETRY = 5;
1723
+ async function fetchReportData(reportId, {
1724
+ includeAllIssues,
1725
+ strict
1726
+ }) {
1727
+ // Do the API call
1728
+
1729
+ const socketSdk = await (0, _sdk$g.setupSdk)();
1730
+ const spinner = (0, _ora$g.default)(`Fetching report with ID ${reportId} (this could take a while)`).start();
1731
+ let result;
1732
+ for (let retry = 1; !result; ++retry) {
1733
+ try {
1734
+ // eslint-disable-next-line no-await-in-loop
1735
+ result = await (0, _apiHelpers$g.handleApiCall)(socketSdk.getReport(reportId), 'fetching report');
1736
+ } catch (err) {
1737
+ if (retry >= MAX_TIMEOUT_RETRY || !(err instanceof _ponyCause$3.ErrorWithCause) || err.cause?.cause?.response?.statusCode !== 524) {
1738
+ throw err;
1739
+ }
1740
+ }
1741
+ }
1742
+ if (result.success === false) {
1743
+ return (0, _apiHelpers$g.handleUnsuccessfulApiResponse)('getReport', result, spinner);
1744
+ }
1745
+
1746
+ // Conclude the status of the API call
1747
+
1748
+ if (strict) {
1749
+ if (result.data.healthy) {
1750
+ spinner.succeed('Report result is healthy and great!');
1751
+ } else {
1752
+ spinner.fail('Report result deemed unhealthy for project');
1753
+ }
1754
+ } else if (result.data.healthy === false) {
1755
+ const severityCount = (0, _formatIssues.getSeverityCount)(result.data.issues, includeAllIssues ? undefined : 'high');
1756
+ const issueSummary = (0, _formatIssues.formatSeverityCount)(severityCount);
1757
+ spinner.succeed(`Report has these issues: ${issueSummary}`);
1758
+ } else {
1759
+ spinner.succeed('Report has no issues');
1760
+ }
1761
+ return result.data;
1762
+ }
1763
+ function formatReportDataOutput(data, {
1764
+ name,
1765
+ outputJson,
1766
+ outputMarkdown,
1767
+ reportId,
1768
+ strict
1769
+ }) {
1770
+ if (outputJson) {
1771
+ console.log(JSON.stringify(data, undefined, 2));
1772
+ } else {
1773
+ const format = new _chalkMarkdown$2.ChalkOrMarkdown(!!outputMarkdown);
1774
+ console.log('\nDetailed info on socket.dev: ' + format.hyperlink(reportId, data.url, {
1775
+ fallbackToUrl: true
1776
+ }));
1777
+ if (!outputMarkdown) {
1778
+ 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'));
1779
+ }
1780
+ }
1781
+ if (strict && data.healthy === false) {
1782
+ process.exit(1);
1783
+ }
1784
+ }
1785
+
1786
+ var _interopRequireDefault$i = vendor.interopRequireDefault.default;
1787
+ Object.defineProperty(create$5, "__esModule", {
1788
+ value: true
1789
+ });
1790
+ create$5.create = void 0;
1791
+ var _nodePath$1 = require$$1;
1792
+ var _betterAjvErrors = require$$2;
1793
+ var _config = require$$3$3;
1794
+ var _meow$h = _interopRequireDefault$i(vendor.build);
1795
+ var _ora$f = _interopRequireDefault$i(vendor.ora);
1796
+ var _ponyCause$2 = require$$6;
1797
+ var _view$2 = view$3;
1798
+ var _flags$e = flags$1;
1799
+ var _apiHelpers$f = apiHelpers;
1800
+ var _chalkMarkdown$1 = sdk.chalkMarkdown;
1801
+ var _errors$g = sdk.errors;
1802
+ var _formatting$g = formatting;
1803
+ var _misc$1 = sdk.misc;
1804
+ var _pathResolve$1 = pathResolve.pathResolve;
1805
+ var _sdk$f = sdk.sdk;
1806
+ const create$4 = create$5.create = {
1807
+ description: 'Create a project report',
1808
+ async run(argv, importMeta, {
1809
+ parentName
1810
+ }) {
1811
+ const name = `${parentName} create`;
1812
+ const input = await setupCommand$g(name, create$4.description, argv, importMeta);
1813
+ if (input) {
1814
+ const {
1815
+ config,
1816
+ cwd,
1817
+ debugLog,
1818
+ dryRun,
1819
+ includeAllIssues,
1820
+ outputJson,
1821
+ outputMarkdown,
1822
+ packagePaths,
1823
+ strict,
1824
+ view
1825
+ } = input;
1826
+ const result = input && (await createReport(packagePaths, {
1827
+ config,
1828
+ cwd,
1829
+ debugLog,
1830
+ dryRun
1831
+ }));
1832
+ if (result && view) {
1833
+ const reportId = result.data.id;
1834
+ const reportData = input && (await (0, _view$2.fetchReportData)(reportId, {
1835
+ includeAllIssues,
1836
+ strict
1837
+ }));
1838
+ if (reportData) {
1839
+ (0, _view$2.formatReportDataOutput)(reportData, {
1840
+ includeAllIssues,
1841
+ name,
1842
+ outputJson,
1843
+ outputMarkdown,
1844
+ reportId,
1845
+ strict
1846
+ });
1847
+ }
1848
+ } else if (result) {
1849
+ formatReportCreationOutput(result.data, {
1850
+ outputJson,
1851
+ outputMarkdown
1852
+ });
1853
+ }
1854
+ }
1855
+ }
1856
+ };
1857
+
1858
+ // Internal functions
1859
+
1860
+ async function setupCommand$g(name, description, argv, importMeta) {
1861
+ const flags = {
1862
+ __proto__: null,
1863
+ ..._flags$e.outputFlags,
1864
+ ..._flags$e.validationFlags,
1865
+ debug: {
1866
+ type: 'boolean',
1867
+ shortFlag: 'd',
1868
+ default: false,
1869
+ description: 'Output debug information'
1870
+ },
1871
+ dryRun: {
1872
+ type: 'boolean',
1873
+ default: false,
1874
+ description: 'Only output what will be done without actually doing it'
1875
+ },
1876
+ view: {
1877
+ type: 'boolean',
1878
+ shortFlag: 'v',
1879
+ default: false,
1880
+ description: 'Will wait for and return the created report'
1881
+ }
1882
+ };
1883
+ const cli = (0, _meow$h.default)(`
1884
+ Usage
1885
+ $ ${name} <paths-to-package-folders-and-files>
1886
+
1887
+ Uploads the specified "package.json" and lock files for JavaScript, Python, and Go dependency manifests.
1888
+ If any folder is specified, the ones found in there recursively are uploaded.
1889
+
1890
+ Supports globbing such as "**/package.json", "**/requirements.txt", "**/pyproject.toml", and "**/go.mod".
1891
+
1892
+ Ignores any file specified in your project's ".gitignore", your project's
1893
+ "socket.yml" file's "projectIgnorePaths" and also has a sensible set of
1894
+ default ignores from the "ignore-by-default" module.
1895
+
1896
+ Options
1897
+ ${(0, _formatting$g.printFlagList)({
1898
+ all: 'Include all issues',
1899
+ debug: 'Output debug information',
1900
+ 'dry-run': 'Only output what will be done without actually doing it',
1901
+ json: 'Output result as json',
1902
+ markdown: 'Output result as markdown',
1903
+ strict: 'Exits with an error code if any matching issues are found',
1904
+ view: 'Will wait for and return the created report'
1905
+ }, 6)}
1906
+
1907
+ Examples
1908
+ $ ${name} .
1909
+ $ ${name} '**/package.json'
1910
+ $ ${name} /path/to/a/package.json /path/to/another/package.json
1911
+ $ ${name} . --view --json
1912
+ `, {
1913
+ argv,
1914
+ description,
1915
+ importMeta,
1916
+ flags
1917
+ });
1918
+ const {
1919
+ all: includeAllIssues,
1920
+ dryRun,
1921
+ json: outputJson,
1922
+ markdown: outputMarkdown,
1923
+ strict,
1924
+ view
1925
+ } = cli.flags;
1926
+ if (!cli.input[0]) {
1927
+ cli.showHelp();
1928
+ return;
1929
+ }
1930
+ const debugLog = (0, _misc$1.createDebugLogger)(!dryRun || cli.flags['debug']);
1931
+
1932
+ // TODO: Allow setting a custom cwd and/or configFile path?
1933
+ const cwd = process.cwd();
1934
+ const absoluteConfigPath = _nodePath$1.join(cwd, 'socket.yml');
1935
+ const config = await (0, _config.readSocketConfig)(absoluteConfigPath).catch(cause => {
1936
+ if (cause && typeof cause === 'object' && cause instanceof _config.SocketValidationError) {
1937
+ // Inspired by workbox-build:
1938
+ // https://github.com/GoogleChrome/workbox/blob/95f97a207fd51efb3f8a653f6e3e58224183a778/packages/workbox-build/src/lib/validate-options.ts#L68-L71
1939
+ const betterErrors = (0, _betterAjvErrors.betterAjvErrors)({
1940
+ basePath: 'config',
1941
+ data: cause.data,
1942
+ errors: cause.validationErrors,
1943
+ schema: cause.schema
1944
+ });
1945
+ 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'));
1946
+ } else {
1947
+ throw new _ponyCause$2.ErrorWithCause('Failed to read socket.yml config', {
1948
+ cause
1949
+ });
1950
+ }
1951
+ });
1952
+ const socketSdk = await (0, _sdk$f.setupSdk)();
1953
+ const supportedFiles = await socketSdk.getReportSupportedFiles().then(res => {
1954
+ if (!res.success) (0, _apiHelpers$f.handleUnsuccessfulApiResponse)('getReportSupportedFiles', res, (0, _ora$f.default)());
1955
+ return res.data;
1956
+ }).catch(cause => {
1957
+ throw new _ponyCause$2.ErrorWithCause('Failed getting supported files for report', {
1958
+ cause
1959
+ });
1960
+ });
1961
+ const packagePaths = await (0, _pathResolve$1.getPackageFiles)(cwd, cli.input, config, supportedFiles, debugLog);
1962
+ return {
1963
+ config,
1964
+ cwd,
1965
+ debugLog,
1966
+ dryRun,
1967
+ includeAllIssues,
1968
+ outputJson,
1969
+ outputMarkdown,
1970
+ packagePaths,
1971
+ strict,
1972
+ view
1973
+ };
1974
+ }
1975
+ async function createReport(packagePaths, {
1976
+ config,
1977
+ cwd,
1978
+ debugLog,
1979
+ dryRun
1980
+ }) {
1981
+ debugLog('Uploading:', packagePaths.join(`\n${_chalkMarkdown$1.logSymbols.info} Uploading: `));
1982
+ if (dryRun) {
1983
+ return;
1984
+ }
1985
+ const socketSdk = await (0, _sdk$f.setupSdk)();
1986
+ const spinner = (0, _ora$f.default)(`Creating report with ${packagePaths.length} package files`).start();
1987
+ const apiCall = socketSdk.createReportFromFilePaths(packagePaths, cwd, config?.issueRules);
1988
+ const result = await (0, _apiHelpers$f.handleApiCall)(apiCall, 'creating report');
1989
+ if (result.success === false) {
1990
+ return (0, _apiHelpers$f.handleUnsuccessfulApiResponse)('createReport', result, spinner);
1991
+ }
1992
+
1993
+ // Conclude the status of the API call
1994
+
1995
+ spinner.succeed();
1996
+ return result;
1997
+ }
1998
+ function formatReportCreationOutput(data, {
1999
+ outputJson,
2000
+ outputMarkdown
2001
+ }) {
2002
+ if (outputJson) {
2003
+ console.log(JSON.stringify(data, undefined, 2));
2004
+ return;
2005
+ }
2006
+ const format = new _chalkMarkdown$1.ChalkOrMarkdown(!!outputMarkdown);
2007
+ console.log('\nNew report: ' + format.hyperlink(data.id, data.url, {
2008
+ fallbackToUrl: true
2009
+ }));
2010
+ }
2011
+
2012
+ var meowWithSubcommands$1 = {};
2013
+
2014
+ var _interopRequireDefault$h = vendor.interopRequireDefault.default;
2015
+ Object.defineProperty(meowWithSubcommands$1, "__esModule", {
2016
+ value: true
2017
+ });
2018
+ meowWithSubcommands$1.meowWithSubcommands = meowWithSubcommands;
2019
+ var _meow$g = _interopRequireDefault$h(vendor.build);
2020
+ var _formatting$f = formatting;
2021
+ var _sorts = sorts;
2022
+ async function meowWithSubcommands(subcommands, options) {
2023
+ const {
2024
+ aliases = {},
2025
+ argv,
2026
+ name,
2027
+ importMeta,
2028
+ ...additionalOptions
2029
+ } = options;
2030
+ const [commandOrAliasName, ...rawCommandArgv] = argv;
2031
+
2032
+ // If we got at least some args, then lets find out if we can find a command
2033
+ if (commandOrAliasName) {
2034
+ const alias = aliases[commandOrAliasName];
2035
+
2036
+ // First: Resolve argv data from alias if its an alias that's been given
2037
+ const [commandName, ...commandArgv] = alias ? [...alias.argv, ...rawCommandArgv] : [commandOrAliasName, ...rawCommandArgv];
2038
+
2039
+ // Second: Find a command definition using that data
2040
+ const commandDefinition = commandName ? subcommands[commandName] : undefined;
2041
+
2042
+ // Third: If a valid command has been found, then we run it...
2043
+ if (commandDefinition) {
2044
+ return await commandDefinition.run(commandArgv, importMeta, {
2045
+ parentName: name
2046
+ });
2047
+ }
2048
+ }
2049
+
2050
+ // ...else we provide basic instructions and help
2051
+ const cli = (0, _meow$g.default)(`
2052
+ Usage
2053
+ $ ${name} <command>
2054
+
2055
+ Commands
2056
+ ${(0, _formatting$f.printHelpList)({
2057
+ ...(0, _sorts.toSortedObject)(subcommands),
2058
+ ...(0, _sorts.toSortedObject)(aliases)
2059
+ }, 6)}
2060
+
2061
+ Options
2062
+ ${(0, _formatting$f.printFlagList)({}, 6)}
2063
+
2064
+ Examples
2065
+ $ ${name} --help
2066
+ `, {
2067
+ argv,
2068
+ importMeta,
2069
+ ...additionalOptions
2070
+ });
2071
+ cli.showHelp();
2072
+ }
2073
+
2074
+ Object.defineProperty(report, "__esModule", {
2075
+ value: true
2076
+ });
2077
+ report.report = void 0;
2078
+ var _create$2 = create$5;
2079
+ var _view$1 = view$3;
2080
+ var _meowWithSubcommands$4 = meowWithSubcommands$1;
2081
+ const description$3 = '[Deprecated] Project report related commands';
2082
+ report.report = {
2083
+ description: description$3,
2084
+ async run(argv, importMeta, {
2085
+ parentName
2086
+ }) {
2087
+ await (0, _meowWithSubcommands$4.meowWithSubcommands)({
2088
+ create: _create$2.create,
2089
+ view: _view$1.view
2090
+ }, {
2091
+ argv,
2092
+ description: description$3,
2093
+ importMeta,
2094
+ name: parentName + ' report'
2095
+ });
2096
+ }
2097
+ };
2098
+
2099
+ var wrapper$1 = {};
2100
+
2101
+ var _interopRequireDefault$g = vendor.interopRequireDefault.default;
2102
+ Object.defineProperty(wrapper$1, "__esModule", {
2103
+ value: true
2104
+ });
2105
+ wrapper$1.wrapper = void 0;
2106
+ var _nodeFs$3 = require$$0;
2107
+ var _nodeOs = require$$2$1;
2108
+ var _nodeReadline = require$$3$4;
2109
+ var _meow$f = _interopRequireDefault$g(vendor.build);
2110
+ var _flags$d = flags$1;
2111
+ var _formatting$e = formatting;
2112
+ const BASH_FILE = `${_nodeOs.homedir()}/.bashrc`;
2113
+ const ZSH_BASH_FILE = `${_nodeOs.homedir()}/.zshrc`;
2114
+ const wrapper = wrapper$1.wrapper = {
2115
+ description: 'Enable or disable the Socket npm/npx wrapper',
2116
+ async run(argv, importMeta, {
2117
+ parentName
2118
+ }) {
2119
+ setupCommand$f(`${parentName} wrapper`, wrapper.description, argv, importMeta);
2120
+ }
2121
+ };
2122
+ function setupCommand$f(name, description, argv, importMeta) {
2123
+ const flags = _flags$d.commandFlags;
2124
+ const cli = (0, _meow$f.default)(`
2125
+ Usage
2126
+ $ ${name} <flag>
2127
+
2128
+ Options
2129
+ ${(0, _formatting$e.printFlagList)(flags, 6)}
2130
+
2131
+ Examples
2132
+ $ ${name} --enable
2133
+ $ ${name} --disable
2134
+ `, {
2135
+ argv,
2136
+ description,
2137
+ importMeta,
2138
+ flags
2139
+ });
2140
+ const {
2141
+ enable,
2142
+ disable
2143
+ } = cli.flags;
2144
+ if (argv[0] === '--postinstall') {
2145
+ const socketWrapperEnabled = _nodeFs$3.existsSync(BASH_FILE) && checkSocketWrapperAlreadySetup(BASH_FILE) || _nodeFs$3.existsSync(ZSH_BASH_FILE) && checkSocketWrapperAlreadySetup(ZSH_BASH_FILE);
2146
+ if (!socketWrapperEnabled) {
2147
+ installSafeNpm(`The Socket CLI is now successfully installed! 🎉
2148
+
2149
+ To better protect yourself against supply-chain attacks, our "safe npm" wrapper can warn you about malicious packages whenever you run 'npm install'.
2150
+
2151
+ Do you want to install "safe npm" (this will create an alias to the socket-npm command)? (y/n)`);
2152
+ }
2153
+ return;
2154
+ }
2155
+ if (!enable && !disable) {
2156
+ cli.showHelp();
2157
+ return;
2158
+ }
2159
+ if (enable) {
2160
+ if (_nodeFs$3.existsSync(BASH_FILE)) {
2161
+ const socketWrapperEnabled = checkSocketWrapperAlreadySetup(BASH_FILE);
2162
+ !socketWrapperEnabled && addAlias(BASH_FILE);
2163
+ }
2164
+ if (_nodeFs$3.existsSync(ZSH_BASH_FILE)) {
2165
+ const socketWrapperEnabled = checkSocketWrapperAlreadySetup(ZSH_BASH_FILE);
2166
+ !socketWrapperEnabled && addAlias(ZSH_BASH_FILE);
2167
+ }
2168
+ } else if (disable) {
2169
+ if (_nodeFs$3.existsSync(BASH_FILE)) {
2170
+ removeAlias(BASH_FILE);
2171
+ }
2172
+ if (_nodeFs$3.existsSync(ZSH_BASH_FILE)) {
2173
+ removeAlias(ZSH_BASH_FILE);
2174
+ }
2175
+ }
2176
+ if (!_nodeFs$3.existsSync(BASH_FILE) && !_nodeFs$3.existsSync(ZSH_BASH_FILE)) {
2177
+ console.error('There was an issue setting up the alias in your bash profile');
2178
+ }
2179
+ return;
2180
+ }
2181
+ const installSafeNpm = query => {
2182
+ console.log(`
2183
+ _____ _ _
2184
+ | __|___ ___| |_ ___| |_
2185
+ |__ | . | _| '_| -_| _|
2186
+ |_____|___|___|_,_|___|_|
2187
+
2188
+ `);
2189
+ const rl = _nodeReadline.createInterface({
2190
+ input: process.stdin,
2191
+ output: process.stdout
2192
+ });
2193
+ return askQuestion(rl, query);
2194
+ };
2195
+ const askQuestion = (rl, query) => {
2196
+ rl.question(query, ans => {
2197
+ if (ans.toLowerCase() === 'y') {
2198
+ try {
2199
+ if (_nodeFs$3.existsSync(BASH_FILE)) {
2200
+ addAlias(BASH_FILE);
2201
+ }
2202
+ if (_nodeFs$3.existsSync(ZSH_BASH_FILE)) {
2203
+ addAlias(ZSH_BASH_FILE);
2204
+ }
2205
+ } catch (e) {
2206
+ throw new Error(`There was an issue setting up the alias: ${e}`);
2207
+ }
2208
+ rl.close();
2209
+ } else if (ans.toLowerCase() !== 'n') {
2210
+ askQuestion(rl, 'Incorrect input: please enter either y (yes) or n (no): ');
2211
+ } else {
2212
+ rl.close();
2213
+ }
2214
+ });
2215
+ };
2216
+ const addAlias = file => {
2217
+ return _nodeFs$3.appendFile(file, 'alias npm="socket npm"\nalias npx="socket npx"\n', err => {
2218
+ if (err) {
2219
+ return new Error(`There was an error setting up the alias: ${err}`);
2220
+ }
2221
+ console.log(`
2222
+ The alias was added to ${file}. Running 'npm install' will now be wrapped in Socket's "safe npm" 🎉
2223
+ If you want to disable it at any time, run \`socket wrapper --disable\`
2224
+ `);
2225
+ });
2226
+ };
2227
+ const removeAlias = file => {
2228
+ return _nodeFs$3.readFile(file, 'utf8', function (err, data) {
2229
+ if (err) {
2230
+ console.error(`There was an error removing the alias: ${err}`);
2231
+ return;
2232
+ }
2233
+ const linesWithoutSocketAlias = data.split('\n').filter(l => l !== 'alias npm="socket npm"' && l !== 'alias npx="socket npx"');
2234
+ const updatedFileContent = linesWithoutSocketAlias.join('\n');
2235
+ _nodeFs$3.writeFile(file, updatedFileContent, function (err) {
2236
+ if (err) {
2237
+ console.log(err);
2238
+ return;
2239
+ } else {
2240
+ console.log(`\nThe alias was removed from ${file}. Running 'npm install' will now run the standard npm command.\n`);
2241
+ }
2242
+ });
2243
+ });
2244
+ };
2245
+ const checkSocketWrapperAlreadySetup = file => {
2246
+ const fileContent = _nodeFs$3.readFileSync(file, 'utf-8');
2247
+ const linesWithSocketAlias = fileContent.split('\n').filter(l => l === 'alias npm="socket npm"' || l === 'alias npx="socket npx"');
2248
+ if (linesWithSocketAlias.length) {
2249
+ console.log(`The Socket npm/npx wrapper is set up in your bash profile (${file}).`);
2250
+ return true;
2251
+ }
2252
+ return false;
2253
+ };
2254
+
2255
+ var scan = {};
2256
+
2257
+ var create$3 = {};
2258
+
2259
+ var _interopRequireDefault$f = vendor.interopRequireDefault.default;
2260
+ Object.defineProperty(create$3, "__esModule", {
2261
+ value: true
2262
+ });
2263
+ create$3.create = void 0;
2264
+ var _nodeProcess = require$$0$1;
2265
+ var _promises = require$$2$2;
2266
+ var _chalk$e = _interopRequireDefault$f(vendor.source);
2267
+ var _meow$e = _interopRequireDefault$f(vendor.build);
2268
+ var _open = _interopRequireDefault$f(vendor.open);
2269
+ var _ora$e = _interopRequireDefault$f(vendor.ora);
2270
+ var _ponyCause$1 = require$$6;
2271
+ var _apiHelpers$e = apiHelpers;
2272
+ var _errors$f = sdk.errors;
2273
+ var _formatting$d = formatting;
2274
+ var _misc = sdk.misc;
2275
+ var _pathResolve = pathResolve.pathResolve;
2276
+ var _sdk$e = sdk.sdk;
2277
+ const create$2 = create$3.create = {
2278
+ description: 'Create a scan',
2279
+ async run(argv, importMeta, {
2280
+ parentName
2281
+ }) {
2282
+ const name = `${parentName} create`;
2283
+ const input = await setupCommand$e(name, create$2.description, argv, importMeta);
2284
+ if (input) {
2285
+ const apiKey = (0, _sdk$e.getDefaultKey)();
2286
+ if (!apiKey) {
2287
+ 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.');
2288
+ }
2289
+ const spinnerText = 'Creating a scan... \n';
2290
+ const spinner = (0, _ora$e.default)(spinnerText).start();
2291
+ await createFullScan(input, spinner, apiKey);
2292
+ }
2293
+ }
2294
+ };
2295
+ const createFullScanFlags = {
2296
+ repo: {
2297
+ type: 'string',
2298
+ shortFlag: 'r',
2299
+ default: '',
2300
+ description: 'Repository name'
2301
+ },
2302
+ branch: {
2303
+ type: 'string',
2304
+ shortFlag: 'b',
2305
+ default: '',
2306
+ description: 'Branch name'
2307
+ },
2308
+ commitMessage: {
2309
+ type: 'string',
2310
+ shortFlag: 'm',
2311
+ default: '',
2312
+ description: 'Commit message'
2313
+ },
2314
+ commitHash: {
2315
+ type: 'string',
2316
+ shortFlag: 'ch',
2317
+ default: '',
2318
+ description: 'Commit hash'
2319
+ },
2320
+ pullRequest: {
2321
+ type: 'number',
2322
+ shortFlag: 'pr',
2323
+ description: 'Commit hash'
2324
+ },
2325
+ committers: {
2326
+ type: 'string',
2327
+ shortFlag: 'c',
2328
+ default: '',
2329
+ description: 'Committers'
2330
+ },
2331
+ defaultBranch: {
2332
+ type: 'boolean',
2333
+ shortFlag: 'db',
2334
+ default: false,
2335
+ description: 'Make default branch'
2336
+ },
2337
+ pendingHead: {
2338
+ type: 'boolean',
2339
+ shortFlag: 'ph',
2340
+ default: false,
2341
+ description: 'Set as pending head'
2342
+ },
2343
+ tmp: {
2344
+ type: 'boolean',
2345
+ shortFlag: 't',
2346
+ default: false,
2347
+ description: 'Set the visibility (true/false) of the scan in your dashboard'
2348
+ }
2349
+ };
2350
+
2351
+ // Internal functions
2352
+
2353
+ async function setupCommand$e(name, description, argv, importMeta) {
2354
+ const flags = {
2355
+ ...createFullScanFlags
2356
+ };
2357
+ const cli = (0, _meow$e.default)(`
2358
+ Usage
2359
+ $ ${name} [...options]
2360
+
2361
+ Options
2362
+ ${(0, _formatting$d.printFlagList)(flags, 6)}
2363
+
2364
+ Examples
2365
+ $ ${name} --org=FakeOrg --repo=test-repo --branch=main ./package.json
2366
+ `, {
2367
+ argv,
2368
+ description,
2369
+ importMeta,
2370
+ flags
2371
+ });
2372
+ const {
2373
+ repo: repoName,
2374
+ branch: branchName,
2375
+ commitMessage,
2376
+ defaultBranch,
2377
+ pendingHead,
2378
+ tmp,
2379
+ committers,
2380
+ commitHash,
2381
+ pullRequest
2382
+ } = cli.flags;
2383
+ if (!cli.input[0]) {
2384
+ cli.showHelp();
2385
+ return;
2386
+ }
2387
+ const {
2388
+ 0: orgSlug = ''
2389
+ } = cli.input;
2390
+ const cwd = process.cwd();
2391
+ const socketSdk = await (0, _sdk$e.setupSdk)();
2392
+ const supportedFiles = await socketSdk.getReportSupportedFiles().then(res => {
2393
+ if (!res.success) (0, _apiHelpers$e.handleUnsuccessfulApiResponse)('getReportSupportedFiles', res, (0, _ora$e.default)());
2394
+ return res.data;
2395
+ }).catch(/** @type {(cause: Error) => never} */
2396
+ cause => {
2397
+ throw new _ponyCause$1.ErrorWithCause('Failed getting supported files for report', {
2398
+ cause
2399
+ });
2400
+ });
2401
+ const debugLog = (0, _misc.createDebugLogger)(false);
2402
+ const packagePaths = await (0, _pathResolve.getPackageFilesFullScans)(cwd, cli.input, supportedFiles, debugLog);
2403
+ if (!repoName || !branchName || !packagePaths.length) {
2404
+ console.error(`${_chalk$e.default.white.bgRed('Input error')}: Please provide the required fields:\n
2405
+ - Repository name using --repo,\n
2406
+ - Branch name using --branch\n
2407
+ - At least one file path (e.g. ./package.json).\n`);
2408
+ cli.showHelp();
2409
+ return;
2410
+ }
2411
+ return {
2412
+ orgSlug,
2413
+ repoName,
2414
+ branchName,
2415
+ commitMessage,
2416
+ defaultBranch,
2417
+ pendingHead,
2418
+ tmp,
2419
+ packagePaths,
2420
+ commitHash,
2421
+ committers,
2422
+ pullRequest
2423
+ };
2424
+ }
2425
+ async function createFullScan(input, spinner, apiKey) {
2426
+ const socketSdk = await (0, _sdk$e.setupSdk)(apiKey);
2427
+ const {
2428
+ orgSlug,
2429
+ repoName,
2430
+ branchName,
2431
+ commitMessage,
2432
+ defaultBranch,
2433
+ pendingHead,
2434
+ tmp,
2435
+ packagePaths
2436
+ } = input;
2437
+ const result = await (0, _apiHelpers$e.handleApiCall)(socketSdk.createOrgFullScan(orgSlug, {
2438
+ repo: repoName,
2439
+ branch: branchName,
2440
+ commit_message: commitMessage,
2441
+ make_default_branch: defaultBranch,
2442
+ set_as_pending_head: pendingHead,
2443
+ tmp
2444
+ }, packagePaths), 'Creating scan');
2445
+ if (!result.success) {
2446
+ (0, _apiHelpers$e.handleUnsuccessfulApiResponse)('CreateOrgFullScan', result, spinner);
2447
+ return;
2448
+ }
2449
+ spinner.stop();
2450
+ console.log('\n✅ Scan created successfully\n');
2451
+ const link = _chalk$e.default.hex('#00FFFF').underline(`${result.data.html_report_url}`);
2452
+ console.log(`Available at: ${link}\n`);
2453
+ const rl = _promises.createInterface({
2454
+ input: _nodeProcess.stdin,
2455
+ output: _nodeProcess.stdout
2456
+ });
2457
+ const answer = await rl.question('Would you like to open it in your browser? (y/n)');
2458
+ if (answer.toLowerCase() === 'y') {
2459
+ await (0, _open.default)(`${result.data.html_report_url}`);
2460
+ }
2461
+ rl.close();
2462
+ }
2463
+
2464
+ var _delete$3 = {};
2465
+
2466
+ var _interopRequireDefault$e = vendor.interopRequireDefault.default;
2467
+ Object.defineProperty(_delete$3, "__esModule", {
2468
+ value: true
2469
+ });
2470
+ _delete$3.del = void 0;
2471
+ var _chalk$d = _interopRequireDefault$e(vendor.source);
2472
+ var _meow$d = _interopRequireDefault$e(vendor.build);
2473
+ var _ora$d = _interopRequireDefault$e(vendor.ora);
2474
+ var _flags$c = flags$1;
2475
+ var _apiHelpers$d = apiHelpers;
2476
+ var _errors$e = sdk.errors;
2477
+ var _formatting$c = formatting;
2478
+ var _sdk$d = sdk.sdk;
2479
+ const del$1 = _delete$3.del = {
2480
+ description: 'Delete a scan',
2481
+ async run(argv, importMeta, {
2482
+ parentName
2483
+ }) {
2484
+ const name = `${parentName} del`;
2485
+ const input = setupCommand$d(name, del$1.description, argv, importMeta);
2486
+ if (input) {
2487
+ const apiKey = (0, _sdk$d.getDefaultKey)();
2488
+ if (!apiKey) {
2489
+ 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.');
2490
+ }
2491
+ const spinnerText = 'Deleting scan...';
2492
+ const spinner = (0, _ora$d.default)(spinnerText).start();
2493
+ await deleteOrgFullScan(input.orgSlug, input.fullScanId, spinner, apiKey);
2494
+ }
2495
+ }
2496
+ };
2497
+
2498
+ // Internal functions
2499
+
2500
+ function setupCommand$d(name, description, argv, importMeta) {
2501
+ const flags = {
2502
+ ..._flags$c.outputFlags
2503
+ };
2504
+ const cli = (0, _meow$d.default)(`
2505
+ Usage
2506
+ $ ${name} <org slug> <scan ID>
2507
+
2508
+ Options
2509
+ ${(0, _formatting$c.printFlagList)(flags, 6)}
2510
+
2511
+ Examples
2512
+ $ ${name} FakeOrg 000aaaa1-0000-0a0a-00a0-00a0000000a0
2513
+ `, {
2514
+ argv,
2515
+ description,
2516
+ importMeta,
2517
+ flags
2518
+ });
2519
+ const {
2520
+ json: outputJson,
2521
+ markdown: outputMarkdown
2522
+ } = cli.flags;
2523
+ if (cli.input.length < 2) {
2524
+ console.error(`${_chalk$d.default.white.bgRed('Input error')}: Please specify an organization slug and a scan ID.\n`);
2525
+ cli.showHelp();
2526
+ return;
2527
+ }
2528
+ const {
2529
+ 0: orgSlug = '',
2530
+ 1: fullScanId = ''
2531
+ } = cli.input;
2532
+ return {
2533
+ outputJson,
2534
+ outputMarkdown,
2535
+ orgSlug,
2536
+ fullScanId
2537
+ };
2538
+ }
2539
+ async function deleteOrgFullScan(orgSlug, fullScanId, spinner, apiKey) {
2540
+ const socketSdk = await (0, _sdk$d.setupSdk)(apiKey);
2541
+ const result = await (0, _apiHelpers$d.handleApiCall)(socketSdk.deleteOrgFullScan(orgSlug, fullScanId), 'Deleting scan');
2542
+ if (!result.success) {
2543
+ (0, _apiHelpers$d.handleUnsuccessfulApiResponse)('deleteOrgFullScan', result, spinner);
2544
+ return;
2545
+ }
2546
+ spinner.stop();
2547
+ console.log('\n ✅ Scan deleted successfully\n');
2548
+ }
2549
+
2550
+ var list$3 = {};
2551
+
2552
+ var _interopRequireDefault$d = vendor.interopRequireDefault.default;
2553
+ Object.defineProperty(list$3, "__esModule", {
2554
+ value: true
2555
+ });
2556
+ list$3.list = void 0;
2557
+ var _chalk$c = _interopRequireDefault$d(vendor.source);
2558
+ var _chalkTable$3 = require$$2$3;
2559
+ var _meow$c = _interopRequireDefault$d(vendor.build);
2560
+ var _ora$c = _interopRequireDefault$d(vendor.ora);
2561
+ var _flags$b = flags$1;
2562
+ var _apiHelpers$c = apiHelpers;
2563
+ var _errors$d = sdk.errors;
2564
+ var _formatting$b = formatting;
2565
+ var _sdk$c = sdk.sdk;
2566
+ // @ts-ignore
2567
+
2568
+ const list$2 = list$3.list = {
2569
+ description: 'List scans for an organization',
2570
+ async run(argv, importMeta, {
2571
+ parentName
2572
+ }) {
2573
+ const name = `${parentName} list`;
2574
+ const input = setupCommand$c(name, list$2.description, argv, importMeta);
2575
+ if (input) {
2576
+ const apiKey = (0, _sdk$c.getDefaultKey)();
2577
+ if (!apiKey) {
2578
+ 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.');
2579
+ }
2580
+ const spinnerText = 'Listing scans... \n';
2581
+ const spinner = (0, _ora$c.default)(spinnerText).start();
2582
+ await listOrgFullScan(input.orgSlug, input, spinner, apiKey);
2583
+ }
2584
+ }
2585
+ };
2586
+ const listFullScanFlags = {
2587
+ sort: {
2588
+ type: 'string',
2589
+ shortFlag: 's',
2590
+ default: 'created_at',
2591
+ description: 'Sorting option (`name` or `created_at`) - default is `created_at`'
2592
+ },
2593
+ direction: {
2594
+ type: 'string',
2595
+ shortFlag: 'd',
2596
+ default: 'desc',
2597
+ description: 'Direction option (`desc` or `asc`) - Default is `desc`'
2598
+ },
2599
+ perPage: {
2600
+ type: 'number',
2601
+ shortFlag: 'pp',
2602
+ default: 30,
2603
+ description: 'Results per page - Default is 30'
2604
+ },
2605
+ page: {
2606
+ type: 'number',
2607
+ shortFlag: 'p',
2608
+ default: 1,
2609
+ description: 'Page number - Default is 1'
2610
+ },
2611
+ fromTime: {
2612
+ type: 'string',
2613
+ shortFlag: 'f',
2614
+ default: '',
2615
+ description: 'From time - as a unix timestamp'
2616
+ },
2617
+ untilTime: {
2618
+ type: 'string',
2619
+ shortFlag: 'u',
2620
+ default: '',
2621
+ description: 'Until time - as a unix timestamp'
2622
+ }
2623
+ };
2624
+
2625
+ // Internal functions
2626
+
2627
+ function setupCommand$c(name, description, argv, importMeta) {
2628
+ const flags = {
2629
+ ..._flags$b.outputFlags,
2630
+ ...listFullScanFlags
2631
+ };
2632
+ const cli = (0, _meow$c.default)(`
2633
+ Usage
2634
+ $ ${name} <org slug>
2635
+
2636
+ Options
2637
+ ${(0, _formatting$b.printFlagList)(flags, 6)}
2638
+
2639
+ Examples
2640
+ $ ${name} FakeOrg
2641
+ `, {
2642
+ argv,
2643
+ description,
2644
+ importMeta,
2645
+ flags
2646
+ });
2647
+ const {
2648
+ json: outputJson,
2649
+ markdown: outputMarkdown,
2650
+ sort,
2651
+ direction,
2652
+ perPage,
2653
+ page,
2654
+ fromTime,
2655
+ untilTime
2656
+ } = cli.flags;
2657
+ if (!cli.input[0]) {
2658
+ console.error(`${_chalk$c.default.white.bgRed('Input error')}: Please specify an organization slug.\n`);
2659
+ cli.showHelp();
2660
+ return;
2661
+ }
2662
+ const {
2663
+ 0: orgSlug = ''
2664
+ } = cli.input;
2665
+ return {
2666
+ outputJson,
2667
+ outputMarkdown,
2668
+ orgSlug,
2669
+ sort,
2670
+ direction,
2671
+ per_page: perPage,
2672
+ page,
2673
+ from_time: fromTime,
2674
+ until_time: untilTime
2675
+ };
2676
+ }
2677
+ async function listOrgFullScan(orgSlug, input, spinner, apiKey) {
2678
+ const socketSdk = await (0, _sdk$c.setupSdk)(apiKey);
2679
+ const result = await (0, _apiHelpers$c.handleApiCall)(socketSdk.getOrgFullScanList(orgSlug, input), 'Listing scans');
2680
+ if (!result.success) {
2681
+ (0, _apiHelpers$c.handleUnsuccessfulApiResponse)('getOrgFullScanList', result, spinner);
2682
+ return;
2683
+ }
2684
+ spinner.stop();
2685
+ console.log(`\n Listing scans for: ${orgSlug}\n`);
2686
+ const options = {
2687
+ columns: [{
2688
+ field: 'id',
2689
+ name: _chalk$c.default.magenta('ID')
2690
+ }, {
2691
+ field: 'report_url',
2692
+ name: _chalk$c.default.magenta('Scan URL')
2693
+ }, {
2694
+ field: 'branch',
2695
+ name: _chalk$c.default.magenta('Branch')
2696
+ }, {
2697
+ field: 'created_at',
2698
+ name: _chalk$c.default.magenta('Created at')
2699
+ }]
2700
+ };
2701
+ const formattedResults = result.data.results.map(d => {
2702
+ return {
2703
+ id: d.id,
2704
+ report_url: _chalk$c.default.underline(`${d.html_report_url}`),
2705
+ created_at: d.created_at ? new Date(d.created_at).toLocaleDateString('en-us', {
2706
+ year: 'numeric',
2707
+ month: 'numeric',
2708
+ day: 'numeric'
2709
+ }) : '',
2710
+ branch: d.branch
2711
+ };
2712
+ });
2713
+ console.log(`${_chalkTable$3(options, formattedResults)}\n`);
2714
+ }
2715
+
2716
+ var metadata$1 = {};
2717
+
2718
+ var _interopRequireDefault$c = vendor.interopRequireDefault.default;
2719
+ Object.defineProperty(metadata$1, "__esModule", {
2720
+ value: true
2721
+ });
2722
+ metadata$1.metadata = void 0;
2723
+ var _chalk$b = _interopRequireDefault$c(vendor.source);
2724
+ var _meow$b = _interopRequireDefault$c(vendor.build);
2725
+ var _ora$b = _interopRequireDefault$c(vendor.ora);
2726
+ var _flags$a = flags$1;
2727
+ var _apiHelpers$b = apiHelpers;
2728
+ var _errors$c = sdk.errors;
2729
+ var _formatting$a = formatting;
2730
+ var _sdk$b = sdk.sdk;
2731
+ const metadata = metadata$1.metadata = {
2732
+ description: "Get a scan's metadata",
2733
+ async run(argv, importMeta, {
2734
+ parentName
2735
+ }) {
2736
+ const name = `${parentName} metadata`;
2737
+ const input = setupCommand$b(name, metadata.description, argv, importMeta);
2738
+ if (input) {
2739
+ const apiKey = (0, _sdk$b.getDefaultKey)();
2740
+ if (!apiKey) {
2741
+ 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.');
2742
+ }
2743
+ const spinnerText = "Getting scan's metadata... \n";
2744
+ const spinner = (0, _ora$b.default)(spinnerText).start();
2745
+ await getOrgScanMetadata(input.orgSlug, input.scanID, spinner, apiKey);
2746
+ }
2747
+ }
2748
+ };
2749
+
2750
+ // Internal functions
2751
+
2752
+ function setupCommand$b(name, description, argv, importMeta) {
2753
+ const flags = {
2754
+ ..._flags$a.outputFlags
2755
+ };
2756
+ const cli = (0, _meow$b.default)(`
2757
+ Usage
2758
+ $ ${name} <org slug> <scan id>
2759
+
2760
+ Options
2761
+ ${(0, _formatting$a.printFlagList)(flags, 6)}
2762
+
2763
+ Examples
2764
+ $ ${name} FakeOrg 000aaaa1-0000-0a0a-00a0-00a0000000a0
2765
+ `, {
2766
+ argv,
2767
+ description,
2768
+ importMeta,
2769
+ flags
2770
+ });
2771
+ const {
2772
+ json: outputJson,
2773
+ markdown: outputMarkdown
2774
+ } = cli.flags;
2775
+ if (cli.input.length < 2) {
2776
+ console.error(`${_chalk$b.default.white.bgRed('Input error')}: Please specify an organization slug and a scan ID.\n`);
2777
+ cli.showHelp();
2778
+ return;
2779
+ }
2780
+ const {
2781
+ 0: orgSlug = '',
2782
+ 1: scanID = ''
2783
+ } = cli.input;
2784
+ return {
2785
+ outputJson,
2786
+ outputMarkdown,
2787
+ orgSlug,
2788
+ scanID
2789
+ };
2790
+ }
2791
+ async function getOrgScanMetadata(orgSlug, scanId, spinner, apiKey) {
2792
+ const socketSdk = await (0, _sdk$b.setupSdk)(apiKey);
2793
+ const result = await (0, _apiHelpers$b.handleApiCall)(socketSdk.getOrgFullScanMetadata(orgSlug, scanId), 'Listing scans');
2794
+ if (!result.success) {
2795
+ (0, _apiHelpers$b.handleUnsuccessfulApiResponse)('getOrgFullScanMetadata', result, spinner);
2796
+ return;
2797
+ }
2798
+ spinner.stop();
2799
+ console.log('\nScan metadata:\n');
2800
+ console.log(result.data);
2801
+ }
2802
+
2803
+ var stream$1 = {};
2804
+
2805
+ var _interopRequireDefault$b = vendor.interopRequireDefault.default;
2806
+ Object.defineProperty(stream$1, "__esModule", {
2807
+ value: true
2808
+ });
2809
+ stream$1.stream = void 0;
2810
+ var _chalk$a = _interopRequireDefault$b(vendor.source);
2811
+ var _meow$a = _interopRequireDefault$b(vendor.build);
2812
+ var _ora$a = _interopRequireDefault$b(vendor.ora);
2813
+ var _flags$9 = flags$1;
2814
+ var _apiHelpers$a = apiHelpers;
2815
+ var _errors$b = sdk.errors;
2816
+ var _formatting$9 = formatting;
2817
+ var _sdk$a = sdk.sdk;
2818
+ const stream = stream$1.stream = {
2819
+ description: 'Stream the output of a scan',
2820
+ async run(argv, importMeta, {
2821
+ parentName
2822
+ }) {
2823
+ const name = `${parentName} stream`;
2824
+ const input = setupCommand$a(name, stream.description, argv, importMeta);
2825
+ if (input) {
2826
+ const apiKey = (0, _sdk$a.getDefaultKey)();
2827
+ if (!apiKey) {
2828
+ 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.');
2829
+ }
2830
+ const spinnerText = 'Streaming scan...\n';
2831
+ const spinner = (0, _ora$a.default)(spinnerText).start();
2832
+ await getOrgFullScan(input.orgSlug, input.fullScanId, input.file, spinner, apiKey);
2833
+ }
2834
+ }
2835
+ };
2836
+
2837
+ // Internal functions
2838
+
2839
+ function setupCommand$a(name, description, argv, importMeta) {
2840
+ const flags = {
2841
+ ..._flags$9.outputFlags
2842
+ };
2843
+ const cli = (0, _meow$a.default)(`
2844
+ Usage
2845
+ $ ${name} <org slug> <scan ID> <path to output file>
2846
+
2847
+ Options
2848
+ ${(0, _formatting$9.printFlagList)(flags, 6)}
2849
+
2850
+ Examples
2851
+ $ ${name} FakeOrg 000aaaa1-0000-0a0a-00a0-00a0000000a0 ./stream.txt
2852
+ `, {
2853
+ argv,
2854
+ description,
2855
+ importMeta,
2856
+ flags
2857
+ });
2858
+ const {
2859
+ json: outputJson,
2860
+ markdown: outputMarkdown
2861
+ } = cli.flags;
2862
+ if (cli.input.length < 2) {
2863
+ console.error(`${_chalk$a.default.white.bgRed('Input error')}: Please specify an organization slug and a scan ID.\n`);
2864
+ cli.showHelp();
2865
+ return;
2866
+ }
2867
+ const {
2868
+ 0: orgSlug = '',
2869
+ 1: fullScanId = '',
2870
+ 2: file
2871
+ } = cli.input;
2872
+ return {
2873
+ outputJson,
2874
+ outputMarkdown,
2875
+ orgSlug,
2876
+ fullScanId,
2877
+ file
2878
+ };
2879
+ }
2880
+ async function getOrgFullScan(orgSlug, fullScanId, file, spinner, apiKey) {
2881
+ const socketSdk = await (0, _sdk$a.setupSdk)(apiKey);
2882
+ const result = await (0, _apiHelpers$a.handleApiCall)(socketSdk.getOrgFullScan(orgSlug, fullScanId, file), 'Streaming a scan');
2883
+ if (!result?.success) {
2884
+ (0, _apiHelpers$a.handleUnsuccessfulApiResponse)('getOrgFullScan', result, spinner);
2885
+ return;
2886
+ }
2887
+ spinner.stop();
2888
+ console.log(file ? `\nFull scan details written to ${file}\n` : '\nFull scan details:\n');
2889
+ }
2890
+
2891
+ Object.defineProperty(scan, "__esModule", {
2892
+ value: true
2893
+ });
2894
+ scan.scan = void 0;
2895
+ var _create$1 = create$3;
2896
+ var _delete$2 = _delete$3;
2897
+ var _list$1 = list$3;
2898
+ var _metadata = metadata$1;
2899
+ var _stream = stream$1;
2900
+ var _meowWithSubcommands$3 = meowWithSubcommands$1;
2901
+ const description$2 = 'Scans related commands';
2902
+ scan.scan = {
2903
+ description: description$2,
2904
+ async run(argv, importMeta, {
2905
+ parentName
2906
+ }) {
2907
+ await (0, _meowWithSubcommands$3.meowWithSubcommands)({
2908
+ create: _create$1.create,
2909
+ stream: _stream.stream,
2910
+ list: _list$1.list,
2911
+ del: _delete$2.del,
2912
+ metadata: _metadata.metadata
2913
+ }, {
2914
+ argv,
2915
+ description: description$2,
2916
+ importMeta,
2917
+ name: parentName + ' scan'
2918
+ });
2919
+ }
2920
+ };
2921
+
2922
+ var auditLog$1 = {};
2923
+
2924
+ var _interopRequireDefault$a = vendor.interopRequireDefault.default;
2925
+ Object.defineProperty(auditLog$1, "__esModule", {
2926
+ value: true
2927
+ });
2928
+ auditLog$1.auditLog = void 0;
2929
+ var _prompts = require$$1$2;
2930
+ var _chalk$9 = _interopRequireDefault$a(vendor.source);
2931
+ var _meow$9 = _interopRequireDefault$a(vendor.build);
2932
+ var _ora$9 = _interopRequireDefault$a(vendor.ora);
2933
+ var _flags$8 = flags$1;
2934
+ var _apiHelpers$9 = apiHelpers;
2935
+ var _errors$a = sdk.errors;
2936
+ var _formatting$8 = formatting;
2937
+ var _sdk$9 = sdk.sdk;
2938
+ const auditLog = auditLog$1.auditLog = {
2939
+ description: 'Look up the audit log for an organization',
2940
+ async run(argv, importMeta, {
2941
+ parentName
2942
+ }) {
2943
+ const name = parentName + ' audit-log';
2944
+ const input = setupCommand$9(name, auditLog.description, argv, importMeta);
2945
+ if (input) {
2946
+ const apiKey = (0, _sdk$9.getDefaultKey)();
2947
+ if (!apiKey) {
2948
+ 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.');
2949
+ }
2950
+ const spinner = (0, _ora$9.default)(`Looking up audit log for ${input.orgSlug}\n`).start();
2951
+ await fetchOrgAuditLog(input.orgSlug, input, spinner, apiKey);
2952
+ }
2953
+ }
2954
+ };
2955
+ const auditLogFlags = {
2956
+ type: {
2957
+ type: 'string',
2958
+ shortFlag: 't',
2959
+ default: '',
2960
+ description: 'Type of log event'
2961
+ },
2962
+ perPage: {
2963
+ type: 'number',
2964
+ shortFlag: 'pp',
2965
+ default: 30,
2966
+ description: 'Results per page - default is 30'
2967
+ },
2968
+ page: {
2969
+ type: 'number',
2970
+ shortFlag: 'p',
2971
+ default: 1,
2972
+ description: 'Page number - default is 1'
2973
+ }
2974
+ };
2975
+
2976
+ // Internal functions
2977
+
2978
+ function setupCommand$9(name, description, argv, importMeta) {
2979
+ const flags = {
2980
+ __proto__: null,
2981
+ ...auditLogFlags,
2982
+ ..._flags$8.outputFlags
2983
+ };
2984
+ const cli = (0, _meow$9.default)(`
2985
+ Usage
2986
+ $ ${name} <org slug>
2987
+
2988
+ Options
2989
+ ${(0, _formatting$8.printFlagList)(flags, 6)}
2990
+
2991
+ Examples
2992
+ $ ${name} FakeOrg
2993
+ `, {
2994
+ argv,
2995
+ description,
2996
+ importMeta,
2997
+ flags
2998
+ });
2999
+ const {
3000
+ json: outputJson,
3001
+ markdown: outputMarkdown,
3002
+ page,
3003
+ perPage
3004
+ } = cli.flags;
3005
+ const type = cli.flags['type'];
3006
+ if (cli.input.length < 1) {
3007
+ console.error(`${_chalk$9.default.white.bgRed('Input error')}: Please provide an organization slug\n`);
3008
+ cli.showHelp();
3009
+ return;
3010
+ }
3011
+ const {
3012
+ 0: orgSlug = ''
3013
+ } = cli.input;
3014
+ return {
3015
+ outputJson,
3016
+ outputMarkdown,
3017
+ orgSlug,
3018
+ type: type && type.charAt(0).toUpperCase() + type.slice(1),
3019
+ page,
3020
+ per_page: perPage
3021
+ };
3022
+ }
3023
+ async function fetchOrgAuditLog(orgSlug, input, spinner, apiKey) {
3024
+ const socketSdk = await (0, _sdk$9.setupSdk)(apiKey);
3025
+ const result = await (0, _apiHelpers$9.handleApiCall)(socketSdk.getAuditLogEvents(orgSlug, input), `Looking up audit log for ${orgSlug}\n`);
3026
+ if (!result.success) {
3027
+ (0, _apiHelpers$9.handleUnsuccessfulApiResponse)('getAuditLogEvents', result, spinner);
3028
+ return;
3029
+ }
3030
+ spinner.stop();
3031
+ const data = [];
3032
+ const logDetails = {};
3033
+ for (const d of result.data.results) {
3034
+ const {
3035
+ created_at
3036
+ } = d;
3037
+ if (created_at) {
3038
+ const name = `${new Date(created_at).toLocaleDateString('en-us', {
3039
+ year: 'numeric',
3040
+ month: 'numeric',
3041
+ day: 'numeric'
3042
+ })} - ${d.user_email} - ${d.type} - ${d.ip_address} - ${d.user_agent}`;
3043
+ data.push({
3044
+ name
3045
+ }, new _prompts.Separator());
3046
+ logDetails[name] = JSON.stringify(d.payload);
3047
+ }
3048
+ }
3049
+ console.log(logDetails[await (0, _prompts.select)({
3050
+ message: input.type ? `\n Audit log for: ${orgSlug} with type: ${input.type}\n` : `\n Audit log for: ${orgSlug}\n`,
3051
+ choices: data,
3052
+ pageSize: 30
3053
+ })]);
3054
+ }
3055
+
3056
+ var repos = {};
3057
+
3058
+ var create$1 = {};
3059
+
3060
+ var _interopRequireDefault$9 = vendor.interopRequireDefault.default;
3061
+ Object.defineProperty(create$1, "__esModule", {
3062
+ value: true
3063
+ });
3064
+ create$1.create = void 0;
3065
+ var _chalk$8 = _interopRequireDefault$9(vendor.source);
3066
+ var _meow$8 = _interopRequireDefault$9(vendor.build);
3067
+ var _ora$8 = _interopRequireDefault$9(vendor.ora);
3068
+ var _flags$7 = flags$1;
3069
+ var _apiHelpers$8 = apiHelpers;
3070
+ var _errors$9 = sdk.errors;
3071
+ var _formatting$7 = formatting;
3072
+ var _sdk$8 = sdk.sdk;
3073
+ const create = create$1.create = {
3074
+ description: 'Create a repository in an organization',
3075
+ async run(argv, importMeta, {
3076
+ parentName
3077
+ }) {
3078
+ const name = `${parentName} create`;
3079
+ const input = setupCommand$8(name, create.description, argv, importMeta);
3080
+ if (input) {
3081
+ const apiKey = (0, _sdk$8.getDefaultKey)();
3082
+ if (!apiKey) {
3083
+ 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.');
3084
+ }
3085
+ const spinnerText = 'Creating repository... \n';
3086
+ const spinner = (0, _ora$8.default)(spinnerText).start();
3087
+ await createRepo(input.orgSlug, input, spinner, apiKey);
3088
+ }
3089
+ }
3090
+ };
3091
+ const repositoryCreationFlags = {
3092
+ repoName: {
3093
+ type: 'string',
3094
+ shortFlag: 'n',
3095
+ default: '',
3096
+ description: 'Repository name'
3097
+ },
3098
+ repoDescription: {
3099
+ type: 'string',
3100
+ shortFlag: 'd',
3101
+ default: '',
3102
+ description: 'Repository description'
3103
+ },
3104
+ homepage: {
3105
+ type: 'string',
3106
+ shortFlag: 'h',
3107
+ default: '',
3108
+ description: 'Repository url'
3109
+ },
3110
+ defaultBranch: {
3111
+ type: 'string',
3112
+ shortFlag: 'b',
3113
+ default: 'main',
3114
+ description: 'Repository default branch'
3115
+ },
3116
+ visibility: {
3117
+ type: 'string',
3118
+ shortFlag: 'v',
3119
+ default: 'private',
3120
+ description: 'Repository visibility (Default Private)'
3121
+ }
3122
+ };
3123
+
3124
+ // Internal functions
3125
+
3126
+ function setupCommand$8(name, description, argv, importMeta) {
3127
+ const flags = {
3128
+ __proto__: null,
3129
+ ..._flags$7.outputFlags,
3130
+ ...repositoryCreationFlags
3131
+ };
3132
+ const cli = (0, _meow$8.default)(`
3133
+ Usage
3134
+ $ ${name} <org slug>
3135
+
3136
+ Options
3137
+ ${(0, _formatting$7.printFlagList)(flags, 6)}
3138
+
3139
+ Examples
3140
+ $ ${name} FakeOrg --repoName=test-repo
3141
+ `, {
3142
+ argv,
3143
+ description,
3144
+ importMeta,
3145
+ flags
3146
+ });
3147
+ const {
3148
+ json: outputJson,
3149
+ markdown: outputMarkdown,
3150
+ repoName,
3151
+ repoDescription,
3152
+ homepage,
3153
+ defaultBranch,
3154
+ visibility
3155
+ } = cli.flags;
3156
+ const [orgSlug = ''] = cli.input;
3157
+ if (!orgSlug) {
3158
+ console.error(`${_chalk$8.default.white.bgRed('Input error')}: Please provide an organization slug\n`);
3159
+ cli.showHelp();
3160
+ return;
3161
+ }
3162
+ if (!repoName) {
3163
+ console.error(`${_chalk$8.default.white.bgRed('Input error')}: Repository name is required.\n`);
3164
+ cli.showHelp();
3165
+ return;
3166
+ }
3167
+ return {
3168
+ outputJson,
3169
+ outputMarkdown,
3170
+ orgSlug,
3171
+ name: repoName,
3172
+ description: repoDescription,
3173
+ homepage,
3174
+ default_branch: defaultBranch,
3175
+ visibility
3176
+ };
3177
+ }
3178
+ async function createRepo(orgSlug, input, spinner, apiKey) {
3179
+ const socketSdk = await (0, _sdk$8.setupSdk)(apiKey);
3180
+ const result = await (0, _apiHelpers$8.handleApiCall)(socketSdk.createOrgRepo(orgSlug, input), 'creating repository');
3181
+ if (!result.success) {
3182
+ (0, _apiHelpers$8.handleUnsuccessfulApiResponse)('createOrgRepo', result, spinner);
3183
+ return;
3184
+ }
3185
+ spinner.stop();
3186
+ console.log('\n✅ Repository created successfully\n');
3187
+ }
3188
+
3189
+ var _delete$1 = {};
3190
+
3191
+ var _interopRequireDefault$8 = vendor.interopRequireDefault.default;
3192
+ Object.defineProperty(_delete$1, "__esModule", {
3193
+ value: true
3194
+ });
3195
+ _delete$1.del = void 0;
3196
+ var _chalk$7 = _interopRequireDefault$8(vendor.source);
3197
+ var _meow$7 = _interopRequireDefault$8(vendor.build);
3198
+ var _ora$7 = _interopRequireDefault$8(vendor.ora);
3199
+ var _apiHelpers$7 = apiHelpers;
3200
+ var _errors$8 = sdk.errors;
3201
+ var _sdk$7 = sdk.sdk;
3202
+ const del = _delete$1.del = {
3203
+ description: 'Delete a repository in an organization',
3204
+ async run(argv, importMeta, {
3205
+ parentName
3206
+ }) {
3207
+ const name = `${parentName} del`;
3208
+ const input = setupCommand$7(name, del.description, argv, importMeta);
3209
+ if (input) {
3210
+ const apiKey = (0, _sdk$7.getDefaultKey)();
3211
+ if (!apiKey) {
3212
+ 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.');
3213
+ }
3214
+ const spinnerText = 'Deleting repository... \n';
3215
+ const spinner = (0, _ora$7.default)(spinnerText).start();
3216
+ await deleteRepository(input.orgSlug, input.repoName, spinner, apiKey);
3217
+ }
3218
+ }
3219
+ };
3220
+
3221
+ // Internal functions
3222
+
3223
+ function setupCommand$7(name, description, argv, importMeta) {
3224
+ const cli = (0, _meow$7.default)(`
3225
+ Usage
3226
+ $ ${name} <org slug> <repo slug>
3227
+
3228
+ Examples
3229
+ $ ${name} FakeOrg test-repo
3230
+ `, {
3231
+ argv,
3232
+ description,
3233
+ importMeta
3234
+ });
3235
+ const {
3236
+ 0: orgSlug = '',
3237
+ 1: repoName = ''
3238
+ } = cli.input;
3239
+ if (!orgSlug || !repoName) {
3240
+ console.error(`${_chalk$7.default.white.bgRed('Input error')}: Please provide an organization slug and repository slug\n`);
3241
+ cli.showHelp();
3242
+ return;
3243
+ }
3244
+ return {
3245
+ orgSlug,
3246
+ repoName
3247
+ };
3248
+ }
3249
+ async function deleteRepository(orgSlug, repoName, spinner, apiKey) {
3250
+ const socketSdk = await (0, _sdk$7.setupSdk)(apiKey);
3251
+ const result = await (0, _apiHelpers$7.handleApiCall)(socketSdk.deleteOrgRepo(orgSlug, repoName), 'deleting repository');
3252
+ if (!result.success) {
3253
+ (0, _apiHelpers$7.handleUnsuccessfulApiResponse)('deleteOrgRepo', result, spinner);
3254
+ return;
3255
+ }
3256
+ spinner.stop();
3257
+ console.log('\n✅ Repository deleted successfully\n');
3258
+ }
3259
+
3260
+ var list$1 = {};
3261
+
3262
+ var _interopRequireDefault$7 = vendor.interopRequireDefault.default;
3263
+ Object.defineProperty(list$1, "__esModule", {
3264
+ value: true
3265
+ });
3266
+ list$1.list = void 0;
3267
+ var _chalk$6 = _interopRequireDefault$7(vendor.source);
3268
+ var _chalkTable$2 = require$$2$3;
3269
+ var _meow$6 = _interopRequireDefault$7(vendor.build);
3270
+ var _ora$6 = _interopRequireDefault$7(vendor.ora);
3271
+ var _flags$6 = flags$1;
3272
+ var _apiHelpers$6 = apiHelpers;
3273
+ var _errors$7 = sdk.errors;
3274
+ var _formatting$6 = formatting;
3275
+ var _sdk$6 = sdk.sdk;
3276
+ // @ts-ignore
3277
+
3278
+ const list = list$1.list = {
3279
+ description: 'List repositories in an organization',
3280
+ async run(argv, importMeta, {
3281
+ parentName
3282
+ }) {
3283
+ const name = `${parentName} list`;
3284
+ const input = setupCommand$6(name, list.description, argv, importMeta);
3285
+ if (input) {
3286
+ const apiKey = (0, _sdk$6.getDefaultKey)();
3287
+ if (!apiKey) {
3288
+ 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.');
3289
+ }
3290
+ const spinnerText = 'Listing repositories... \n';
3291
+ const spinner = (0, _ora$6.default)(spinnerText).start();
3292
+ await listOrgRepos(input.orgSlug, input, spinner, apiKey);
3293
+ }
3294
+ }
3295
+ };
3296
+ const listRepoFlags = {
3297
+ sort: {
3298
+ type: 'string',
3299
+ shortFlag: 's',
3300
+ default: 'created_at',
3301
+ description: 'Sorting option'
3302
+ },
3303
+ direction: {
3304
+ type: 'string',
3305
+ default: 'desc',
3306
+ description: 'Direction option'
3307
+ },
3308
+ perPage: {
3309
+ type: 'number',
3310
+ shortFlag: 'pp',
3311
+ default: 30,
3312
+ description: 'Number of results per page'
3313
+ },
3314
+ page: {
3315
+ type: 'number',
3316
+ shortFlag: 'p',
3317
+ default: 1,
3318
+ description: 'Page number'
3319
+ }
3320
+ };
3321
+
3322
+ // Internal functions
3323
+
3324
+ function setupCommand$6(name, description, argv, importMeta) {
3325
+ const flags = {
3326
+ ..._flags$6.outputFlags,
3327
+ ...listRepoFlags
3328
+ };
3329
+ const cli = (0, _meow$6.default)(`
3330
+ Usage
3331
+ $ ${name} <org slug>
3332
+
3333
+ Options
3334
+ ${(0, _formatting$6.printFlagList)(flags, 6)}
3335
+
3336
+ Examples
3337
+ $ ${name} FakeOrg
3338
+ `, {
3339
+ argv,
3340
+ description,
3341
+ importMeta,
3342
+ flags
3343
+ });
3344
+ const {
3345
+ json: outputJson,
3346
+ markdown: outputMarkdown,
3347
+ perPage,
3348
+ sort,
3349
+ direction,
3350
+ page
3351
+ } = cli.flags;
3352
+ if (!cli.input[0]) {
3353
+ console.error(`${_chalk$6.default.white.bgRed('Input error')}: Please provide an organization slug\n`);
3354
+ cli.showHelp();
3355
+ return;
3356
+ }
3357
+ const {
3358
+ 0: orgSlug = ''
3359
+ } = cli.input;
3360
+ return {
3361
+ outputJson,
3362
+ outputMarkdown,
3363
+ orgSlug,
3364
+ sort,
3365
+ direction,
3366
+ page,
3367
+ per_page: perPage
3368
+ };
3369
+ }
3370
+ async function listOrgRepos(orgSlug, input, spinner, apiKey) {
3371
+ const socketSdk = await (0, _sdk$6.setupSdk)(apiKey);
3372
+ const result = await (0, _apiHelpers$6.handleApiCall)(socketSdk.getOrgRepoList(orgSlug, input), 'listing repositories');
3373
+ if (!result.success) {
3374
+ (0, _apiHelpers$6.handleUnsuccessfulApiResponse)('getOrgRepoList', result, spinner);
3375
+ return;
3376
+ }
3377
+ spinner.stop();
3378
+ const options = {
3379
+ columns: [{
3380
+ field: 'id',
3381
+ name: _chalk$6.default.magenta('ID')
3382
+ }, {
3383
+ field: 'name',
3384
+ name: _chalk$6.default.magenta('Name')
3385
+ }, {
3386
+ field: 'visibility',
3387
+ name: _chalk$6.default.magenta('Visibility')
3388
+ }, {
3389
+ field: 'default_branch',
3390
+ name: _chalk$6.default.magenta('Default branch')
3391
+ }, {
3392
+ field: 'archived',
3393
+ name: _chalk$6.default.magenta('Archived')
3394
+ }]
3395
+ };
3396
+ console.log(`${_chalkTable$2(options, result.data.results)}\n`);
3397
+ }
3398
+
3399
+ var update$1 = {};
3400
+
3401
+ var _interopRequireDefault$6 = vendor.interopRequireDefault.default;
3402
+ Object.defineProperty(update$1, "__esModule", {
3403
+ value: true
3404
+ });
3405
+ update$1.update = void 0;
3406
+ var _chalk$5 = _interopRequireDefault$6(vendor.source);
3407
+ var _meow$5 = _interopRequireDefault$6(vendor.build);
3408
+ var _ora$5 = _interopRequireDefault$6(vendor.ora);
3409
+ var _flags$5 = flags$1;
3410
+ var _apiHelpers$5 = apiHelpers;
3411
+ var _errors$6 = sdk.errors;
3412
+ var _formatting$5 = formatting;
3413
+ var _sdk$5 = sdk.sdk;
3414
+ const update = update$1.update = {
3415
+ description: 'Update a repository in an organization',
3416
+ async run(argv, importMeta, {
3417
+ parentName
3418
+ }) {
3419
+ const name = `${parentName} update`;
3420
+ const input = setupCommand$5(name, update.description, argv, importMeta);
3421
+ if (input) {
3422
+ const apiKey = (0, _sdk$5.getDefaultKey)();
3423
+ if (!apiKey) {
3424
+ 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.');
3425
+ }
3426
+ const spinnerText = 'Updating repository... \n';
3427
+ const spinner = (0, _ora$5.default)(spinnerText).start();
3428
+ await updateRepository(input.orgSlug, input, spinner, apiKey);
3429
+ }
3430
+ }
3431
+ };
3432
+ const repositoryUpdateFlags = {
3433
+ repoName: {
3434
+ type: 'string',
3435
+ shortFlag: 'n',
3436
+ default: '',
3437
+ description: 'Repository name'
3438
+ },
3439
+ repoDescription: {
3440
+ type: 'string',
3441
+ shortFlag: 'd',
3442
+ default: '',
3443
+ description: 'Repository description'
3444
+ },
3445
+ homepage: {
3446
+ type: 'string',
3447
+ shortFlag: 'h',
3448
+ default: '',
3449
+ description: 'Repository url'
3450
+ },
3451
+ defaultBranch: {
3452
+ type: 'string',
3453
+ shortFlag: 'b',
3454
+ default: 'main',
3455
+ description: 'Repository default branch'
3456
+ },
3457
+ visibility: {
3458
+ type: 'string',
3459
+ shortFlag: 'v',
3460
+ default: 'private',
3461
+ description: 'Repository visibility (Default Private)'
3462
+ }
3463
+ };
3464
+
3465
+ // Internal functions
3466
+
3467
+ function setupCommand$5(name, description, argv, importMeta) {
3468
+ const flags = {
3469
+ ..._flags$5.outputFlags,
3470
+ ...repositoryUpdateFlags
3471
+ };
3472
+ const cli = (0, _meow$5.default)(`
3473
+ Usage
3474
+ $ ${name} <org slug>
3475
+
3476
+ Options
3477
+ ${(0, _formatting$5.printFlagList)(flags, 6)}
3478
+
3479
+ Examples
3480
+ $ ${name} FakeOrg
3481
+ `, {
3482
+ argv,
3483
+ description,
3484
+ importMeta,
3485
+ flags
3486
+ });
3487
+ const {
3488
+ json: outputJson,
3489
+ markdown: outputMarkdown,
3490
+ repoName,
3491
+ repoDescription,
3492
+ homepage,
3493
+ defaultBranch,
3494
+ visibility
3495
+ } = cli.flags;
3496
+ const [orgSlug = ''] = cli.input;
3497
+ if (!orgSlug) {
3498
+ console.error(`${_chalk$5.default.white.bgRed('Input error')}: Please provide an organization slug and repository name\n`);
3499
+ cli.showHelp();
3500
+ return;
3501
+ }
3502
+ if (!repoName) {
3503
+ console.error(`${_chalk$5.default.white.bgRed('Input error')}: Repository name is required.\n`);
3504
+ cli.showHelp();
3505
+ return;
3506
+ }
3507
+ return {
3508
+ outputJson,
3509
+ outputMarkdown,
3510
+ orgSlug,
3511
+ name: repoName,
3512
+ description: repoDescription,
3513
+ homepage,
3514
+ default_branch: defaultBranch,
3515
+ visibility
3516
+ };
3517
+ }
3518
+ async function updateRepository(orgSlug, input, spinner, apiKey) {
3519
+ const socketSdk = await (0, _sdk$5.setupSdk)(apiKey);
3520
+ const result = await (0, _apiHelpers$5.handleApiCall)(socketSdk.updateOrgRepo(orgSlug, input.name, input), 'updating repository');
3521
+ if (!result.success) {
3522
+ (0, _apiHelpers$5.handleUnsuccessfulApiResponse)('updateOrgRepo', result, spinner);
3523
+ return;
3524
+ }
3525
+ spinner.stop();
3526
+ console.log('\n✅ Repository updated successfully\n');
3527
+ }
3528
+
3529
+ var view$1 = {};
3530
+
3531
+ var _interopRequireDefault$5 = vendor.interopRequireDefault.default;
3532
+ Object.defineProperty(view$1, "__esModule", {
3533
+ value: true
3534
+ });
3535
+ view$1.view = void 0;
3536
+ var _chalk$4 = _interopRequireDefault$5(vendor.source);
3537
+ var _chalkTable$1 = require$$2$3;
3538
+ var _meow$4 = _interopRequireDefault$5(vendor.build);
3539
+ var _ora$4 = _interopRequireDefault$5(vendor.ora);
3540
+ var _flags$4 = flags$1;
3541
+ var _apiHelpers$4 = apiHelpers;
3542
+ var _errors$5 = sdk.errors;
3543
+ var _formatting$4 = formatting;
3544
+ var _sdk$4 = sdk.sdk;
3545
+ // @ts-ignore
3546
+
3547
+ const view = view$1.view = {
3548
+ description: 'View repositories in an organization',
3549
+ async run(argv, importMeta, {
3550
+ parentName
3551
+ }) {
3552
+ const name = `${parentName} view`;
3553
+ const input = setupCommand$4(name, view.description, argv, importMeta);
3554
+ if (input) {
3555
+ const apiKey = (0, _sdk$4.getDefaultKey)();
3556
+ if (!apiKey) {
3557
+ 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.');
3558
+ }
3559
+ const spinnerText = 'Fetching repository... \n';
3560
+ const spinner = (0, _ora$4.default)(spinnerText).start();
3561
+ await viewRepository(input.orgSlug, input.repositoryName, spinner, apiKey);
3562
+ }
3563
+ }
3564
+ };
3565
+
3566
+ // Internal functions
3567
+
3568
+ function setupCommand$4(name, description, argv, importMeta) {
3569
+ const flags = {
3570
+ ..._flags$4.outputFlags
3571
+ };
3572
+ const cli = (0, _meow$4.default)(`
3573
+ Usage
3574
+ $ ${name} <org slug>
3575
+
3576
+ Options
3577
+ ${(0, _formatting$4.printFlagList)(flags, 6)}
3578
+
3579
+ Examples
3580
+ $ ${name} FakeOrg
3581
+ `, {
3582
+ argv,
3583
+ description,
3584
+ importMeta,
3585
+ flags
3586
+ });
3587
+ const {
3588
+ json: outputJson,
3589
+ markdown: outputMarkdown
3590
+ } = cli.flags;
3591
+ if (!cli.input[0]) {
3592
+ console.error(`${_chalk$4.default.white.bgRed('Input error')}: Please provide an organization slug and repository name\n`);
3593
+ cli.showHelp();
3594
+ return;
3595
+ }
3596
+ const {
3597
+ 0: orgSlug = '',
3598
+ 1: repositoryName = ''
3599
+ } = cli.input;
3600
+ return {
3601
+ outputJson,
3602
+ outputMarkdown,
3603
+ orgSlug,
3604
+ repositoryName
3605
+ };
3606
+ }
3607
+ async function viewRepository(orgSlug, repoName, spinner, apiKey) {
3608
+ const socketSdk = await (0, _sdk$4.setupSdk)(apiKey);
3609
+ const result = await (0, _apiHelpers$4.handleApiCall)(socketSdk.getOrgRepo(orgSlug, repoName), 'fetching repository');
3610
+ if (!result.success) {
3611
+ (0, _apiHelpers$4.handleUnsuccessfulApiResponse)('getOrgRepo', result, spinner);
3612
+ return;
3613
+ }
3614
+ spinner.stop();
3615
+ const options = {
3616
+ columns: [{
3617
+ field: 'id',
3618
+ name: _chalk$4.default.magenta('ID')
3619
+ }, {
3620
+ field: 'name',
3621
+ name: _chalk$4.default.magenta('Name')
3622
+ }, {
3623
+ field: 'visibility',
3624
+ name: _chalk$4.default.magenta('Visibility')
3625
+ }, {
3626
+ field: 'default_branch',
3627
+ name: _chalk$4.default.magenta('Default branch')
3628
+ }, {
3629
+ field: 'homepage',
3630
+ name: _chalk$4.default.magenta('Homepage')
3631
+ }, {
3632
+ field: 'archived',
3633
+ name: _chalk$4.default.magenta('Archived')
3634
+ }, {
3635
+ field: 'created_at',
3636
+ name: _chalk$4.default.magenta('Created at')
3637
+ }]
3638
+ };
3639
+ console.log(`${_chalkTable$1(options, [result.data])}\n`);
3640
+ }
3641
+
3642
+ Object.defineProperty(repos, "__esModule", {
3643
+ value: true
3644
+ });
3645
+ repos.repo = void 0;
3646
+ var _create = create$1;
3647
+ var _delete = _delete$1;
3648
+ var _list = list$1;
3649
+ var _update = update$1;
3650
+ var _view = view$1;
3651
+ var _meowWithSubcommands$2 = meowWithSubcommands$1;
3652
+ const description$1 = 'Repositories related commands';
3653
+ repos.repo = {
3654
+ description: description$1,
3655
+ run: async (argv, importMeta, {
3656
+ parentName
3657
+ }) => {
3658
+ await (0, _meowWithSubcommands$2.meowWithSubcommands)({
3659
+ create: _create.create,
3660
+ view: _view.view,
3661
+ list: _list.list,
3662
+ del: _delete.del,
3663
+ update: _update.update
3664
+ }, {
3665
+ argv,
3666
+ description: description$1,
3667
+ importMeta,
3668
+ name: `${parentName} repo`
3669
+ });
3670
+ }
3671
+ };
3672
+
3673
+ var dependencies$1 = {};
3674
+
3675
+ var _interopRequireDefault$4 = vendor.interopRequireDefault.default;
3676
+ Object.defineProperty(dependencies$1, "__esModule", {
3677
+ value: true
3678
+ });
3679
+ dependencies$1.dependencies = void 0;
3680
+ var _chalk$3 = _interopRequireDefault$4(vendor.source);
3681
+ var _chalkTable = require$$2$3;
3682
+ var _meow$3 = _interopRequireDefault$4(vendor.build);
3683
+ var _ora$3 = _interopRequireDefault$4(vendor.ora);
3684
+ var _flags$3 = flags$1;
3685
+ var _apiHelpers$3 = apiHelpers;
3686
+ var _errors$4 = sdk.errors;
3687
+ var _formatting$3 = formatting;
3688
+ var _sdk$3 = sdk.sdk;
3689
+ // @ts-ignore
3690
+
3691
+ const dependencies = dependencies$1.dependencies = {
3692
+ description: 'Search for any dependency that is being used in your organization',
3693
+ async run(argv, importMeta, {
3694
+ parentName
3695
+ }) {
3696
+ const name = parentName + ' dependencies';
3697
+ const input = setupCommand$3(name, dependencies.description, argv, importMeta);
3698
+ if (input) {
3699
+ await searchDeps(input);
3700
+ }
3701
+ }
3702
+ };
3703
+ const dependenciesFlags = {
3704
+ limit: {
3705
+ type: 'number',
3706
+ shortFlag: 'l',
3707
+ default: 50,
3708
+ description: 'Maximum number of dependencies returned'
3709
+ },
3710
+ offset: {
3711
+ type: 'number',
3712
+ shortFlag: 'o',
3713
+ default: 0,
3714
+ description: 'Page number'
3715
+ }
3716
+ };
3717
+
3718
+ // Internal functions
3719
+
3720
+ function setupCommand$3(name, description, argv, importMeta) {
3721
+ const flags = {
3722
+ __proto__: null,
3723
+ ..._flags$3.outputFlags,
3724
+ ...dependenciesFlags
3725
+ };
3726
+ const cli = (0, _meow$3.default)(`
3727
+ Usage
3728
+ $ ${name}
3729
+
3730
+ Options
3731
+ ${(0, _formatting$3.printFlagList)(flags, 6)}
3732
+
3733
+ Examples
3734
+ $ ${name}
3735
+ `, {
3736
+ argv,
3737
+ description,
3738
+ importMeta,
3739
+ flags
3740
+ });
3741
+ const {
3742
+ json: outputJson,
3743
+ markdown: outputMarkdown,
3744
+ limit,
3745
+ offset
3746
+ } = cli.flags;
3747
+ return {
3748
+ outputJson,
3749
+ outputMarkdown,
3750
+ limit,
3751
+ offset
3752
+ };
3753
+ }
3754
+ async function searchDeps({
3755
+ limit,
3756
+ offset,
3757
+ outputJson
3758
+ }) {
3759
+ const apiKey = (0, _sdk$3.getDefaultKey)();
3760
+ if (!apiKey) {
3761
+ 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.');
3762
+ }
3763
+ const spinnerText = 'Searching dependencies...';
3764
+ const spinner = (0, _ora$3.default)(spinnerText).start();
3765
+ const socketSdk = await (0, _sdk$3.setupSdk)(apiKey);
3766
+ const result = await (0, _apiHelpers$3.handleApiCall)(socketSdk.searchDependencies({
3767
+ limit,
3768
+ offset
3769
+ }), 'Searching dependencies');
3770
+ if (!result.success) {
3771
+ (0, _apiHelpers$3.handleUnsuccessfulApiResponse)('searchDependencies', result, spinner);
3772
+ return;
3773
+ }
3774
+ spinner.stop();
3775
+ console.log('Organization dependencies:\n');
3776
+ if (outputJson) {
3777
+ console.log(result.data);
3778
+ return;
3779
+ }
3780
+ const options = {
3781
+ columns: [{
3782
+ field: 'namespace',
3783
+ name: _chalk$3.default.cyan('Namespace')
3784
+ }, {
3785
+ field: 'name',
3786
+ name: _chalk$3.default.cyan('Name')
3787
+ }, {
3788
+ field: 'version',
3789
+ name: _chalk$3.default.cyan('Version')
3790
+ }, {
3791
+ field: 'repository',
3792
+ name: _chalk$3.default.cyan('Repository')
3793
+ }, {
3794
+ field: 'branch',
3795
+ name: _chalk$3.default.cyan('Branch')
3796
+ }, {
3797
+ field: 'type',
3798
+ name: _chalk$3.default.cyan('Type')
3799
+ }, {
3800
+ field: 'direct',
3801
+ name: _chalk$3.default.cyan('Direct')
3802
+ }]
3803
+ };
3804
+ console.log(`${_chalkTable(options, result.data.rows)}\n`);
3805
+ }
3806
+
3807
+ var analytics$1 = {};
3808
+
3809
+ var _interopRequireDefault$3 = vendor.interopRequireDefault.default;
3810
+ Object.defineProperty(analytics$1, "__esModule", {
3811
+ value: true
3812
+ });
3813
+ analytics$1.analytics = void 0;
3814
+ var _nodeFs$2 = require$$0;
3815
+ var _blessed$1 = require$$2$4;
3816
+ var _blessedContrib$1 = require$$3$5;
3817
+ var _chalk$2 = _interopRequireDefault$3(vendor.source);
3818
+ var _meow$2 = _interopRequireDefault$3(vendor.build);
3819
+ var _ora$2 = _interopRequireDefault$3(vendor.ora);
3820
+ var _flags$2 = flags$1;
3821
+ var _apiHelpers$2 = apiHelpers;
3822
+ var _errors$3 = sdk.errors;
3823
+ var _formatting$2 = formatting;
3824
+ var _sdk$2 = sdk.sdk;
3825
+ // @ts-ignore
3826
+
3827
+ const analytics = analytics$1.analytics = {
3828
+ description: `Look up analytics data \n
3829
+ Default parameters are set to show the organization-level analytics over the last 7 days.`,
3830
+ async run(argv, importMeta, {
3831
+ parentName
3832
+ }) {
3833
+ const name = parentName + ' analytics';
3834
+ const input = setupCommand$2(name, analytics.description, argv, importMeta);
3835
+ if (input) {
3836
+ const apiKey = (0, _sdk$2.getDefaultKey)();
3837
+ if (!apiKey) {
3838
+ 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.');
3839
+ }
3840
+ const spinner = (0, _ora$2.default)('Fetching analytics data').start();
3841
+ if (input.scope === 'org') {
3842
+ await fetchOrgAnalyticsData(input.time, spinner, apiKey, input.outputJson, input.file);
3843
+ } else {
3844
+ if (input.repo) {
3845
+ await fetchRepoAnalyticsData(input.repo, input.time, spinner, apiKey, input.outputJson, input.file);
3846
+ }
3847
+ }
3848
+ }
3849
+ }
3850
+ };
3851
+ const analyticsFlags = {
3852
+ scope: {
3853
+ type: 'string',
3854
+ shortFlag: 's',
3855
+ default: 'org',
3856
+ description: "Scope of the analytics data - either 'org' or 'repo'"
3857
+ },
3858
+ time: {
3859
+ type: 'number',
3860
+ shortFlag: 't',
3861
+ default: 7,
3862
+ description: 'Time filter - either 7, 30 or 90'
3863
+ },
3864
+ repo: {
3865
+ type: 'string',
3866
+ shortFlag: 'r',
3867
+ default: '',
3868
+ description: 'Name of the repository'
3869
+ },
3870
+ file: {
3871
+ type: 'string',
3872
+ shortFlag: 'f',
3873
+ default: '',
3874
+ description: 'Path to a local file to save the output'
3875
+ }
3876
+ };
3877
+
3878
+ // Internal functions
3879
+
3880
+ function setupCommand$2(name, description, argv, importMeta) {
3881
+ const flags = {
3882
+ __proto__: null,
3883
+ ..._flags$2.outputFlags,
3884
+ ...analyticsFlags
3885
+ };
3886
+ const cli = (0, _meow$2.default)(`
3887
+ Usage
3888
+ $ ${name} --scope=<scope> --time=<time filter>
3889
+
3890
+ Options
3891
+ ${(0, _formatting$2.printFlagList)(flags, 6)}
3892
+
3893
+ Examples
3894
+ $ ${name} --scope=org --time=7
3895
+ $ ${name} --scope=org --time=30
3896
+ $ ${name} --scope=repo --repo=test-repo --time=30
3897
+ `, {
3898
+ argv,
3899
+ description,
3900
+ importMeta,
3901
+ flags
3902
+ });
3903
+ const {
3904
+ json: outputJson,
3905
+ scope,
3906
+ time,
3907
+ repo,
3908
+ file
3909
+ } = cli.flags;
3910
+ if (scope !== 'org' && scope !== 'repo') {
3911
+ throw new _errors$3.InputError("The scope must either be 'org' or 'repo'");
3912
+ }
3913
+ if (time !== 7 && time !== 30 && time !== 90) {
3914
+ throw new _errors$3.InputError('The time filter must either be 7, 30 or 90');
3915
+ }
3916
+ if (scope === 'repo' && !repo) {
3917
+ console.error(`${_chalk$2.default.bgRed.white('Input error')}: Please provide a repository name when using the repository scope. \n`);
3918
+ cli.showHelp();
3919
+ return;
3920
+ }
3921
+ return {
3922
+ scope,
3923
+ time,
3924
+ repo,
3925
+ outputJson,
3926
+ file
3927
+ };
3928
+ }
3929
+ 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'];
3930
+ async function fetchOrgAnalyticsData(time, spinner, apiKey, outputJson, filePath) {
3931
+ const socketSdk = await (0, _sdk$2.setupSdk)(apiKey);
3932
+ const result = await (0, _apiHelpers$2.handleApiCall)(socketSdk.getOrgAnalytics(time.toString()), 'fetching analytics data');
3933
+ if (result.success === false) {
3934
+ return (0, _apiHelpers$2.handleUnsuccessfulApiResponse)('getOrgAnalytics', result, spinner);
3935
+ }
3936
+ spinner.stop();
3937
+ if (!result.data.length) {
3938
+ return console.log('No analytics data is available for this organization yet.');
3939
+ }
3940
+ const data = formatData(result.data, 'org');
3941
+ if (outputJson && !filePath) {
3942
+ return console.log(result.data);
3943
+ }
3944
+ if (filePath) {
3945
+ _nodeFs$2.writeFile(filePath, JSON.stringify(result.data), err => {
3946
+ err ? console.error(err) : console.log(`Data successfully written to ${filePath}`);
3947
+ });
3948
+ return;
3949
+ }
3950
+ return displayAnalyticsScreen(data);
3951
+ }
3952
+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
3953
+ const formatDate = date => {
3954
+ return `${months[new Date(date).getMonth()]} ${new Date(date).getDate()}`;
3955
+ };
3956
+ const formatData = (data, scope) => {
3957
+ let formattedData, sortedTopFiveAlerts;
3958
+ if (scope === 'org') {
3959
+ const topFiveAlerts = data.map(d => d['top_five_alert_types']);
3960
+ const totalTopAlerts = topFiveAlerts.reduce((acc, current) => {
3961
+ const alertTypes = Object.keys(current);
3962
+ alertTypes.map(type => {
3963
+ if (!acc[type]) {
3964
+ acc[type] = current[type];
3965
+ } else {
3966
+ acc[type] += current[type];
3967
+ }
3968
+ return acc;
3969
+ });
3970
+ return acc;
3971
+ }, {});
3972
+ sortedTopFiveAlerts = Object.entries(totalTopAlerts).sort(({
3973
+ 1: a
3974
+ }, {
3975
+ 1: b
3976
+ }) => b - a).slice(0, 5).reduce((r, {
3977
+ 0: k,
3978
+ 1: v
3979
+ }) => {
3980
+ r[k] = v;
3981
+ return r;
3982
+ }, {});
3983
+ const formatData = label => {
3984
+ return data.reduce((acc, current) => {
3985
+ const date = formatDate(current['created_at']);
3986
+ if (!acc[date]) {
3987
+ acc[date] = current[label];
3988
+ } else {
3989
+ acc[date] += current[label];
3990
+ }
3991
+ return acc;
3992
+ }, {});
3993
+ };
3994
+ formattedData = METRICS.reduce((acc, current) => {
3995
+ acc[current] = formatData(current);
3996
+ return acc;
3997
+ }, {});
3998
+ } else if (scope === 'repo') {
3999
+ const topAlerts = data.reduce((acc, current) => {
4000
+ const alertTypes = Object.keys(current['top_five_alert_types']);
4001
+ alertTypes.map(type => {
4002
+ if (!acc[type]) {
4003
+ acc[type] = current['top_five_alert_types'][type];
4004
+ } else {
4005
+ if (current['top_five_alert_types'][type] > (acc[type] || 0)) {
4006
+ acc[type] = current['top_five_alert_types'][type];
4007
+ }
4008
+ }
4009
+ return acc;
4010
+ });
4011
+ return acc;
4012
+ }, {});
4013
+ sortedTopFiveAlerts = Object.entries(topAlerts).sort(({
4014
+ 1: a
4015
+ }, {
4016
+ 1: b
4017
+ }) => b - a).slice(0, 5).reduce((r, {
4018
+ 0: k,
4019
+ 1: v
4020
+ }) => {
4021
+ r[k] = v;
4022
+ return r;
4023
+ }, {});
4024
+ formattedData = data.reduce((acc, current) => {
4025
+ METRICS.forEach(m => {
4026
+ if (!acc[m]) {
4027
+ acc[m] = {};
4028
+ }
4029
+ acc[m][formatDate(current['created_at'])] = current[m];
4030
+ return acc;
4031
+ });
4032
+ return acc;
4033
+ }, {});
4034
+ }
4035
+ return {
4036
+ ...formattedData,
4037
+ top_five_alert_types: sortedTopFiveAlerts
4038
+ };
4039
+ };
4040
+ async function fetchRepoAnalyticsData(repo, time, spinner, apiKey, outputJson, filePath) {
4041
+ const socketSdk = await (0, _sdk$2.setupSdk)(apiKey);
4042
+ const result = await (0, _apiHelpers$2.handleApiCall)(socketSdk.getRepoAnalytics(repo, time.toString()), 'fetching analytics data');
4043
+ if (result.success === false) {
4044
+ return (0, _apiHelpers$2.handleUnsuccessfulApiResponse)('getRepoAnalytics', result, spinner);
4045
+ }
4046
+ spinner.stop();
4047
+ if (!result.data.length) {
4048
+ return console.log('No analytics data is available for this organization yet.');
4049
+ }
4050
+ const data = formatData(result.data, 'repo');
4051
+ if (outputJson && !filePath) {
4052
+ return console.log(result.data);
4053
+ }
4054
+ if (filePath) {
4055
+ _nodeFs$2.writeFile(filePath, JSON.stringify(result.data), err => {
4056
+ err ? console.error(err) : console.log(`Data successfully written to ${filePath}`);
4057
+ });
4058
+ return;
4059
+ }
4060
+ return displayAnalyticsScreen(data);
4061
+ }
4062
+ const displayAnalyticsScreen = data => {
4063
+ const screen = _blessed$1.screen();
4064
+ const grid = new _blessedContrib$1.grid({
4065
+ rows: 5,
4066
+ cols: 4,
4067
+ screen
4068
+ });
4069
+ renderLineCharts(grid, screen, 'Total critical alerts', [0, 0, 1, 2], data['total_critical_alerts']);
4070
+ renderLineCharts(grid, screen, 'Total high alerts', [0, 2, 1, 2], data['total_high_alerts']);
4071
+ renderLineCharts(grid, screen, 'Total critical alerts added to the main branch', [1, 0, 1, 2], data['total_critical_added']);
4072
+ renderLineCharts(grid, screen, 'Total high alerts added to the main branch', [1, 2, 1, 2], data['total_high_added']);
4073
+ renderLineCharts(grid, screen, 'Total critical alerts prevented from the main branch', [2, 0, 1, 2], data['total_critical_prevented']);
4074
+ renderLineCharts(grid, screen, 'Total high alerts prevented from the main branch', [2, 2, 1, 2], data['total_high_prevented']);
4075
+ renderLineCharts(grid, screen, 'Total medium alerts prevented from the main branch', [3, 0, 1, 2], data['total_medium_prevented']);
4076
+ renderLineCharts(grid, screen, 'Total low alerts prevented from the main branch', [3, 2, 1, 2], data['total_low_prevented']);
4077
+ const bar = grid.set(4, 0, 1, 2, _blessedContrib$1.bar, {
4078
+ label: 'Top 5 alert types',
4079
+ barWidth: 10,
4080
+ barSpacing: 17,
4081
+ xOffset: 0,
4082
+ maxHeight: 9,
4083
+ barBgColor: 'magenta'
4084
+ });
4085
+ screen.append(bar); //must append before setting data
4086
+
4087
+ bar.setData({
4088
+ titles: Object.keys(data.top_five_alert_types),
4089
+ data: Object.values(data.top_five_alert_types)
4090
+ });
4091
+ screen.render();
4092
+ screen.key(['escape', 'q', 'C-c'], () => process.exit(0));
4093
+ };
4094
+ const renderLineCharts = (grid, screen, title, coords, data) => {
4095
+ const line = grid.set(...coords, _blessedContrib$1.line, {
4096
+ style: {
4097
+ line: 'cyan',
4098
+ text: 'cyan',
4099
+ baseline: 'black'
4100
+ },
4101
+ xLabelPadding: 0,
4102
+ xPadding: 0,
4103
+ xOffset: 0,
4104
+ wholeNumbersOnly: true,
4105
+ legend: {
4106
+ width: 1
4107
+ },
4108
+ label: title
4109
+ });
4110
+ screen.append(line);
4111
+ const lineData = {
4112
+ x: Object.keys(data),
4113
+ y: Object.values(data)
4114
+ };
4115
+ line.setData([lineData]);
4116
+ };
4117
+
4118
+ var diffScan = {};
4119
+
4120
+ var get$1 = {};
4121
+
4122
+ var _interopRequireDefault$2 = vendor.interopRequireDefault.default;
4123
+ Object.defineProperty(get$1, "__esModule", {
4124
+ value: true
4125
+ });
4126
+ get$1.get = void 0;
4127
+ var _nodeFs$1 = require$$0;
4128
+ var _nodeUtil = require$$0$2;
4129
+ var _chalk$1 = _interopRequireDefault$2(vendor.source);
4130
+ var _meow$1 = _interopRequireDefault$2(vendor.build);
4131
+ var _ora$1 = _interopRequireDefault$2(vendor.ora);
4132
+ var _flags$1 = flags$1;
4133
+ var _apiHelpers$1 = apiHelpers;
4134
+ var _errors$2 = sdk.errors;
4135
+ var _formatting$1 = formatting;
4136
+ var _sdk$1 = sdk.sdk;
4137
+ const get = get$1.get = {
4138
+ description: 'Get a diff scan for an organization',
4139
+ async run(argv, importMeta, {
4140
+ parentName
4141
+ }) {
4142
+ const name = `${parentName} get`;
4143
+ const input = setupCommand$1(name, get.description, argv, importMeta);
4144
+ if (input) {
4145
+ const apiKey = (0, _sdk$1.getDefaultKey)();
4146
+ if (!apiKey) {
4147
+ 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.');
4148
+ }
4149
+ const spinnerText = 'Getting diff scan... \n';
4150
+ const spinner = (0, _ora$1.default)(spinnerText).start();
4151
+ await getDiffScan(input, spinner, apiKey);
4152
+ }
4153
+ }
4154
+ };
4155
+ const getDiffScanFlags = {
4156
+ before: {
4157
+ type: 'string',
4158
+ shortFlag: 'b',
4159
+ default: '',
4160
+ description: 'The full scan ID of the base scan'
4161
+ },
4162
+ after: {
4163
+ type: 'string',
4164
+ shortFlag: 'a',
4165
+ default: '',
4166
+ description: 'The full scan ID of the head scan'
4167
+ },
4168
+ preview: {
4169
+ type: 'boolean',
4170
+ shortFlag: 'p',
4171
+ default: true,
4172
+ description: 'A boolean flag to persist or not the diff scan result'
4173
+ },
4174
+ file: {
4175
+ type: 'string',
4176
+ shortFlag: 'f',
4177
+ default: '',
4178
+ description: 'Path to a local file where the output should be saved'
4179
+ }
4180
+ };
4181
+
4182
+ // Internal functions
4183
+
4184
+ function setupCommand$1(name, description, argv, importMeta) {
4185
+ const flags = {
4186
+ __proto__: null,
4187
+ ..._flags$1.outputFlags,
4188
+ ...getDiffScanFlags
4189
+ };
4190
+ const cli = (0, _meow$1.default)(`
4191
+ Usage
4192
+ $ ${name} <org slug> --before=<before> --after=<after>
4193
+
4194
+ Options
4195
+ ${(0, _formatting$1.printFlagList)(flags, 6)}
4196
+
4197
+ Examples
4198
+ $ ${name} FakeCorp --before=aaa0aa0a-aaaa-0000-0a0a-0000000a00a0 --after=aaa1aa1a-aaaa-1111-1a1a-1111111a11a1
4199
+ `, {
4200
+ argv,
4201
+ description,
4202
+ importMeta,
4203
+ flags
4204
+ });
4205
+ const {
4206
+ json: outputJson,
4207
+ markdown: outputMarkdown,
4208
+ before,
4209
+ after,
4210
+ preview,
4211
+ file
4212
+ } = cli.flags;
4213
+ if (!before || !after) {
4214
+ 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`);
4215
+ cli.showHelp();
4216
+ return;
4217
+ }
4218
+ if (cli.input.length < 1) {
4219
+ console.error(`${_chalk$1.default.bgRed.white('Input error')}: Please provide an organization slug\n`);
4220
+ cli.showHelp();
4221
+ return;
4222
+ }
4223
+ const [orgSlug = ''] = cli.input;
4224
+ return {
4225
+ outputJson,
4226
+ outputMarkdown,
4227
+ before,
4228
+ after,
4229
+ preview,
4230
+ orgSlug,
4231
+ file
4232
+ };
4233
+ }
4234
+ async function getDiffScan({
4235
+ before,
4236
+ after,
4237
+ orgSlug,
4238
+ file,
4239
+ outputJson
4240
+ }, spinner, apiKey) {
4241
+ const response = await (0, _apiHelpers$1.queryAPI)(`${orgSlug}/full-scans/diff?before=${before}&after=${after}&preview`, apiKey);
4242
+ const data = await response.json();
4243
+ if (!response.ok) {
4244
+ spinner.stop();
4245
+ const err = await (0, _apiHelpers$1.handleAPIError)(response.status);
4246
+ console.error(`${_chalk$1.default.bgRed.white(response.statusText)}: ${err}\n`);
4247
+ return;
4248
+ }
4249
+ spinner.stop();
4250
+ if (file && !outputJson) {
4251
+ _nodeFs$1.writeFile(file, JSON.stringify(data), err => {
4252
+ err ? console.error(err) : console.log(`Data successfully written to ${file}`);
4253
+ });
4254
+ return;
4255
+ }
4256
+ if (outputJson) {
4257
+ console.log(`\n Diff scan result: \n`);
4258
+ console.log(_nodeUtil.inspect(data, {
4259
+ showHidden: false,
4260
+ depth: null,
4261
+ colors: true
4262
+ }));
4263
+ // @ts-ignore
4264
+ console.log(`\n View this diff scan in the Socket dashboard: ${_chalk$1.default.cyan(data?.['diff_report_url'])}\n`);
4265
+ return;
4266
+ }
4267
+ console.log('Diff scan result: ');
4268
+ console.log(data);
4269
+ console.log(`\n 📝 To display the detailed report in the terminal, use the --json flag \n`);
4270
+ // @ts-ignore
4271
+ console.log(`\n View this diff scan in the Socket dashboard: ${_chalk$1.default.cyan(data?.['diff_report_url'])}\n`);
4272
+ }
4273
+
4274
+ Object.defineProperty(diffScan, "__esModule", {
4275
+ value: true
4276
+ });
4277
+ diffScan.diffScan = void 0;
4278
+ var _get = get$1;
4279
+ var _meowWithSubcommands$1 = meowWithSubcommands$1;
4280
+ const description = 'Diff scans related commands';
4281
+ diffScan.diffScan = {
4282
+ description,
4283
+ run: async (argv, importMeta, {
4284
+ parentName
4285
+ }) => {
4286
+ await (0, _meowWithSubcommands$1.meowWithSubcommands)({
4287
+ get: _get.get
4288
+ }, {
4289
+ argv,
4290
+ description,
4291
+ importMeta,
4292
+ name: parentName + ' diff-scan'
4293
+ });
4294
+ }
4295
+ };
4296
+
4297
+ var threatFeed$1 = {};
4298
+
4299
+ var _interopRequireDefault$1 = vendor.interopRequireDefault.default;
4300
+ Object.defineProperty(threatFeed$1, "__esModule", {
4301
+ value: true
4302
+ });
4303
+ threatFeed$1.threatFeed = void 0;
4304
+ var _blessed = require$$2$4;
4305
+ var _blessedContrib = require$$3$5;
4306
+ var _meow = _interopRequireDefault$1(vendor.build);
4307
+ var _ora = _interopRequireDefault$1(vendor.ora);
4308
+ var _flags = flags$1;
4309
+ var _apiHelpers = apiHelpers;
4310
+ var _errors$1 = sdk.errors;
4311
+ var _formatting = formatting;
4312
+ var _sdk = sdk.sdk;
4313
+ // @ts-ignore
4314
+
4315
+ const threatFeed = threatFeed$1.threatFeed = {
4316
+ description: 'Look up the threat feed',
4317
+ async run(argv, importMeta, {
4318
+ parentName
4319
+ }) {
4320
+ const name = parentName + ' threat-feed';
4321
+ const input = setupCommand(name, threatFeed.description, argv, importMeta);
4322
+ if (input) {
4323
+ const apiKey = (0, _sdk.getDefaultKey)();
4324
+ if (!apiKey) {
4325
+ 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.');
4326
+ }
4327
+ const spinner = (0, _ora.default)(`Looking up the threat feed \n`).start();
4328
+ await fetchThreatFeed(input, spinner, apiKey);
4329
+ }
4330
+ }
4331
+ };
4332
+ const threatFeedFlags = {
4333
+ perPage: {
4334
+ type: 'number',
4335
+ shortFlag: 'pp',
4336
+ default: 30,
4337
+ description: 'Number of items per page'
4338
+ },
4339
+ page: {
4340
+ type: 'string',
4341
+ shortFlag: 'p',
4342
+ default: '1',
4343
+ description: 'Page token'
4344
+ },
4345
+ direction: {
4346
+ type: 'string',
4347
+ shortFlag: 'd',
4348
+ default: 'desc',
4349
+ description: 'Order asc or desc by the createdAt attribute.'
4350
+ },
4351
+ filter: {
4352
+ type: 'string',
4353
+ shortFlag: 'f',
4354
+ default: 'mal',
4355
+ description: 'Filter what type of threats to return'
4356
+ }
4357
+ };
4358
+
4359
+ // Internal functions
4360
+
4361
+ function setupCommand(name, description, argv, importMeta) {
4362
+ const flags = {
4363
+ __proto__: null,
4364
+ ...threatFeedFlags,
4365
+ ..._flags.outputFlags
4366
+ };
4367
+ const cli = (0, _meow.default)(`
4368
+ Usage
4369
+ $ ${name}
4370
+
4371
+ Options
4372
+ ${(0, _formatting.printFlagList)(flags, 6)}
4373
+
4374
+ Examples
4375
+ $ ${name}
4376
+ $ ${name} --perPage=5 --page=2 --direction=asc --filter=joke
4377
+ `, {
4378
+ argv,
4379
+ description,
4380
+ importMeta,
4381
+ flags
4382
+ });
4383
+ const {
4384
+ json: outputJson,
4385
+ markdown: outputMarkdown,
4386
+ perPage: per_page,
4387
+ page,
4388
+ direction,
4389
+ filter
4390
+ } = cli.flags;
4391
+ return {
4392
+ outputJson,
4393
+ outputMarkdown,
4394
+ per_page,
4395
+ page,
4396
+ direction,
4397
+ filter
4398
+ };
4399
+ }
4400
+ async function fetchThreatFeed({
4401
+ per_page,
4402
+ page,
4403
+ direction,
4404
+ filter,
4405
+ outputJson
4406
+ }, spinner, apiKey) {
4407
+ const formattedQueryParams = formatQueryParams({
4408
+ per_page,
4409
+ page,
4410
+ direction,
4411
+ filter
4412
+ }).join('&');
4413
+ const response = await (0, _apiHelpers.queryAPI)(`threat-feed?${formattedQueryParams}`, apiKey);
4414
+ const data = await response.json();
4415
+ spinner.stop();
4416
+ if (outputJson) {
4417
+ return console.log(data);
4418
+ }
4419
+ const screen = _blessed.screen();
4420
+ const table = _blessedContrib.table({
4421
+ keys: 'true',
4422
+ fg: 'white',
4423
+ selectedFg: 'white',
4424
+ selectedBg: 'magenta',
4425
+ interactive: 'true',
4426
+ label: 'Threat feed',
4427
+ width: '100%',
4428
+ height: '100%',
4429
+ border: {
4430
+ type: 'line',
4431
+ fg: 'cyan'
4432
+ },
4433
+ columnSpacing: 3,
4434
+ //in chars
4435
+ columnWidth: [9, 30, 10, 17, 13, 100] /*in chars*/
4436
+ });
4437
+
4438
+ // allow control the table with the keyboard
4439
+ table.focus();
4440
+ screen.append(table);
4441
+ const formattedOutput = formatResults(data.results);
4442
+ table.setData({
4443
+ headers: ['Ecosystem', 'Name', 'Version', 'Threat type', 'Detected at', 'Details'],
4444
+ data: formattedOutput
4445
+ });
4446
+ screen.render();
4447
+ screen.key(['escape', 'q', 'C-c'], () => process.exit(0));
4448
+ }
4449
+ const formatResults = data => {
4450
+ return data.map(d => {
4451
+ const ecosystem = d.purl.split('pkg:')[1].split('/')[0];
4452
+ const name = d.purl.split('/')[1].split('@')[0];
4453
+ const version = d.purl.split('@')[1];
4454
+ const timeStart = new Date(d.createdAt).getMilliseconds();
4455
+ const timeEnd = Date.now();
4456
+ const diff = getHourDiff(timeStart, timeEnd);
4457
+ const hourDiff = diff > 0 ? `${diff} hours ago` : `${getMinDiff(timeStart, timeEnd)} minutes ago`;
4458
+ return [ecosystem, decodeURIComponent(name), version, d.threatType, hourDiff, d.locationHtmlUrl];
4459
+ });
4460
+ };
4461
+ const formatQueryParams = params => Object.entries(params).map(entry => `${entry[0]}=${entry[1]}`);
4462
+ const getHourDiff = (start, end) => Math.floor((end - start) / 3600000);
4463
+ const getMinDiff = (start, end) => Math.floor((end - start) / 60000);
4464
+
4465
+ (function (exports) {
4466
+
4467
+ Object.defineProperty(exports, "__esModule", {
4468
+ value: true
4469
+ });
4470
+ var _cdxgen = cdxgen;
4471
+ Object.keys(_cdxgen).forEach(function (key) {
4472
+ if (key === "default" || key === "__esModule") return;
4473
+ if (key in exports && exports[key] === _cdxgen[key]) return;
4474
+ Object.defineProperty(exports, key, {
4475
+ enumerable: true,
4476
+ get: function () {
4477
+ return _cdxgen[key];
4478
+ }
4479
+ });
4480
+ });
4481
+ var _info = info$1;
4482
+ Object.keys(_info).forEach(function (key) {
4483
+ if (key === "default" || key === "__esModule") return;
4484
+ if (key in exports && exports[key] === _info[key]) return;
4485
+ Object.defineProperty(exports, key, {
4486
+ enumerable: true,
4487
+ get: function () {
4488
+ return _info[key];
4489
+ }
4490
+ });
4491
+ });
4492
+ var _login = login;
4493
+ Object.keys(_login).forEach(function (key) {
4494
+ if (key === "default" || key === "__esModule") return;
4495
+ if (key in exports && exports[key] === _login[key]) return;
4496
+ Object.defineProperty(exports, key, {
4497
+ enumerable: true,
4498
+ get: function () {
4499
+ return _login[key];
4500
+ }
4501
+ });
4502
+ });
4503
+ var _logout = logout;
4504
+ Object.keys(_logout).forEach(function (key) {
4505
+ if (key === "default" || key === "__esModule") return;
4506
+ if (key in exports && exports[key] === _logout[key]) return;
4507
+ Object.defineProperty(exports, key, {
4508
+ enumerable: true,
4509
+ get: function () {
4510
+ return _logout[key];
4511
+ }
4512
+ });
4513
+ });
4514
+ var _npm = npm;
4515
+ Object.keys(_npm).forEach(function (key) {
4516
+ if (key === "default" || key === "__esModule") return;
4517
+ if (key in exports && exports[key] === _npm[key]) return;
4518
+ Object.defineProperty(exports, key, {
4519
+ enumerable: true,
4520
+ get: function () {
4521
+ return _npm[key];
4522
+ }
4523
+ });
4524
+ });
4525
+ var _npx = npx;
4526
+ Object.keys(_npx).forEach(function (key) {
4527
+ if (key === "default" || key === "__esModule") return;
4528
+ if (key in exports && exports[key] === _npx[key]) return;
4529
+ Object.defineProperty(exports, key, {
4530
+ enumerable: true,
4531
+ get: function () {
4532
+ return _npx[key];
4533
+ }
4534
+ });
4535
+ });
4536
+ var _optimize = optimize$1;
4537
+ Object.keys(_optimize).forEach(function (key) {
4538
+ if (key === "default" || key === "__esModule") return;
4539
+ if (key in exports && exports[key] === _optimize[key]) return;
4540
+ Object.defineProperty(exports, key, {
4541
+ enumerable: true,
4542
+ get: function () {
4543
+ return _optimize[key];
4544
+ }
4545
+ });
4546
+ });
4547
+ var _organization = organization;
4548
+ Object.keys(_organization).forEach(function (key) {
4549
+ if (key === "default" || key === "__esModule") return;
4550
+ if (key in exports && exports[key] === _organization[key]) return;
4551
+ Object.defineProperty(exports, key, {
4552
+ enumerable: true,
4553
+ get: function () {
4554
+ return _organization[key];
4555
+ }
4556
+ });
4557
+ });
4558
+ var _rawNpm = rawNpm$1;
4559
+ Object.keys(_rawNpm).forEach(function (key) {
4560
+ if (key === "default" || key === "__esModule") return;
4561
+ if (key in exports && exports[key] === _rawNpm[key]) return;
4562
+ Object.defineProperty(exports, key, {
4563
+ enumerable: true,
4564
+ get: function () {
4565
+ return _rawNpm[key];
4566
+ }
4567
+ });
4568
+ });
4569
+ var _rawNpx = rawNpx$1;
4570
+ Object.keys(_rawNpx).forEach(function (key) {
4571
+ if (key === "default" || key === "__esModule") return;
4572
+ if (key in exports && exports[key] === _rawNpx[key]) return;
4573
+ Object.defineProperty(exports, key, {
4574
+ enumerable: true,
4575
+ get: function () {
4576
+ return _rawNpx[key];
4577
+ }
4578
+ });
4579
+ });
4580
+ var _report = report;
4581
+ Object.keys(_report).forEach(function (key) {
4582
+ if (key === "default" || key === "__esModule") return;
4583
+ if (key in exports && exports[key] === _report[key]) return;
4584
+ Object.defineProperty(exports, key, {
4585
+ enumerable: true,
4586
+ get: function () {
4587
+ return _report[key];
4588
+ }
4589
+ });
4590
+ });
4591
+ var _wrapper = wrapper$1;
4592
+ Object.keys(_wrapper).forEach(function (key) {
4593
+ if (key === "default" || key === "__esModule") return;
4594
+ if (key in exports && exports[key] === _wrapper[key]) return;
4595
+ Object.defineProperty(exports, key, {
4596
+ enumerable: true,
4597
+ get: function () {
4598
+ return _wrapper[key];
4599
+ }
4600
+ });
4601
+ });
4602
+ var _scan = scan;
4603
+ Object.keys(_scan).forEach(function (key) {
4604
+ if (key === "default" || key === "__esModule") return;
4605
+ if (key in exports && exports[key] === _scan[key]) return;
4606
+ Object.defineProperty(exports, key, {
4607
+ enumerable: true,
4608
+ get: function () {
4609
+ return _scan[key];
4610
+ }
4611
+ });
4612
+ });
4613
+ var _auditLog = auditLog$1;
4614
+ Object.keys(_auditLog).forEach(function (key) {
4615
+ if (key === "default" || key === "__esModule") return;
4616
+ if (key in exports && exports[key] === _auditLog[key]) return;
4617
+ Object.defineProperty(exports, key, {
4618
+ enumerable: true,
4619
+ get: function () {
4620
+ return _auditLog[key];
4621
+ }
4622
+ });
4623
+ });
4624
+ var _repos = repos;
4625
+ Object.keys(_repos).forEach(function (key) {
4626
+ if (key === "default" || key === "__esModule") return;
4627
+ if (key in exports && exports[key] === _repos[key]) return;
4628
+ Object.defineProperty(exports, key, {
4629
+ enumerable: true,
4630
+ get: function () {
4631
+ return _repos[key];
4632
+ }
4633
+ });
4634
+ });
4635
+ var _dependencies = dependencies$1;
4636
+ Object.keys(_dependencies).forEach(function (key) {
4637
+ if (key === "default" || key === "__esModule") return;
4638
+ if (key in exports && exports[key] === _dependencies[key]) return;
4639
+ Object.defineProperty(exports, key, {
4640
+ enumerable: true,
4641
+ get: function () {
4642
+ return _dependencies[key];
4643
+ }
4644
+ });
4645
+ });
4646
+ var _analytics = analytics$1;
4647
+ Object.keys(_analytics).forEach(function (key) {
4648
+ if (key === "default" || key === "__esModule") return;
4649
+ if (key in exports && exports[key] === _analytics[key]) return;
4650
+ Object.defineProperty(exports, key, {
4651
+ enumerable: true,
4652
+ get: function () {
4653
+ return _analytics[key];
4654
+ }
4655
+ });
4656
+ });
4657
+ var _diffScan = diffScan;
4658
+ Object.keys(_diffScan).forEach(function (key) {
4659
+ if (key === "default" || key === "__esModule") return;
4660
+ if (key in exports && exports[key] === _diffScan[key]) return;
4661
+ Object.defineProperty(exports, key, {
4662
+ enumerable: true,
4663
+ get: function () {
4664
+ return _diffScan[key];
4665
+ }
4666
+ });
4667
+ });
4668
+ var _threatFeed = threatFeed$1;
4669
+ Object.keys(_threatFeed).forEach(function (key) {
4670
+ if (key === "default" || key === "__esModule") return;
4671
+ if (key in exports && exports[key] === _threatFeed[key]) return;
4672
+ Object.defineProperty(exports, key, {
4673
+ enumerable: true,
4674
+ get: function () {
4675
+ return _threatFeed[key];
4676
+ }
4677
+ });
4678
+ });
4679
+ } (commands));
4680
+
4681
+ var _interopRequireWildcard = vendor.interopRequireWildcard.default;
4682
+ var _interopRequireDefault = vendor.interopRequireDefault.default;
4683
+ var _nodeFs = require$$0;
4684
+ var _nodePath = require$$1;
4685
+ var _nodeUrl = require$$2$5;
4686
+ var _chalk = _interopRequireDefault(vendor.source);
4687
+ var _ponyCause = require$$6;
4688
+ var _updateNotifier = _interopRequireDefault(vendor.updateNotifier);
4689
+ var cliCommands = _interopRequireWildcard(commands, true);
4690
+ var _chalkMarkdown = sdk.chalkMarkdown;
4691
+ var _errors = sdk.errors;
4692
+ var _meowWithSubcommands = meowWithSubcommands$1;
4693
+ const distPath = __dirname;
4694
+ const rootPath = _nodePath.resolve(distPath, '..');
4695
+ const formattedCliCommands = Object.fromEntries(Object.entries(cliCommands).map(entry => {
4696
+ entry[0] = camelToHyphen(entry[0]);
4697
+ return entry;
4698
+ }));
4699
+ function camelToHyphen(str) {
4700
+ return str.replace(/[A-Z]+/g, '-$&').toLowerCase();
4701
+ }
4702
+
4703
+ // TODO: Add autocompletion using https://socket.dev/npm/package/omelette
4704
+ void (async () => {
4705
+ try {
4706
+ (0, _updateNotifier.default)({
4707
+ pkg: JSON.parse((0, _nodeFs.readFileSync)(_nodePath.join(rootPath, 'package.json'), 'utf8'))
4708
+ }).notify();
4709
+ } catch {}
4710
+ try {
4711
+ await (0, _meowWithSubcommands.meowWithSubcommands)(formattedCliCommands, {
4712
+ aliases: {
4713
+ ci: {
4714
+ description: 'Alias for "report create --view --strict"',
4715
+ argv: ['report', 'create', '--view', '--strict']
4716
+ }
4717
+ },
4718
+ argv: process.argv.slice(2),
4719
+ name: 'socket',
4720
+ importMeta: {
4721
+ url: `${(0, _nodeUrl.pathToFileURL)(__filename)}`
4722
+ }
4723
+ });
4724
+ } catch (err) {
4725
+ let errorTitle;
4726
+ let errorMessage = '';
4727
+ let errorBody;
4728
+ if (err instanceof _errors.AuthError) {
4729
+ errorTitle = 'Authentication error';
4730
+ errorMessage = err.message;
4731
+ } else if (err instanceof _errors.InputError) {
4732
+ errorTitle = 'Invalid input';
4733
+ errorMessage = err.message;
4734
+ errorBody = err.body;
4735
+ } else if (err instanceof Error) {
4736
+ errorTitle = 'Unexpected error';
4737
+ errorMessage = (0, _ponyCause.messageWithCauses)(err);
4738
+ errorBody = (0, _ponyCause.stackWithCauses)(err);
4739
+ } else {
4740
+ errorTitle = 'Unexpected error with no details';
4741
+ }
4742
+ console.error(`${_chalkMarkdown.logSymbols.error} ${_chalk.default.white.bgRed(errorTitle + ':')} ${errorMessage}`);
4743
+ if (errorBody) {
4744
+ console.error(`\n${errorBody}`);
4745
+ }
4746
+ process.exit(1);
4747
+ }
4748
+ })();
4749
+
4750
+ (function (exports) {
4751
+
4752
+ var _interopRequireWildcard = vendor.interopRequireWildcard.default;
4753
+ Object.defineProperty(exports, "__esModule", {
4754
+ value: true
4755
+ });
4756
+ var _exportNames = {};
4757
+ Object.defineProperty(exports, "default", {
4758
+ enumerable: true,
4759
+ get: function () {
4760
+ return _cli.default;
4761
+ }
4762
+ });
4763
+ var _cli = _interopRequireWildcard(cli, true);
4764
+ Object.keys(_cli).forEach(function (key) {
4765
+ if (key === "default" || key === "__esModule") return;
4766
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
4767
+ if (key in exports && exports[key] === _cli[key]) return;
4768
+ Object.defineProperty(exports, key, {
4769
+ enumerable: true,
4770
+ get: function () {
4771
+ return _cli[key];
4772
+ }
4773
+ });
4774
+ });
4775
+ } (cli$1));
4776
+
4777
+ module.exports = cli$1;