@socketsecurity/cli 0.11.0 → 0.12.0

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