@coana-tech/cli 14.12.42 → 14.12.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.mjs CHANGED
@@ -47599,8 +47599,340 @@ var require_es_set_tostringtag = __commonJS({
47599
47599
  }
47600
47600
  });
47601
47601
 
47602
- // ../../node_modules/.pnpm/form-data@4.0.2/node_modules/form-data/lib/populate.js
47602
+ // ../../node_modules/.pnpm/form-data@4.0.4/node_modules/form-data/lib/populate.js
47603
47603
  var require_populate = __commonJS({
47604
+ "../../node_modules/.pnpm/form-data@4.0.4/node_modules/form-data/lib/populate.js"(exports2, module2) {
47605
+ "use strict";
47606
+ module2.exports = function(dst, src) {
47607
+ Object.keys(src).forEach(function(prop2) {
47608
+ dst[prop2] = dst[prop2] || src[prop2];
47609
+ });
47610
+ return dst;
47611
+ };
47612
+ }
47613
+ });
47614
+
47615
+ // ../../node_modules/.pnpm/form-data@4.0.4/node_modules/form-data/lib/form_data.js
47616
+ var require_form_data = __commonJS({
47617
+ "../../node_modules/.pnpm/form-data@4.0.4/node_modules/form-data/lib/form_data.js"(exports2, module2) {
47618
+ "use strict";
47619
+ var CombinedStream = require_combined_stream();
47620
+ var util5 = __require("util");
47621
+ var path2 = __require("path");
47622
+ var http2 = __require("http");
47623
+ var https2 = __require("https");
47624
+ var parseUrl = __require("url").parse;
47625
+ var fs = __require("fs");
47626
+ var Stream2 = __require("stream").Stream;
47627
+ var crypto7 = __require("crypto");
47628
+ var mime = require_mime_types();
47629
+ var asynckit = require_asynckit();
47630
+ var setToStringTag = require_es_set_tostringtag();
47631
+ var hasOwn2 = require_hasown();
47632
+ var populate = require_populate();
47633
+ function FormData4(options) {
47634
+ if (!(this instanceof FormData4)) {
47635
+ return new FormData4(options);
47636
+ }
47637
+ this._overheadLength = 0;
47638
+ this._valueLength = 0;
47639
+ this._valuesToMeasure = [];
47640
+ CombinedStream.call(this);
47641
+ options = options || {};
47642
+ for (var option in options) {
47643
+ this[option] = options[option];
47644
+ }
47645
+ }
47646
+ util5.inherits(FormData4, CombinedStream);
47647
+ FormData4.LINE_BREAK = "\r\n";
47648
+ FormData4.DEFAULT_CONTENT_TYPE = "application/octet-stream";
47649
+ FormData4.prototype.append = function(field, value, options) {
47650
+ options = options || {};
47651
+ if (typeof options === "string") {
47652
+ options = { filename: options };
47653
+ }
47654
+ var append4 = CombinedStream.prototype.append.bind(this);
47655
+ if (typeof value === "number" || value == null) {
47656
+ value = String(value);
47657
+ }
47658
+ if (Array.isArray(value)) {
47659
+ this._error(new Error("Arrays are not supported."));
47660
+ return;
47661
+ }
47662
+ var header = this._multiPartHeader(field, value, options);
47663
+ var footer = this._multiPartFooter();
47664
+ append4(header);
47665
+ append4(value);
47666
+ append4(footer);
47667
+ this._trackLength(header, value, options);
47668
+ };
47669
+ FormData4.prototype._trackLength = function(header, value, options) {
47670
+ var valueLength = 0;
47671
+ if (options.knownLength != null) {
47672
+ valueLength += Number(options.knownLength);
47673
+ } else if (Buffer.isBuffer(value)) {
47674
+ valueLength = value.length;
47675
+ } else if (typeof value === "string") {
47676
+ valueLength = Buffer.byteLength(value);
47677
+ }
47678
+ this._valueLength += valueLength;
47679
+ this._overheadLength += Buffer.byteLength(header) + FormData4.LINE_BREAK.length;
47680
+ if (!value || !value.path && !(value.readable && hasOwn2(value, "httpVersion")) && !(value instanceof Stream2)) {
47681
+ return;
47682
+ }
47683
+ if (!options.knownLength) {
47684
+ this._valuesToMeasure.push(value);
47685
+ }
47686
+ };
47687
+ FormData4.prototype._lengthRetriever = function(value, callback) {
47688
+ if (hasOwn2(value, "fd")) {
47689
+ if (value.end != void 0 && value.end != Infinity && value.start != void 0) {
47690
+ callback(null, value.end + 1 - (value.start ? value.start : 0));
47691
+ } else {
47692
+ fs.stat(value.path, function(err, stat4) {
47693
+ if (err) {
47694
+ callback(err);
47695
+ return;
47696
+ }
47697
+ var fileSize = stat4.size - (value.start ? value.start : 0);
47698
+ callback(null, fileSize);
47699
+ });
47700
+ }
47701
+ } else if (hasOwn2(value, "httpVersion")) {
47702
+ callback(null, Number(value.headers["content-length"]));
47703
+ } else if (hasOwn2(value, "httpModule")) {
47704
+ value.on("response", function(response) {
47705
+ value.pause();
47706
+ callback(null, Number(response.headers["content-length"]));
47707
+ });
47708
+ value.resume();
47709
+ } else {
47710
+ callback("Unknown stream");
47711
+ }
47712
+ };
47713
+ FormData4.prototype._multiPartHeader = function(field, value, options) {
47714
+ if (typeof options.header === "string") {
47715
+ return options.header;
47716
+ }
47717
+ var contentDisposition = this._getContentDisposition(value, options);
47718
+ var contentType = this._getContentType(value, options);
47719
+ var contents2 = "";
47720
+ var headers = {
47721
+ // add custom disposition as third element or keep it two elements if not
47722
+ "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []),
47723
+ // if no content type. allow it to be empty array
47724
+ "Content-Type": [].concat(contentType || [])
47725
+ };
47726
+ if (typeof options.header === "object") {
47727
+ populate(headers, options.header);
47728
+ }
47729
+ var header;
47730
+ for (var prop2 in headers) {
47731
+ if (hasOwn2(headers, prop2)) {
47732
+ header = headers[prop2];
47733
+ if (header == null) {
47734
+ continue;
47735
+ }
47736
+ if (!Array.isArray(header)) {
47737
+ header = [header];
47738
+ }
47739
+ if (header.length) {
47740
+ contents2 += prop2 + ": " + header.join("; ") + FormData4.LINE_BREAK;
47741
+ }
47742
+ }
47743
+ }
47744
+ return "--" + this.getBoundary() + FormData4.LINE_BREAK + contents2 + FormData4.LINE_BREAK;
47745
+ };
47746
+ FormData4.prototype._getContentDisposition = function(value, options) {
47747
+ var filename;
47748
+ if (typeof options.filepath === "string") {
47749
+ filename = path2.normalize(options.filepath).replace(/\\/g, "/");
47750
+ } else if (options.filename || value && (value.name || value.path)) {
47751
+ filename = path2.basename(options.filename || value && (value.name || value.path));
47752
+ } else if (value && value.readable && hasOwn2(value, "httpVersion")) {
47753
+ filename = path2.basename(value.client._httpMessage.path || "");
47754
+ }
47755
+ if (filename) {
47756
+ return 'filename="' + filename + '"';
47757
+ }
47758
+ };
47759
+ FormData4.prototype._getContentType = function(value, options) {
47760
+ var contentType = options.contentType;
47761
+ if (!contentType && value && value.name) {
47762
+ contentType = mime.lookup(value.name);
47763
+ }
47764
+ if (!contentType && value && value.path) {
47765
+ contentType = mime.lookup(value.path);
47766
+ }
47767
+ if (!contentType && value && value.readable && hasOwn2(value, "httpVersion")) {
47768
+ contentType = value.headers["content-type"];
47769
+ }
47770
+ if (!contentType && (options.filepath || options.filename)) {
47771
+ contentType = mime.lookup(options.filepath || options.filename);
47772
+ }
47773
+ if (!contentType && value && typeof value === "object") {
47774
+ contentType = FormData4.DEFAULT_CONTENT_TYPE;
47775
+ }
47776
+ return contentType;
47777
+ };
47778
+ FormData4.prototype._multiPartFooter = function() {
47779
+ return function(next2) {
47780
+ var footer = FormData4.LINE_BREAK;
47781
+ var lastPart = this._streams.length === 0;
47782
+ if (lastPart) {
47783
+ footer += this._lastBoundary();
47784
+ }
47785
+ next2(footer);
47786
+ }.bind(this);
47787
+ };
47788
+ FormData4.prototype._lastBoundary = function() {
47789
+ return "--" + this.getBoundary() + "--" + FormData4.LINE_BREAK;
47790
+ };
47791
+ FormData4.prototype.getHeaders = function(userHeaders) {
47792
+ var header;
47793
+ var formHeaders = {
47794
+ "content-type": "multipart/form-data; boundary=" + this.getBoundary()
47795
+ };
47796
+ for (header in userHeaders) {
47797
+ if (hasOwn2(userHeaders, header)) {
47798
+ formHeaders[header.toLowerCase()] = userHeaders[header];
47799
+ }
47800
+ }
47801
+ return formHeaders;
47802
+ };
47803
+ FormData4.prototype.setBoundary = function(boundary) {
47804
+ if (typeof boundary !== "string") {
47805
+ throw new TypeError("FormData boundary must be a string");
47806
+ }
47807
+ this._boundary = boundary;
47808
+ };
47809
+ FormData4.prototype.getBoundary = function() {
47810
+ if (!this._boundary) {
47811
+ this._generateBoundary();
47812
+ }
47813
+ return this._boundary;
47814
+ };
47815
+ FormData4.prototype.getBuffer = function() {
47816
+ var dataBuffer = new Buffer.alloc(0);
47817
+ var boundary = this.getBoundary();
47818
+ for (var i7 = 0, len = this._streams.length; i7 < len; i7++) {
47819
+ if (typeof this._streams[i7] !== "function") {
47820
+ if (Buffer.isBuffer(this._streams[i7])) {
47821
+ dataBuffer = Buffer.concat([dataBuffer, this._streams[i7]]);
47822
+ } else {
47823
+ dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i7])]);
47824
+ }
47825
+ if (typeof this._streams[i7] !== "string" || this._streams[i7].substring(2, boundary.length + 2) !== boundary) {
47826
+ dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData4.LINE_BREAK)]);
47827
+ }
47828
+ }
47829
+ }
47830
+ return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]);
47831
+ };
47832
+ FormData4.prototype._generateBoundary = function() {
47833
+ this._boundary = "--------------------------" + crypto7.randomBytes(12).toString("hex");
47834
+ };
47835
+ FormData4.prototype.getLengthSync = function() {
47836
+ var knownLength = this._overheadLength + this._valueLength;
47837
+ if (this._streams.length) {
47838
+ knownLength += this._lastBoundary().length;
47839
+ }
47840
+ if (!this.hasKnownLength()) {
47841
+ this._error(new Error("Cannot calculate proper length in synchronous way."));
47842
+ }
47843
+ return knownLength;
47844
+ };
47845
+ FormData4.prototype.hasKnownLength = function() {
47846
+ var hasKnownLength = true;
47847
+ if (this._valuesToMeasure.length) {
47848
+ hasKnownLength = false;
47849
+ }
47850
+ return hasKnownLength;
47851
+ };
47852
+ FormData4.prototype.getLength = function(cb) {
47853
+ var knownLength = this._overheadLength + this._valueLength;
47854
+ if (this._streams.length) {
47855
+ knownLength += this._lastBoundary().length;
47856
+ }
47857
+ if (!this._valuesToMeasure.length) {
47858
+ process.nextTick(cb.bind(this, null, knownLength));
47859
+ return;
47860
+ }
47861
+ asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
47862
+ if (err) {
47863
+ cb(err);
47864
+ return;
47865
+ }
47866
+ values.forEach(function(length) {
47867
+ knownLength += length;
47868
+ });
47869
+ cb(null, knownLength);
47870
+ });
47871
+ };
47872
+ FormData4.prototype.submit = function(params, cb) {
47873
+ var request;
47874
+ var options;
47875
+ var defaults3 = { method: "post" };
47876
+ if (typeof params === "string") {
47877
+ params = parseUrl(params);
47878
+ options = populate({
47879
+ port: params.port,
47880
+ path: params.pathname,
47881
+ host: params.hostname,
47882
+ protocol: params.protocol
47883
+ }, defaults3);
47884
+ } else {
47885
+ options = populate(params, defaults3);
47886
+ if (!options.port) {
47887
+ options.port = options.protocol === "https:" ? 443 : 80;
47888
+ }
47889
+ }
47890
+ options.headers = this.getHeaders(params.headers);
47891
+ if (options.protocol === "https:") {
47892
+ request = https2.request(options);
47893
+ } else {
47894
+ request = http2.request(options);
47895
+ }
47896
+ this.getLength(function(err, length) {
47897
+ if (err && err !== "Unknown stream") {
47898
+ this._error(err);
47899
+ return;
47900
+ }
47901
+ if (length) {
47902
+ request.setHeader("Content-Length", length);
47903
+ }
47904
+ this.pipe(request);
47905
+ if (cb) {
47906
+ var onResponse;
47907
+ var callback = function(error, responce) {
47908
+ request.removeListener("error", callback);
47909
+ request.removeListener("response", onResponse);
47910
+ return cb.call(this, error, responce);
47911
+ };
47912
+ onResponse = callback.bind(this, null);
47913
+ request.on("error", callback);
47914
+ request.on("response", onResponse);
47915
+ }
47916
+ }.bind(this));
47917
+ return request;
47918
+ };
47919
+ FormData4.prototype._error = function(err) {
47920
+ if (!this.error) {
47921
+ this.error = err;
47922
+ this.pause();
47923
+ this.emit("error", err);
47924
+ }
47925
+ };
47926
+ FormData4.prototype.toString = function() {
47927
+ return "[object FormData]";
47928
+ };
47929
+ setToStringTag(FormData4, "FormData");
47930
+ module2.exports = FormData4;
47931
+ }
47932
+ });
47933
+
47934
+ // ../../node_modules/.pnpm/form-data@4.0.2/node_modules/form-data/lib/populate.js
47935
+ var require_populate2 = __commonJS({
47604
47936
  "../../node_modules/.pnpm/form-data@4.0.2/node_modules/form-data/lib/populate.js"(exports2, module2) {
47605
47937
  module2.exports = function(dst, src) {
47606
47938
  Object.keys(src).forEach(function(prop2) {
@@ -47612,7 +47944,7 @@ var require_populate = __commonJS({
47612
47944
  });
47613
47945
 
47614
47946
  // ../../node_modules/.pnpm/form-data@4.0.2/node_modules/form-data/lib/form_data.js
47615
- var require_form_data = __commonJS({
47947
+ var require_form_data2 = __commonJS({
47616
47948
  "../../node_modules/.pnpm/form-data@4.0.2/node_modules/form-data/lib/form_data.js"(exports2, module2) {
47617
47949
  var CombinedStream = require_combined_stream();
47618
47950
  var util5 = __require("util");
@@ -47625,7 +47957,7 @@ var require_form_data = __commonJS({
47625
47957
  var mime = require_mime_types();
47626
47958
  var asynckit = require_asynckit();
47627
47959
  var setToStringTag = require_es_set_tostringtag();
47628
- var populate = require_populate();
47960
+ var populate = require_populate2();
47629
47961
  module2.exports = FormData4;
47630
47962
  util5.inherits(FormData4, CombinedStream);
47631
47963
  function FormData4(options) {
@@ -49261,338 +49593,6 @@ var require_follow_redirects = __commonJS({
49261
49593
  }
49262
49594
  });
49263
49595
 
49264
- // ../../node_modules/.pnpm/form-data@4.0.4/node_modules/form-data/lib/populate.js
49265
- var require_populate2 = __commonJS({
49266
- "../../node_modules/.pnpm/form-data@4.0.4/node_modules/form-data/lib/populate.js"(exports2, module2) {
49267
- "use strict";
49268
- module2.exports = function(dst, src) {
49269
- Object.keys(src).forEach(function(prop2) {
49270
- dst[prop2] = dst[prop2] || src[prop2];
49271
- });
49272
- return dst;
49273
- };
49274
- }
49275
- });
49276
-
49277
- // ../../node_modules/.pnpm/form-data@4.0.4/node_modules/form-data/lib/form_data.js
49278
- var require_form_data2 = __commonJS({
49279
- "../../node_modules/.pnpm/form-data@4.0.4/node_modules/form-data/lib/form_data.js"(exports2, module2) {
49280
- "use strict";
49281
- var CombinedStream = require_combined_stream();
49282
- var util5 = __require("util");
49283
- var path2 = __require("path");
49284
- var http2 = __require("http");
49285
- var https2 = __require("https");
49286
- var parseUrl = __require("url").parse;
49287
- var fs = __require("fs");
49288
- var Stream2 = __require("stream").Stream;
49289
- var crypto7 = __require("crypto");
49290
- var mime = require_mime_types();
49291
- var asynckit = require_asynckit();
49292
- var setToStringTag = require_es_set_tostringtag();
49293
- var hasOwn2 = require_hasown();
49294
- var populate = require_populate2();
49295
- function FormData4(options) {
49296
- if (!(this instanceof FormData4)) {
49297
- return new FormData4(options);
49298
- }
49299
- this._overheadLength = 0;
49300
- this._valueLength = 0;
49301
- this._valuesToMeasure = [];
49302
- CombinedStream.call(this);
49303
- options = options || {};
49304
- for (var option in options) {
49305
- this[option] = options[option];
49306
- }
49307
- }
49308
- util5.inherits(FormData4, CombinedStream);
49309
- FormData4.LINE_BREAK = "\r\n";
49310
- FormData4.DEFAULT_CONTENT_TYPE = "application/octet-stream";
49311
- FormData4.prototype.append = function(field, value, options) {
49312
- options = options || {};
49313
- if (typeof options === "string") {
49314
- options = { filename: options };
49315
- }
49316
- var append4 = CombinedStream.prototype.append.bind(this);
49317
- if (typeof value === "number" || value == null) {
49318
- value = String(value);
49319
- }
49320
- if (Array.isArray(value)) {
49321
- this._error(new Error("Arrays are not supported."));
49322
- return;
49323
- }
49324
- var header = this._multiPartHeader(field, value, options);
49325
- var footer = this._multiPartFooter();
49326
- append4(header);
49327
- append4(value);
49328
- append4(footer);
49329
- this._trackLength(header, value, options);
49330
- };
49331
- FormData4.prototype._trackLength = function(header, value, options) {
49332
- var valueLength = 0;
49333
- if (options.knownLength != null) {
49334
- valueLength += Number(options.knownLength);
49335
- } else if (Buffer.isBuffer(value)) {
49336
- valueLength = value.length;
49337
- } else if (typeof value === "string") {
49338
- valueLength = Buffer.byteLength(value);
49339
- }
49340
- this._valueLength += valueLength;
49341
- this._overheadLength += Buffer.byteLength(header) + FormData4.LINE_BREAK.length;
49342
- if (!value || !value.path && !(value.readable && hasOwn2(value, "httpVersion")) && !(value instanceof Stream2)) {
49343
- return;
49344
- }
49345
- if (!options.knownLength) {
49346
- this._valuesToMeasure.push(value);
49347
- }
49348
- };
49349
- FormData4.prototype._lengthRetriever = function(value, callback) {
49350
- if (hasOwn2(value, "fd")) {
49351
- if (value.end != void 0 && value.end != Infinity && value.start != void 0) {
49352
- callback(null, value.end + 1 - (value.start ? value.start : 0));
49353
- } else {
49354
- fs.stat(value.path, function(err, stat4) {
49355
- if (err) {
49356
- callback(err);
49357
- return;
49358
- }
49359
- var fileSize = stat4.size - (value.start ? value.start : 0);
49360
- callback(null, fileSize);
49361
- });
49362
- }
49363
- } else if (hasOwn2(value, "httpVersion")) {
49364
- callback(null, Number(value.headers["content-length"]));
49365
- } else if (hasOwn2(value, "httpModule")) {
49366
- value.on("response", function(response) {
49367
- value.pause();
49368
- callback(null, Number(response.headers["content-length"]));
49369
- });
49370
- value.resume();
49371
- } else {
49372
- callback("Unknown stream");
49373
- }
49374
- };
49375
- FormData4.prototype._multiPartHeader = function(field, value, options) {
49376
- if (typeof options.header === "string") {
49377
- return options.header;
49378
- }
49379
- var contentDisposition = this._getContentDisposition(value, options);
49380
- var contentType = this._getContentType(value, options);
49381
- var contents2 = "";
49382
- var headers = {
49383
- // add custom disposition as third element or keep it two elements if not
49384
- "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []),
49385
- // if no content type. allow it to be empty array
49386
- "Content-Type": [].concat(contentType || [])
49387
- };
49388
- if (typeof options.header === "object") {
49389
- populate(headers, options.header);
49390
- }
49391
- var header;
49392
- for (var prop2 in headers) {
49393
- if (hasOwn2(headers, prop2)) {
49394
- header = headers[prop2];
49395
- if (header == null) {
49396
- continue;
49397
- }
49398
- if (!Array.isArray(header)) {
49399
- header = [header];
49400
- }
49401
- if (header.length) {
49402
- contents2 += prop2 + ": " + header.join("; ") + FormData4.LINE_BREAK;
49403
- }
49404
- }
49405
- }
49406
- return "--" + this.getBoundary() + FormData4.LINE_BREAK + contents2 + FormData4.LINE_BREAK;
49407
- };
49408
- FormData4.prototype._getContentDisposition = function(value, options) {
49409
- var filename;
49410
- if (typeof options.filepath === "string") {
49411
- filename = path2.normalize(options.filepath).replace(/\\/g, "/");
49412
- } else if (options.filename || value && (value.name || value.path)) {
49413
- filename = path2.basename(options.filename || value && (value.name || value.path));
49414
- } else if (value && value.readable && hasOwn2(value, "httpVersion")) {
49415
- filename = path2.basename(value.client._httpMessage.path || "");
49416
- }
49417
- if (filename) {
49418
- return 'filename="' + filename + '"';
49419
- }
49420
- };
49421
- FormData4.prototype._getContentType = function(value, options) {
49422
- var contentType = options.contentType;
49423
- if (!contentType && value && value.name) {
49424
- contentType = mime.lookup(value.name);
49425
- }
49426
- if (!contentType && value && value.path) {
49427
- contentType = mime.lookup(value.path);
49428
- }
49429
- if (!contentType && value && value.readable && hasOwn2(value, "httpVersion")) {
49430
- contentType = value.headers["content-type"];
49431
- }
49432
- if (!contentType && (options.filepath || options.filename)) {
49433
- contentType = mime.lookup(options.filepath || options.filename);
49434
- }
49435
- if (!contentType && value && typeof value === "object") {
49436
- contentType = FormData4.DEFAULT_CONTENT_TYPE;
49437
- }
49438
- return contentType;
49439
- };
49440
- FormData4.prototype._multiPartFooter = function() {
49441
- return function(next2) {
49442
- var footer = FormData4.LINE_BREAK;
49443
- var lastPart = this._streams.length === 0;
49444
- if (lastPart) {
49445
- footer += this._lastBoundary();
49446
- }
49447
- next2(footer);
49448
- }.bind(this);
49449
- };
49450
- FormData4.prototype._lastBoundary = function() {
49451
- return "--" + this.getBoundary() + "--" + FormData4.LINE_BREAK;
49452
- };
49453
- FormData4.prototype.getHeaders = function(userHeaders) {
49454
- var header;
49455
- var formHeaders = {
49456
- "content-type": "multipart/form-data; boundary=" + this.getBoundary()
49457
- };
49458
- for (header in userHeaders) {
49459
- if (hasOwn2(userHeaders, header)) {
49460
- formHeaders[header.toLowerCase()] = userHeaders[header];
49461
- }
49462
- }
49463
- return formHeaders;
49464
- };
49465
- FormData4.prototype.setBoundary = function(boundary) {
49466
- if (typeof boundary !== "string") {
49467
- throw new TypeError("FormData boundary must be a string");
49468
- }
49469
- this._boundary = boundary;
49470
- };
49471
- FormData4.prototype.getBoundary = function() {
49472
- if (!this._boundary) {
49473
- this._generateBoundary();
49474
- }
49475
- return this._boundary;
49476
- };
49477
- FormData4.prototype.getBuffer = function() {
49478
- var dataBuffer = new Buffer.alloc(0);
49479
- var boundary = this.getBoundary();
49480
- for (var i7 = 0, len = this._streams.length; i7 < len; i7++) {
49481
- if (typeof this._streams[i7] !== "function") {
49482
- if (Buffer.isBuffer(this._streams[i7])) {
49483
- dataBuffer = Buffer.concat([dataBuffer, this._streams[i7]]);
49484
- } else {
49485
- dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i7])]);
49486
- }
49487
- if (typeof this._streams[i7] !== "string" || this._streams[i7].substring(2, boundary.length + 2) !== boundary) {
49488
- dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData4.LINE_BREAK)]);
49489
- }
49490
- }
49491
- }
49492
- return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]);
49493
- };
49494
- FormData4.prototype._generateBoundary = function() {
49495
- this._boundary = "--------------------------" + crypto7.randomBytes(12).toString("hex");
49496
- };
49497
- FormData4.prototype.getLengthSync = function() {
49498
- var knownLength = this._overheadLength + this._valueLength;
49499
- if (this._streams.length) {
49500
- knownLength += this._lastBoundary().length;
49501
- }
49502
- if (!this.hasKnownLength()) {
49503
- this._error(new Error("Cannot calculate proper length in synchronous way."));
49504
- }
49505
- return knownLength;
49506
- };
49507
- FormData4.prototype.hasKnownLength = function() {
49508
- var hasKnownLength = true;
49509
- if (this._valuesToMeasure.length) {
49510
- hasKnownLength = false;
49511
- }
49512
- return hasKnownLength;
49513
- };
49514
- FormData4.prototype.getLength = function(cb) {
49515
- var knownLength = this._overheadLength + this._valueLength;
49516
- if (this._streams.length) {
49517
- knownLength += this._lastBoundary().length;
49518
- }
49519
- if (!this._valuesToMeasure.length) {
49520
- process.nextTick(cb.bind(this, null, knownLength));
49521
- return;
49522
- }
49523
- asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
49524
- if (err) {
49525
- cb(err);
49526
- return;
49527
- }
49528
- values.forEach(function(length) {
49529
- knownLength += length;
49530
- });
49531
- cb(null, knownLength);
49532
- });
49533
- };
49534
- FormData4.prototype.submit = function(params, cb) {
49535
- var request;
49536
- var options;
49537
- var defaults3 = { method: "post" };
49538
- if (typeof params === "string") {
49539
- params = parseUrl(params);
49540
- options = populate({
49541
- port: params.port,
49542
- path: params.pathname,
49543
- host: params.hostname,
49544
- protocol: params.protocol
49545
- }, defaults3);
49546
- } else {
49547
- options = populate(params, defaults3);
49548
- if (!options.port) {
49549
- options.port = options.protocol === "https:" ? 443 : 80;
49550
- }
49551
- }
49552
- options.headers = this.getHeaders(params.headers);
49553
- if (options.protocol === "https:") {
49554
- request = https2.request(options);
49555
- } else {
49556
- request = http2.request(options);
49557
- }
49558
- this.getLength(function(err, length) {
49559
- if (err && err !== "Unknown stream") {
49560
- this._error(err);
49561
- return;
49562
- }
49563
- if (length) {
49564
- request.setHeader("Content-Length", length);
49565
- }
49566
- this.pipe(request);
49567
- if (cb) {
49568
- var onResponse;
49569
- var callback = function(error, responce) {
49570
- request.removeListener("error", callback);
49571
- request.removeListener("response", onResponse);
49572
- return cb.call(this, error, responce);
49573
- };
49574
- onResponse = callback.bind(this, null);
49575
- request.on("error", callback);
49576
- request.on("response", onResponse);
49577
- }
49578
- }.bind(this));
49579
- return request;
49580
- };
49581
- FormData4.prototype._error = function(err) {
49582
- if (!this.error) {
49583
- this.error = err;
49584
- this.pause();
49585
- this.emit("error", err);
49586
- }
49587
- };
49588
- FormData4.prototype.toString = function() {
49589
- return "[object FormData]";
49590
- };
49591
- setToStringTag(FormData4, "FormData");
49592
- module2.exports = FormData4;
49593
- }
49594
- });
49595
-
49596
49596
  // ../../node_modules/.pnpm/is-retry-allowed@2.2.0/node_modules/is-retry-allowed/index.js
49597
49597
  var require_is_retry_allowed = __commonJS({
49598
49598
  "../../node_modules/.pnpm/is-retry-allowed@2.2.0/node_modules/is-retry-allowed/index.js"(exports2, module2) {
@@ -184569,7 +184569,7 @@ var require_p_retry = __commonJS({
184569
184569
  var require_axios = __commonJS({
184570
184570
  "../../node_modules/.pnpm/axios@1.9.0/node_modules/axios/dist/node/axios.cjs"(exports2, module2) {
184571
184571
  "use strict";
184572
- var FormData$1 = require_form_data2();
184572
+ var FormData$1 = require_form_data();
184573
184573
  var crypto7 = __require("crypto");
184574
184574
  var url2 = __require("url");
184575
184575
  var proxyFromEnv2 = require_proxy_from_env();
@@ -195318,6 +195318,20 @@ function resolveConflicts2(ecosystem, patches, ctxt) {
195318
195318
  return resolvedPatches;
195319
195319
  }
195320
195320
 
195321
+ // ../utils/src/dashboard-api/socket-api.ts
195322
+ var import_form_data2 = __toESM(require_form_data(), 1);
195323
+ import { readFile as readFile8 } from "node:fs/promises";
195324
+ import { join as join5, relative as relative3, resolve as resolve8 } from "node:path";
195325
+
195326
+ // ../web-compat-utils/src/ghsa.ts
195327
+ function extractGHSAIdFromUrl(url2) {
195328
+ const match2 = url2.match(/(GHSA-[a-z0-9-]+)/);
195329
+ if (match2) {
195330
+ return match2[1];
195331
+ }
195332
+ return void 0;
195333
+ }
195334
+
195321
195335
  // ../../node_modules/.pnpm/axios@1.8.2/node_modules/axios/lib/helpers/bind.js
195322
195336
  function bind(fn2, thisArg) {
195323
195337
  return function wrap2() {
@@ -195763,7 +195777,7 @@ AxiosError.from = (error, code, config3, request, response, customProps) => {
195763
195777
  var AxiosError_default = AxiosError;
195764
195778
 
195765
195779
  // ../../node_modules/.pnpm/axios@1.8.2/node_modules/axios/lib/platform/node/classes/FormData.js
195766
- var import_form_data = __toESM(require_form_data(), 1);
195780
+ var import_form_data = __toESM(require_form_data2(), 1);
195767
195781
  var FormData_default = import_form_data.default;
195768
195782
 
195769
195783
  // ../../node_modules/.pnpm/axios@1.8.2/node_modules/axios/lib/helpers/toFormData.js
@@ -198616,20 +198630,6 @@ var {
198616
198630
  mergeConfig: mergeConfig2
198617
198631
  } = axios_default;
198618
198632
 
198619
- // ../utils/src/dashboard-api/socket-api.ts
198620
- var import_form_data2 = __toESM(require_form_data2(), 1);
198621
- import { readFile as readFile8 } from "node:fs/promises";
198622
- import { join as join5, relative as relative3, resolve as resolve8 } from "node:path";
198623
-
198624
- // ../web-compat-utils/src/ghsa.ts
198625
- function extractGHSAIdFromUrl(url2) {
198626
- const match2 = url2.match(/(GHSA-[a-z0-9-]+)/);
198627
- if (match2) {
198628
- return match2[1];
198629
- }
198630
- return void 0;
198631
- }
198632
-
198633
198633
  // ../../node_modules/.pnpm/axios-retry@4.1.0_axios@1.8.2/node_modules/axios-retry/dist/esm/index.js
198634
198634
  var import_is_retry_allowed = __toESM(require_is_retry_allowed(), 1);
198635
198635
  var namespace = "axios-retry";
@@ -198822,7 +198822,7 @@ function prettyPrintAxiosError(error) {
198822
198822
  printableHeaders = Object.fromEntries(
198823
198823
  Object.entries(headers).map(([key, value]) => {
198824
198824
  try {
198825
- if (key === "api-key" || key === "apiKey") {
198825
+ if (key === "api-key" || key === "apiKey" || key === "Authorization") {
198826
198826
  return [key, "REDACTED"];
198827
198827
  }
198828
198828
  if (Array.isArray(value)) {
@@ -198907,7 +198907,7 @@ async function createSocketTier1Scan(cliOptions, coanaCliVersion) {
198907
198907
  };
198908
198908
  return (await axios2.put(url2, data2, { headers: getAuthHeaders() })).data;
198909
198909
  } catch (error) {
198910
- handleError(error, "Error creating tier 1 scan", false);
198910
+ handleError(error, "Error creating tier 1 scan", true);
198911
198911
  throw new Error("we should never reach this point");
198912
198912
  }
198913
198913
  }
@@ -199048,7 +199048,7 @@ async function getLatestBucketsSocket(subprojectPath, workspacePath) {
199048
199048
  }
199049
199049
  logger.debug(
199050
199050
  "Unable to retrieve cached analysis configuration. Will continue with default configuration.",
199051
- error?.message
199051
+ error.message
199052
199052
  );
199053
199053
  return void 0;
199054
199054
  }
@@ -199064,7 +199064,7 @@ async function useSocketComputeFixEndpoint(autofixRunId, artifacts, vulnerableAr
199064
199064
  };
199065
199065
  return (await axios2.post(url2, data2, { headers: getAuthHeaders() })).data;
199066
199066
  } catch (error) {
199067
- logger.error("Request to compute fixes failed:", error);
199067
+ handleError(error, "Request to compute fixes failed", false);
199068
199068
  return {
199069
199069
  type: "error",
199070
199070
  message: "Error during computation"
@@ -199078,8 +199078,8 @@ async function augmentArtifactsWithVulnerabilities(components) {
199078
199078
  const augmentedArtifacts = (await axios2.post(url2, data2, { headers: getAuthHeaders() })).data;
199079
199079
  return parseSocketResponse(augmentedArtifacts);
199080
199080
  } catch (e) {
199081
- logger.error("Failed to scan for vulnerabilities in socket mode", e);
199082
- throw e;
199081
+ handleError(e, "Failed to scan for vulnerabilities in socket mode", true);
199082
+ throw new Error("we should never reach this point");
199083
199083
  }
199084
199084
  }
199085
199085
  async function fetchManifestFilesFromManifestsTarHash(manifestsTarHash) {
@@ -199087,10 +199087,8 @@ async function fetchManifestFilesFromManifestsTarHash(manifestsTarHash) {
199087
199087
  const url2 = getSocketApiUrl(`orgs/${process.env.SOCKET_ORG_SLUG}/manifest-files?tarHash=${manifestsTarHash}`);
199088
199088
  return (await axios2.get(url2, { headers: getAuthHeaders() })).data;
199089
199089
  } catch (e) {
199090
- if (e instanceof AxiosError2) {
199091
- prettyPrintAxiosError(e);
199092
- }
199093
- throw new Error("Failed to fetch artifacts from Socket API using manifests tar hash");
199090
+ handleError(e, "Failed to fetch artifacts from Socket API using manifests tar hash", true);
199091
+ throw new Error("we should never reach this point");
199094
199092
  }
199095
199093
  }
199096
199094
  async function fetchArtifactsFromManifestsTarHash(manifestsTarHash) {
@@ -199099,10 +199097,8 @@ async function fetchArtifactsFromManifestsTarHash(manifestsTarHash) {
199099
199097
  const responseData = (await axios2.post(url2, {}, { headers: getAuthHeaders() })).data;
199100
199098
  return parseComputeArtifactsResponse(responseData);
199101
199099
  } catch (e) {
199102
- if (e instanceof AxiosError2) {
199103
- prettyPrintAxiosError(e);
199104
- }
199105
- throw new Error("Failed to fetch artifacts from Socket API using manifests tar hash");
199100
+ handleError(e, "Failed to fetch artifacts from Socket API using manifests tar hash", true);
199101
+ throw new Error("we should never reach this point");
199106
199102
  }
199107
199103
  }
199108
199104
  async function computeSocketFactArtifacts(rootDir, manifestFiles) {
@@ -206926,8 +206922,10 @@ var getNpmBin = once(async () => {
206926
206922
  });
206927
206923
  async function actuallyRunInstall(specificPackagesArgs = [], dir) {
206928
206924
  const installationCommand = cmdt2`${await getNpmBin()} install -f --ignore-scripts --no-fund --no-audit --no-progress ${specificPackagesArgs}`;
206929
- logger.info(`running installation command: ${installationCommand}`);
206930
- return execAndLogOnFailure2(installationCommand, dir);
206925
+ logger.info(`Running installation command: "${installationCommand}" in ${dir}`);
206926
+ const result = execAndLogOnFailure2(installationCommand, dir);
206927
+ logger.info(`Installation completed.`);
206928
+ return result;
206931
206929
  }
206932
206930
  async function getWorkspacePathsFromPackageJSON(projectFolder, useDotWhenNoWorkspaces = false) {
206933
206931
  const rootPackageJson = getPackageJsonObject(projectFolder);
@@ -207072,8 +207070,10 @@ var PnpmFixingManager = class extends NpmEcosystemFixingManager {
207072
207070
  }
207073
207071
  async actuallyRunInstall(specificPackagesCmd = [], workspacePath = ".") {
207074
207072
  const installationCommand = cmdt`pnpm install --ignore-scripts${await this.getPnpmMajorVersion() >= 9 && specificPackagesCmd.length === 0 ? "--no-frozen-lockfile" : ""} --config.confirmModulesPurge=false ${specificPackagesCmd}`;
207075
- logger.info(`running installation command: ${installationCommand}`);
207076
- await exec(installationCommand, resolve17(this.rootDir, this.subprojectPath, workspacePath));
207073
+ const installDir = resolve17(this.rootDir, this.subprojectPath, workspacePath);
207074
+ logger.info(`Running installation command: "${installationCommand}" in ${installDir}`);
207075
+ await exec(installationCommand, installDir);
207076
+ logger.info(`Installation completed.`);
207077
207077
  }
207078
207078
  async getLockFileYaml() {
207079
207079
  const lockFile = await (0, import_lockfile_file2.readWantedLockfile)(resolve17(this.rootDir, this.subprojectPath), { ignoreIncompatible: true });
@@ -207367,8 +207367,8 @@ var YarnFixingManager = class extends NpmEcosystemFixingManager {
207367
207367
  env.YARN_NODE_LINKER = "node-modules";
207368
207368
  }
207369
207369
  const installationCommand = cmdt`${cmdWithoutSpecificPackages} ${specificPackagesArgs}`;
207370
- logger.info(`Running installation command: ${installationCommand}`);
207371
207370
  const installDir = resolve19(this.rootDir, this.subprojectPath, workspacePath ?? ".");
207371
+ logger.info(`Running installation command: "${installationCommand}" in ${installDir}`);
207372
207372
  const installResult = await this.runYarnCommand(installationCommand, installDir, { env });
207373
207373
  if (installResult.error) {
207374
207374
  logger.info(`Failed to install packages: ${installResult.error.message}`);
@@ -207481,7 +207481,7 @@ var YarnFixingManager = class extends NpmEcosystemFixingManager {
207481
207481
  import { dirname as dirname8, join as join9, relative as relative7 } from "path";
207482
207482
  import { existsSync as existsSync11 } from "fs";
207483
207483
  import { readFile as readFile16, writeFile as writeFile6 } from "fs/promises";
207484
- function applyUpgradesToPackageJson(packageJsonContent, upgrades, rangeStyle) {
207484
+ function applyUpgradesToPackageJson(filePath, packageJsonContent, upgrades, rangeStyle) {
207485
207485
  let modifiedContent = packageJsonContent;
207486
207486
  for (const upgrade of sortUpgradesByOffset(upgrades)) {
207487
207487
  if (upgrade.manifestRef?.start !== void 0 && upgrade.manifestRef?.end !== void 0) {
@@ -207503,6 +207503,9 @@ function applyUpgradesToPackageJson(packageJsonContent, upgrades, rangeStyle) {
207503
207503
  const specifier = specifierMatch ? specifierMatch[1] : "";
207504
207504
  newVersionString = `"${specifier}${upgrade.upgradeVersion}"`;
207505
207505
  }
207506
+ logger.info(
207507
+ `Upgrading ${upgrade.packageName} from ${originalVersionString} to ${newVersionString} in ${filePath}`
207508
+ );
207506
207509
  modifiedContent = modifiedContent.substring(0, start) + newVersionString + modifiedContent.substring(end2);
207507
207510
  continue;
207508
207511
  }
@@ -207533,6 +207536,7 @@ function applyUpgradesToPackageJson(packageJsonContent, upgrades, rangeStyle) {
207533
207536
  const specifier = specifierMatch ? specifierMatch[1] : "";
207534
207537
  versionString = specifier + upgrade.upgradeVersion;
207535
207538
  }
207539
+ logger.info(`Upgrading ${upgrade.packageName} from ${currentVersion} to ${versionString} in ${filePath}`);
207536
207540
  return `${prefix}${versionString}"`;
207537
207541
  });
207538
207542
  }
@@ -207634,7 +207638,12 @@ var NpmSocketUpgradeManager = class {
207634
207638
  };
207635
207639
  }
207636
207640
  );
207637
- const modifiedContent = applyUpgradesToPackageJson(packageJsonContent, upgradesWithPackageNames, rangeStyle);
207641
+ const modifiedContent = applyUpgradesToPackageJson(
207642
+ packageJsonPath,
207643
+ packageJsonContent,
207644
+ upgradesWithPackageNames,
207645
+ rangeStyle
207646
+ );
207638
207647
  await writeFile6(packageJsonPath, modifiedContent, "utf-8");
207639
207648
  }
207640
207649
  await fixingManager.finalizeFixes();
@@ -207657,7 +207666,9 @@ function getPackageMangerForDirectory(directory) {
207657
207666
  } else if (existsSync11(join9(directory, "package-lock.json"))) {
207658
207667
  return "NPM";
207659
207668
  }
207660
- throw new Error("Upgrading packages is currently only supported for NPM projects using a lock file.");
207669
+ throw new Error(
207670
+ `Upgrading packages is currently only supported for NPM projects using a lock file. Failed to find a lock file in ${directory}`
207671
+ );
207661
207672
  }
207662
207673
  function sortUpgradesByOffset(upgrades) {
207663
207674
  return [...upgrades].sort((a4, b) => {
@@ -212387,6 +212398,711 @@ ${detailsString}` : ""}`;
212387
212398
  }
212388
212399
  };
212389
212400
 
212401
+ // ../utils/src/promise-queue.ts
212402
+ var PromiseQueue = class {
212403
+ /*
212404
+ * @param maxConcurrency The maximum number of tasks that can run in parallel.
212405
+ * @param maxQueueLength The maximum number of tasks that can be queued. If the queue is full, the oldest task is removed.
212406
+ */
212407
+ constructor(maxConcurrency, maxQueueLength) {
212408
+ this.maxConcurrency = maxConcurrency;
212409
+ this.maxQueueLength = maxQueueLength;
212410
+ if (maxQueueLength && maxQueueLength < 1) {
212411
+ throw new Error("maxQueueLength must be at least 1");
212412
+ }
212413
+ this.maxConcurrency = maxConcurrency;
212414
+ }
212415
+ queue = [];
212416
+ activeTasks = 0;
212417
+ idleResolver = null;
212418
+ idleRejector = null;
212419
+ error = null;
212420
+ async runNextTask() {
212421
+ if (this.activeTasks >= this.maxConcurrency) {
212422
+ return;
212423
+ }
212424
+ const task = this.queue.shift();
212425
+ if (task) {
212426
+ this.activeTasks++;
212427
+ try {
212428
+ await task();
212429
+ } catch (e) {
212430
+ this.error = e;
212431
+ } finally {
212432
+ this.activeTasks--;
212433
+ this.runNextTask();
212434
+ this.checkIdle();
212435
+ }
212436
+ } else {
212437
+ this.checkIdle();
212438
+ }
212439
+ }
212440
+ checkIdle() {
212441
+ if (!this.idleResolver || !this.idleRejector) return;
212442
+ const shouldResolve = this.queue.length === 0 && this.activeTasks === 0;
212443
+ if (this.error) this.idleRejector(this.error);
212444
+ else if (shouldResolve) this.idleResolver();
212445
+ const resolvedOrRejected = !!this.error || shouldResolve;
212446
+ if (resolvedOrRejected) {
212447
+ this.error = null;
212448
+ this.idleResolver = null;
212449
+ this.idleRejector = null;
212450
+ }
212451
+ }
212452
+ enqueueTask(task) {
212453
+ if (this.maxQueueLength && this.queue.length >= this.maxQueueLength) {
212454
+ this.queue.shift();
212455
+ }
212456
+ this.queue.push(task);
212457
+ this.runNextTask();
212458
+ }
212459
+ async onIdle() {
212460
+ return new Promise((resolve36, reject) => {
212461
+ if (this.error) {
212462
+ reject(this.error);
212463
+ this.error = null;
212464
+ } else if (this.queue.length === 0 && this.activeTasks === 0) {
212465
+ resolve36();
212466
+ } else {
212467
+ this.idleResolver = resolve36;
212468
+ this.idleRejector = reject;
212469
+ }
212470
+ });
212471
+ }
212472
+ };
212473
+
212474
+ // dist/cli-upgrade-purl.js
212475
+ import { join as join25, relative as relative14, resolve as resolve32 } from "node:path";
212476
+
212477
+ // ../web-compat-utils/src/assertions.ts
212478
+ function assertDefined(value) {
212479
+ if (value === void 0 || value === null) throw new Error("Expected value to be defined");
212480
+ return value;
212481
+ }
212482
+
212483
+ // dist/cli-upgrade-purl.js
212484
+ var import_packageurl_js3 = __toESM(require_packageurl_js(), 1);
212485
+
212486
+ // dist/internal/socket-mode-helpers-socket-dependency-trees.js
212487
+ var import_packageurl_js2 = __toESM(require_packageurl_js(), 1);
212488
+ var import_picomatch4 = __toESM(require_picomatch2(), 1);
212489
+ import { basename as basename10, dirname as dirname13, join as join24, sep as sep5 } from "path";
212490
+ var REQUIREMENTS_FILES_SEARCH_DEPTH2 = 3;
212491
+ function inferWorkspaceFromManifestPath(ecosystem, manifestPath, properPythonProjects) {
212492
+ switch (ecosystem) {
212493
+ case "NPM": {
212494
+ const base = basename10(manifestPath);
212495
+ const dir = dirname13(manifestPath);
212496
+ return base === "package.json" ? dir || "." : void 0;
212497
+ }
212498
+ case "MAVEN": {
212499
+ return ".";
212500
+ }
212501
+ case "PIP": {
212502
+ const base = basename10(manifestPath);
212503
+ const dir = dirname13(manifestPath);
212504
+ const workspaceDir = dir === "" ? "." : dir;
212505
+ if (properPythonProjects.includes(workspaceDir)) {
212506
+ return workspaceDir;
212507
+ }
212508
+ if (base === "poetry.lock" || base === "Pipfile.lock" || base === "uv.lock") {
212509
+ return workspaceDir;
212510
+ }
212511
+ if (base.endsWith(".txt")) {
212512
+ const properProjectDirs = properPythonProjects.filter((properProjectDir) => (properProjectDir === "." || workspaceDir === "." || workspaceDir.startsWith(properProjectDir)) && workspaceDir.replace(properProjectDir, "").split(sep5).length <= REQUIREMENTS_FILES_SEARCH_DEPTH2);
212513
+ const longestProperProjectDir = l5(properProjectDirs, [(d4) => d4.length, "desc"]);
212514
+ if (longestProperProjectDir) {
212515
+ return longestProperProjectDir;
212516
+ }
212517
+ return workspaceDir;
212518
+ }
212519
+ logger.warn(`No workspace found for manifest file ${manifestPath}`);
212520
+ return void 0;
212521
+ }
212522
+ case "NUGET": {
212523
+ return ".";
212524
+ }
212525
+ case "RUST": {
212526
+ return dirname13(manifestPath) || ".";
212527
+ }
212528
+ case "GO": {
212529
+ const base = basename10(manifestPath);
212530
+ const dir = dirname13(manifestPath);
212531
+ return base === "go.mod" ? dir || "." : void 0;
212532
+ }
212533
+ default: {
212534
+ return ".";
212535
+ }
212536
+ }
212537
+ }
212538
+ function inferProjectFromManifestPath(ecosystem, manifestPath) {
212539
+ switch (ecosystem) {
212540
+ case "NPM": {
212541
+ const filename = basename10(manifestPath);
212542
+ if (["package-lock.json", "pnpm-lock.yaml", "pnpm-lock.yml", "yarn.lock"].includes(filename)) {
212543
+ return dirname13(manifestPath) || ".";
212544
+ }
212545
+ return void 0;
212546
+ }
212547
+ }
212548
+ }
212549
+ function getAllToplevelAncestors(artifactMap, artifactId) {
212550
+ const visited = /* @__PURE__ */ new Set();
212551
+ const toplevelAncestors = /* @__PURE__ */ new Set();
212552
+ function findAncestors(currentId) {
212553
+ if (visited.has(currentId)) {
212554
+ return;
212555
+ }
212556
+ visited.add(currentId);
212557
+ const artifact = artifactMap.get(currentId);
212558
+ if (!artifact) {
212559
+ return;
212560
+ }
212561
+ if (artifact.toplevelAncestors && artifact.toplevelAncestors.length > 0) {
212562
+ for (const ancestorId of artifact.toplevelAncestors) {
212563
+ toplevelAncestors.add(ancestorId);
212564
+ findAncestors(ancestorId);
212565
+ }
212566
+ }
212567
+ }
212568
+ findAncestors(artifactId);
212569
+ return Array.from(toplevelAncestors);
212570
+ }
212571
+ async function fetchArtifactsFromSocket(rootWorkingDirectory, manifestsTarHash, mode) {
212572
+ logger.info("Fetching artifacts from Socket backend using manifests tar hash", manifestsTarHash);
212573
+ try {
212574
+ const { artifacts } = await fetchArtifactsFromManifestsTarHash(manifestsTarHash);
212575
+ const properPythonProjects = [];
212576
+ const pipArtifactToRepresentativeManifest = {};
212577
+ for (const artifact of artifacts) {
212578
+ if (artifact.type === "pypi" && artifact.manifestFiles) {
212579
+ pipArtifactToRepresentativeManifest[simplePurl(artifact.type, artifact.namespace ?? "", artifact.name, artifact.version ?? "")] = artifact;
212580
+ }
212581
+ }
212582
+ const venvExcludes = [
212583
+ "venv",
212584
+ ".venv",
212585
+ "env",
212586
+ ".env",
212587
+ "virtualenv",
212588
+ ".virtualenv",
212589
+ "venvs",
212590
+ ".venvs",
212591
+ "envs",
212592
+ ".envs",
212593
+ "__pycache__",
212594
+ ".tox",
212595
+ ".nox",
212596
+ ".pytest_cache",
212597
+ "site-packages",
212598
+ "dist-packages",
212599
+ "conda-meta",
212600
+ "conda-bld",
212601
+ ".mypy_cache",
212602
+ ".ruff_cache",
212603
+ ".hypothesis"
212604
+ ];
212605
+ const allFiles = await getFilesRelative(rootWorkingDirectory, venvExcludes);
212606
+ for (const file of allFiles) {
212607
+ const base = basename10(file);
212608
+ const workspaceDir = dirname13(file) || ".";
212609
+ if (base === "pyproject.toml" || base === "setup.py" && await isSetupPySetuptools(join24(rootWorkingDirectory, file))) {
212610
+ if (!properPythonProjects.includes(workspaceDir)) {
212611
+ properPythonProjects.push(workspaceDir);
212612
+ }
212613
+ }
212614
+ }
212615
+ const artifactMap = new Map(artifacts.map((a4) => [a4.id, a4]));
212616
+ const ecosystemToWorkspaceToAnalysisData = {};
212617
+ const ecosystemWorkspaceVulnIds = /* @__PURE__ */ new Set();
212618
+ const ecosystemToWorkspaceToVulnerabilities = {};
212619
+ const purlsFailedToFindWorkspace = /* @__PURE__ */ new Set();
212620
+ for (const artifact of artifacts) {
212621
+ let processToplevelAncestors2 = function(artifact2) {
212622
+ const allAncestorIds = getAllToplevelAncestors(artifactMap, artifact2.id);
212623
+ allAncestorIds.forEach((ancestorId) => artifactMap.get(ancestorId)?.manifestFiles?.forEach((ref) => manifestFiles.push(ref.file)));
212624
+ };
212625
+ var processToplevelAncestors = processToplevelAncestors2;
212626
+ const ecosystem = getAdvisoryEcosystemFromPurlType(artifact.type);
212627
+ if (!ecosystem)
212628
+ continue;
212629
+ const manifestFiles = [];
212630
+ switch (ecosystem) {
212631
+ case "MAVEN": {
212632
+ manifestFiles.push(...(await getFilesRelative(rootWorkingDirectory)).filter((file) => (0, import_picomatch4.default)("{{*-*.,}pom{.xml,},gradle.lockfile}")(basename10(file))));
212633
+ break;
212634
+ }
212635
+ case "NUGET": {
212636
+ manifestFiles.push(...(await getFilesRelative(rootWorkingDirectory)).filter((file) => (0, import_picomatch4.default)("{*.csproj,packages.lock.json}")(basename10(file))));
212637
+ break;
212638
+ }
212639
+ case "PIP": {
212640
+ const sPurl = simplePurl(artifact.type, artifact.namespace ?? "", artifact.name, artifact.version ?? "");
212641
+ if (pipArtifactToRepresentativeManifest[sPurl]) {
212642
+ manifestFiles.push(...(pipArtifactToRepresentativeManifest[sPurl].manifestFiles ?? []).map((ref) => ref.file));
212643
+ }
212644
+ processToplevelAncestors2(artifact);
212645
+ break;
212646
+ }
212647
+ default: {
212648
+ artifact.manifestFiles?.forEach((ref) => manifestFiles.push(ref.file));
212649
+ processToplevelAncestors2(artifact);
212650
+ break;
212651
+ }
212652
+ }
212653
+ const workspaceToManifestFiles = {};
212654
+ manifestFiles.forEach((manifestFile) => {
212655
+ const workspace = inferWorkspaceFromManifestPath(ecosystem, manifestFile, properPythonProjects);
212656
+ if (!workspace)
212657
+ return;
212658
+ (workspaceToManifestFiles[workspace] ??= []).push(manifestFile);
212659
+ });
212660
+ if (Object.keys(workspaceToManifestFiles).length === 0) {
212661
+ manifestFiles.forEach((manifestFile) => {
212662
+ const workspace = inferProjectFromManifestPath(ecosystem, manifestFile);
212663
+ if (!workspace)
212664
+ return;
212665
+ (workspaceToManifestFiles[workspace] ??= []).push(manifestFile);
212666
+ });
212667
+ }
212668
+ if (Object.keys(workspaceToManifestFiles).length === 0 && artifact.vulnerabilities && artifact.vulnerabilities.length > 0) {
212669
+ const purl = new import_packageurl_js2.PackageURL(artifact.type, artifact.namespace, artifact.name, artifact.version, artifact.qualifiers).toString();
212670
+ purlsFailedToFindWorkspace.add(purl);
212671
+ }
212672
+ for (const [workspace, manifestFiles2] of Object.entries(workspaceToManifestFiles)) {
212673
+ const workspaceData = (ecosystemToWorkspaceToAnalysisData[ecosystem] ??= {})[workspace] ??= {
212674
+ type: "socket",
212675
+ data: {
212676
+ type: ecosystem,
212677
+ manifestFiles: manifestFiles2,
212678
+ artifacts: []
212679
+ }
212680
+ };
212681
+ workspaceData.type;
212682
+ workspaceData.data.artifacts.push(artifact);
212683
+ }
212684
+ if (artifact.vulnerabilities && artifact.vulnerabilities.length > 0) {
212685
+ for (const workspace of Object.keys(workspaceToManifestFiles)) {
212686
+ for (const vuln of artifact.vulnerabilities) {
212687
+ const vulnerability = {
212688
+ url: vuln.ghsaId,
212689
+ purlType: artifact.type,
212690
+ range: vuln.range,
212691
+ name: artifact.name ?? "",
212692
+ dependency: artifact.name ?? "",
212693
+ vulnChainDetails: computeVulnChainDetails(artifacts, artifact.id),
212694
+ vulnerabilityAccessPaths: vuln.reachabilityData?.undeterminableReachability ? vuln.reachabilityData.publicComment ?? "" : vuln.reachabilityData?.pattern ?? null,
212695
+ ecosystem,
212696
+ artifactId: artifact.id
212697
+ };
212698
+ const vulnId = `${ecosystem}-${workspace}-${vulnerability.url}`;
212699
+ if (!ecosystemWorkspaceVulnIds.has(vulnId)) {
212700
+ ecosystemWorkspaceVulnIds.add(vulnId);
212701
+ ((ecosystemToWorkspaceToVulnerabilities[ecosystem] ??= {})[workspace] ??= []).push(vulnerability);
212702
+ }
212703
+ }
212704
+ }
212705
+ }
212706
+ }
212707
+ if (purlsFailedToFindWorkspace.size > 0) {
212708
+ logger.warn(`Failed to find workspace for the following purls with vulnerabilities: ${Array.from(purlsFailedToFindWorkspace).join(", ")}.
212709
+ ${mode === "reachability" ? "This means that we will not do a full reachability analysis for these vulnerabilities, but fallback to the results from the pre-computed reachability analysis." : ""}`);
212710
+ }
212711
+ return {
212712
+ artifacts,
212713
+ ecosystemToWorkspaceToAnalysisData,
212714
+ ecosystemToWorkspaceToVulnerabilities
212715
+ };
212716
+ } catch (error) {
212717
+ logger.error("Failed to fetch artifacts from Socket backend", error);
212718
+ throw error;
212719
+ }
212720
+ }
212721
+ function computeVulnChainDetails(artifacts, vulnerableArtifactId) {
212722
+ const artifactMap = new Map(artifacts.map((a4) => [a4.id, a4]));
212723
+ const parentsMap = /* @__PURE__ */ new Map();
212724
+ for (const artifact of artifacts) {
212725
+ if (artifact.dependencies) {
212726
+ for (const depId of artifact.dependencies) {
212727
+ if (!parentsMap.has(depId)) {
212728
+ parentsMap.set(depId, []);
212729
+ }
212730
+ parentsMap.get(depId).push(artifact.id);
212731
+ }
212732
+ }
212733
+ }
212734
+ const res = {
212735
+ packageName: "root",
212736
+ version: "0.0.0",
212737
+ children: [],
212738
+ transitiveDependencies: {}
212739
+ };
212740
+ function addNode(currentId, childId, visited) {
212741
+ if (visited.has(currentId))
212742
+ return;
212743
+ const currentArtifact = artifactMap.get(currentId);
212744
+ if (!currentArtifact)
212745
+ return;
212746
+ const parents4 = parentsMap.get(currentId);
212747
+ const newCurrentNode = {
212748
+ packageName: getNameFromNamespaceAndName(currentArtifact.type, currentArtifact.namespace, currentArtifact.name),
212749
+ version: currentArtifact.version ?? void 0,
212750
+ children: []
212751
+ };
212752
+ res.transitiveDependencies[currentId] = newCurrentNode;
212753
+ if (childId && !newCurrentNode.children.includes(childId)) {
212754
+ newCurrentNode.children.push(childId);
212755
+ }
212756
+ if (currentId === vulnerableArtifactId) {
212757
+ newCurrentNode.vulnerable = true;
212758
+ }
212759
+ if (currentArtifact.direct && !res.children.includes(currentId)) {
212760
+ res.children.push(currentId);
212761
+ }
212762
+ visited.add(currentId);
212763
+ if (parents4) {
212764
+ for (const parentId of parents4) {
212765
+ addNode(parentId, currentId, visited);
212766
+ }
212767
+ }
212768
+ }
212769
+ addNode(vulnerableArtifactId, void 0, /* @__PURE__ */ new Set());
212770
+ return res;
212771
+ }
212772
+
212773
+ // dist/cli-upgrade-purl.js
212774
+ var ECOSYSTEMS_WITH_SOCKET_UPGRADES = ["NPM", "MAVEN", "NUGET", "GO", "RUST"];
212775
+ async function upgradePurl(rootDir, upgrades, options, logFile, cliFixRunId, prefetchedArtifacts) {
212776
+ if (options.rangeStyle && options.rangeStyle !== "pin") {
212777
+ throw new Error('Range style must be "pin"');
212778
+ }
212779
+ logger.initWinstonLogger(options.debug);
212780
+ logger.silent = options.silent;
212781
+ let cliRunId = cliFixRunId;
212782
+ if (!cliRunId && options.manifestsTarHash) {
212783
+ cliRunId = await getSocketAPI().registerAutofixOrUpgradePurlRun(options.manifestsTarHash, options, "upgrade-purls");
212784
+ }
212785
+ const upgradePurlRunId = cliRunId && await getSocketAPI().registerUpgradePurlRun(cliRunId, upgrades);
212786
+ Spinner.instance({
212787
+ text: "Running Coana Upgrade Purl CLI",
212788
+ isSilent: options.silentSpinner ?? options.silent
212789
+ }).start();
212790
+ try {
212791
+ logger.info(`Upgrading purls for ${rootDir}:
212792
+ ${upgrades.map(({ purl, upgradeVersion }) => ` ${prettyPrintPurlUpgrade(purl, upgradeVersion)}`).join("\n")}`);
212793
+ if (options.manifestsTarHash) {
212794
+ const { supportedUpgrades, unsupportedUpgrades } = upgrades.reduce((acc, upgrade) => {
212795
+ const ecosystem = getAdvisoryEcosystemFromPurl(upgrade.purl);
212796
+ const target = ECOSYSTEMS_WITH_SOCKET_UPGRADES.includes(ecosystem) ? "supportedUpgrades" : "unsupportedUpgrades";
212797
+ acc[target].push(upgrade);
212798
+ return acc;
212799
+ }, { supportedUpgrades: [], unsupportedUpgrades: [] });
212800
+ if (unsupportedUpgrades.length > 0) {
212801
+ logger.warn(`The following upgrades are not supported due to missing support for upgrading their ecosystem: ${unsupportedUpgrades.map(({ purl, upgradeVersion }) => ` ${prettyPrintPurlUpgrade(purl, upgradeVersion)}`).join("\n")}`);
212802
+ }
212803
+ if (supportedUpgrades.length === 0) {
212804
+ return "fixed-none";
212805
+ }
212806
+ try {
212807
+ const purlToUpgradeVersion = new Map(supportedUpgrades.map((upgrade) => [upgrade.purl, upgrade.upgradeVersion]));
212808
+ const [manifestFiles, artifacts] = await Promise.all([
212809
+ fetchManifestFilesFromManifestsTarHash(options.manifestsTarHash),
212810
+ prefetchedArtifacts ?? (await fetchArtifactsFromSocket(rootDir, options.manifestsTarHash, "upgrade-purls")).artifacts
212811
+ ]);
212812
+ const ecosystemToSocketArtifactUpgrades = /* @__PURE__ */ new Map();
212813
+ artifacts.forEach((artifact, idx) => {
212814
+ if (!artifact.name)
212815
+ return;
212816
+ if (!artifact.version)
212817
+ return;
212818
+ const purl = new import_packageurl_js3.PackageURL(artifact.type, artifact.namespace, artifact.name, artifact.version, artifact.qualifiers).toString();
212819
+ const upgradeVersion = purlToUpgradeVersion.get(purl);
212820
+ if (!upgradeVersion)
212821
+ return;
212822
+ const ecosystem = getAdvisoryEcosystemFromPurlType(artifact.type);
212823
+ if (!ecosystemToSocketArtifactUpgrades.has(ecosystem)) {
212824
+ ecosystemToSocketArtifactUpgrades.set(ecosystem, /* @__PURE__ */ new Map());
212825
+ }
212826
+ const currentUpgradeVersion = ecosystemToSocketArtifactUpgrades.get(ecosystem).get(idx);
212827
+ if (currentUpgradeVersion === void 0) {
212828
+ ecosystemToSocketArtifactUpgrades.get(ecosystem).set(idx, upgradeVersion);
212829
+ } else {
212830
+ const versions = sortVersions(ecosystem, [artifact.version, currentUpgradeVersion, upgradeVersion]);
212831
+ if (versionSatisfiesRelation(ecosystem, artifact.version, "=", versions[0])) {
212832
+ ecosystemToSocketArtifactUpgrades.get(ecosystem).set(idx, versions[versions.length - 1]);
212833
+ } else if (versionSatisfiesRelation(ecosystem, artifact.version, "=", versions[versions.length - 1])) {
212834
+ ecosystemToSocketArtifactUpgrades.get(ecosystem).set(idx, versions[0]);
212835
+ } else {
212836
+ ecosystemToSocketArtifactUpgrades.get(ecosystem).set(idx, versions[versions.length - 1]);
212837
+ }
212838
+ }
212839
+ });
212840
+ let anyErrors = false;
212841
+ for (const [ecosystem, upgrades2] of ecosystemToSocketArtifactUpgrades) {
212842
+ if (options.rangeStyle && !["NPM", "MAVEN", "NUGET", "RUST"].includes(ecosystem)) {
212843
+ logger.warn(`Range style is not supported for ${ecosystem}, skipping upgrades`);
212844
+ continue;
212845
+ }
212846
+ const statusUpdater = (update2) => {
212847
+ const statusIcons = {
212848
+ success: "\u2705",
212849
+ skipped: "\u26AA",
212850
+ warn: "\u26A0\uFE0F",
212851
+ error: "\u274C"
212852
+ };
212853
+ logger.info(`${statusIcons[update2.status]} ${update2.message} \u2500 ${relative14(rootDir, resolve32(rootDir, update2.file))}`);
212854
+ update2.artifacts.forEach((idx, i7) => {
212855
+ logger.info(`${" ".repeat(3)}${i7 === update2.artifacts.length - 1 ? "\u2514\u2500" : "\u251C\u2500"} ${prettyPrintSocketFactArtifactUpgrade(artifacts[idx], upgrades2.get(idx))}`);
212856
+ });
212857
+ for (const detail of update2.details ?? []) {
212858
+ logger.debug(detail);
212859
+ }
212860
+ if (update2.patch)
212861
+ logger.debug(update2.patch);
212862
+ if (update2.status === "error")
212863
+ anyErrors = true;
212864
+ };
212865
+ const ctxt = {
212866
+ manifestFiles,
212867
+ upgrades: upgrades2,
212868
+ artifacts,
212869
+ rangeStyle: options.rangeStyle,
212870
+ statusUpdater
212871
+ };
212872
+ await applySocketUpgrades(ecosystem, rootDir, ctxt);
212873
+ }
212874
+ if (upgradePurlRunId) {
212875
+ await getSocketAPI().finalizeUpgradePurlRun(upgradePurlRunId, "succeeded");
212876
+ }
212877
+ return unsupportedUpgrades.length === 0 && !anyErrors ? "fixed-all" : "fixed-some";
212878
+ } catch (error) {
212879
+ if (upgradePurlRunId) {
212880
+ await getSocketAPI().finalizeUpgradePurlRun(
212881
+ upgradePurlRunId,
212882
+ "error",
212883
+ !cliFixRunId ? error.stack : void 0,
212884
+ // do not send stack trace and logContent for computeFixes runs, as that will be handled by that command.
212885
+ !cliFixRunId && logFile ? await logger.getLogContent(logFile) : void 0
212886
+ );
212887
+ }
212888
+ throw error;
212889
+ }
212890
+ }
212891
+ const otherModulesCommunicator = new OtherModulesCommunicator(rootDir, options, {
212892
+ type: "missing"
212893
+ });
212894
+ const ecosystems = upgrades.map((upgrade) => getAdvisoryEcosystemFromPurl(upgrade.purl));
212895
+ const manager = await ProjectManager.create(rootDir, otherModulesCommunicator, ecosystems);
212896
+ const { reachabilitySupport, traditionalScaSupport } = manager.getSubprojectsWithWorkspacePaths();
212897
+ const supportedSubprojects = reachabilitySupport.concat(traditionalScaSupport).filter((p3) => getPackageManagerSupport(p3.packageManagerName).supportsApplyingFixes);
212898
+ if (supportedSubprojects.length === 0) {
212899
+ throw new Error(`No supported projects found in ${rootDir}.`);
212900
+ }
212901
+ const subprojectPromiseQueue = new PromiseQueue(Number(options.concurrency));
212902
+ supportedSubprojects.forEach((subproject) => {
212903
+ subprojectPromiseQueue.enqueueTask(async () => {
212904
+ const workspacePathsMatchingGlob = subproject.workspacePaths.filter((wsPath) => minimatch(join25(subproject.subprojectPath, wsPath), options.globPattern ?? "**"));
212905
+ if (workspacePathsMatchingGlob.length === 0)
212906
+ return;
212907
+ logger.info(`Found workspaces for subproject ${subproject.subprojectPath}${options.globPattern ? `matching glob ${options.globPattern}` : ""}:
212908
+ ${workspacePathsMatchingGlob.map((wsPath) => ` ${wsPath}`).join("\n")}`);
212909
+ const fixingData = await otherModulesCommunicator.getFixingData(subproject.packageManagerName, subproject.subprojectPath, workspacePathsMatchingGlob);
212910
+ const workspaceToFixes = {};
212911
+ Object.entries(fixingData.dependencyTrees).forEach(([wsPath, depTree]) => {
212912
+ const vulnerabilityFixes = [];
212913
+ const simplePurlToDepId = getPurlStrings(depTree);
212914
+ upgrades.forEach((upgrade) => {
212915
+ const purl = import_packageurl_js3.PackageURL.fromString(upgrade.purl);
212916
+ if (purl.version === void 0)
212917
+ throw Error(`Undefined version for purl ${upgrade.purl}`);
212918
+ const simplePurl2 = `pkg:${purl.type}/${purl.namespace ? `${purl.namespace}/` : ""}${purl.name}${purl.version ? `@${purl.version}` : ""}`;
212919
+ for (const depIdMatchingPurl of simplePurlToDepId[simplePurl2] ?? []) {
212920
+ const node = depTree.transitiveDependencies[depIdMatchingPurl];
212921
+ if (!node)
212922
+ throw Error("should not happen!");
212923
+ vulnerabilityFixes.push({
212924
+ dependencyName: node.packageName,
212925
+ currentVersion: assertDefined(node.version),
212926
+ dependencyIdentifier: depIdMatchingPurl,
212927
+ fixedVersion: upgrade.upgradeVersion
212928
+ });
212929
+ }
212930
+ });
212931
+ if (vulnerabilityFixes.length === 0)
212932
+ return;
212933
+ logger.info(`Found ${vulnerabilityFixes.length} ${vulnerabilityFixes.length === 1 ? "dependency" : "dependencies"} matching upgrade specs for ${join25(subproject.subprojectPath, wsPath)}`);
212934
+ workspaceToFixes[wsPath] = [
212935
+ {
212936
+ fixId: "dummy",
212937
+ vulnerabilityFixes
212938
+ }
212939
+ ];
212940
+ });
212941
+ if (Object.entries(workspaceToFixes).length === 0) {
212942
+ logger.info(`No dependencies matching upgrade specs found for subproject ${subproject.subprojectPath}`);
212943
+ return;
212944
+ }
212945
+ await applySecurityFixes(subproject.packageManagerName, rootDir, relative14(rootDir, subproject.subprojectPath) || ".", otherModulesCommunicator, workspaceToFixes, fixingData, signalFixApplied);
212946
+ });
212947
+ });
212948
+ await subprojectPromiseQueue.onIdle();
212949
+ } finally {
212950
+ Spinner.instance().stop();
212951
+ }
212952
+ }
212953
+ var signalFixApplied = (_fixId, subprojectPath, workspacePath, vulnerabilityFixes) => {
212954
+ logger.info(`Successfully upgraded purls for: ${join25(subprojectPath, workspacePath)}`);
212955
+ logger.info(`Upgraded:
212956
+ ${vulnerabilityFixes.map((fix) => ` ${fix.dependencyName} from ${fix.currentVersion} to ${fix.fixedVersion}`).join("\n")}`);
212957
+ };
212958
+
212959
+ // dist/cli-compute-fixes-and-upgrade-purls.js
212960
+ async function computeFixesAndUpgradePurls(path2, options, logFile) {
212961
+ const autofixRunId = options.manifestsTarHash && await getSocketAPI().registerAutofixOrUpgradePurlRun(options.manifestsTarHash, options, "autofix");
212962
+ const { artifacts, ghsaToVulnerableArtifactIds, socketFactArtifacts } = await computeInputForComputingFixes(path2, options);
212963
+ if (Object.keys(ghsaToVulnerableArtifactIds).length === 0) {
212964
+ logger.info("No vulnerabilities to compute fixes for");
212965
+ return { type: "no-vulnerabilities-found" };
212966
+ }
212967
+ if (options.applyFixesTo.length === 0) {
212968
+ logger.info("Vulnerabilities found:", Object.keys(ghsaToVulnerableArtifactIds).join(", "));
212969
+ logger.info("Run again with --apply-fixes-to GHSA_IDS to fix those vulnerabilities by computing packages to upgrade and apply them");
212970
+ return { type: "no-ghsas-fix-requested", ghsas: Object.keys(ghsaToVulnerableArtifactIds) };
212971
+ }
212972
+ const ghsaToVulnerableArtifactIdsToApply = options.applyFixesTo.includes("all") ? ghsaToVulnerableArtifactIds : Object.fromEntries(Object.entries(ghsaToVulnerableArtifactIds).filter(([ghsa]) => options.applyFixesTo.includes(ghsa)));
212973
+ const computedFix = await useSocketComputeFixEndpoint(autofixRunId, artifacts, ghsaToVulnerableArtifactIdsToApply, {
212974
+ noMajorUpdates: options.disableMajorUpdates,
212975
+ minimumReleaseAgeInMinutes: options.minimumReleaseAgeInMinutes
212976
+ });
212977
+ if (computedFix.type !== "success") {
212978
+ throw new Error(`No fix found for the given vulnerabilities`);
212979
+ }
212980
+ const ghsasFailedToFix = Object.keys(ghsaToVulnerableArtifactIdsToApply).filter((ghsa) => {
212981
+ const artifactIds = ghsaToVulnerableArtifactIdsToApply[ghsa];
212982
+ if (!artifactIds)
212983
+ return false;
212984
+ return artifactIds.some((artifactId) => computedFix.ghsaToResult[ghsa].failedArtifacts?.includes(artifactId));
212985
+ });
212986
+ if (ghsasFailedToFix.length > 0) {
212987
+ logger.info("Failed to compute fixes for the following vulnerabilities:");
212988
+ }
212989
+ for (const ghsa of ghsasFailedToFix) {
212990
+ logger.info(` - ${ghsa} (${ghsaToVulnerableArtifactIdsToApply[ghsa].map((id) => simplePurl(artifacts[id].type, artifacts[id].namespace ?? null, artifacts[id].name ?? "", artifacts[id].version ?? null)).join(", ")})`);
212991
+ }
212992
+ const fixesFound = Object.entries(computedFix.ghsaToResult).filter(([_, result]) => result.failedArtifacts === void 0 || result.failedArtifacts.length === 0);
212993
+ if (options.onlyDirectDependencyUpgrades) {
212994
+ return computeDirectDependencyUpgrades(artifacts, fixesFound);
212995
+ }
212996
+ const combinedFixes = fixesFound.flatMap(([_, result]) => result.fixes);
212997
+ if (options.dryRun) {
212998
+ logger.info("Fixes found:");
212999
+ for (const [ghsa, result] of fixesFound) {
213000
+ logger.info(` - ${ghsa}:`);
213001
+ for (const fix of result.fixes) {
213002
+ logger.info(` - ${fix.purl} -> ${fix.fixedVersion}`);
213003
+ }
213004
+ }
213005
+ return {
213006
+ type: "dry-run-result",
213007
+ fixes: Object.fromEntries(fixesFound.map(([ghsa, result]) => [ghsa, result.fixes])),
213008
+ ...ghsasFailedToFix.length > 0 && { failedToFix: ghsasFailedToFix }
213009
+ };
213010
+ }
213011
+ if (combinedFixes.length === 0) {
213012
+ if (autofixRunId) {
213013
+ await getSocketAPI().finalizeAutofixRun(autofixRunId, "fixed-none");
213014
+ }
213015
+ throw new Error("Failed to find a fix for the given vulnerabilities");
213016
+ }
213017
+ try {
213018
+ const applyFixesStatus = await upgradePurl(path2, T3(combinedFixes, (fix) => `${fix.purl}${fix.fixedVersion}`).map((fix) => ({
213019
+ purl: fix.purl,
213020
+ upgradeVersion: fix.fixedVersion
213021
+ })), {
213022
+ debug: options.debug,
213023
+ silent: options.silent,
213024
+ runWithoutDocker: options.runWithoutDocker,
213025
+ manifestsTarHash: options.manifestsTarHash,
213026
+ concurrency: "1",
213027
+ globPattern: options.globPattern,
213028
+ rangeStyle: options.rangeStyle
213029
+ }, void 0, autofixRunId, socketFactArtifacts) ?? "fixed-all";
213030
+ if (autofixRunId) {
213031
+ await getSocketAPI().finalizeAutofixRun(autofixRunId, ghsasFailedToFix.length === 0 && applyFixesStatus === "fixed-all" ? "fixed-all" : ghsasFailedToFix.length === Object.keys(ghsaToVulnerableArtifactIdsToApply).length || applyFixesStatus === "fixed-none" ? "fixed-none" : "fixed-some");
213032
+ }
213033
+ return {
213034
+ type: "applied-fixes",
213035
+ fixes: Object.fromEntries(fixesFound.map(([ghsa, result]) => [ghsa, result.fixes]))
213036
+ };
213037
+ } catch (error) {
213038
+ if (autofixRunId) {
213039
+ await getSocketAPI().finalizeAutofixRun(autofixRunId, "error", error.stack, await logger.getLogContent(logFile));
213040
+ }
213041
+ logger.error("Error applying fixes:", error);
213042
+ throw error;
213043
+ }
213044
+ }
213045
+ async function computeInputForComputingFixes(path2, options) {
213046
+ if (!options.manifestsTarHash)
213047
+ throw new Error("Manifests tar hash is required for computing fixes");
213048
+ const { artifacts } = await fetchArtifactsFromSocket(path2, options.manifestsTarHash, "autofix");
213049
+ const ghsaToVulnerableArtifactIds = {};
213050
+ for (const [index2, artifact] of artifacts.entries()) {
213051
+ if (!artifact.vulnerabilities)
213052
+ continue;
213053
+ for (const vulnerability of artifact.vulnerabilities) {
213054
+ if (!(ghsaToVulnerableArtifactIds[vulnerability.ghsaId] ??= []).includes(index2)) {
213055
+ ghsaToVulnerableArtifactIds[vulnerability.ghsaId].push(index2);
213056
+ }
213057
+ }
213058
+ }
213059
+ const sbomTaskArtifacts = artifacts.map((artifact) => ({
213060
+ type: artifact.type,
213061
+ name: artifact.name ?? "",
213062
+ version: artifact.version ?? "",
213063
+ namespace: artifact.namespace ?? void 0,
213064
+ adj: artifact.dependencies?.map((dep) => artifacts.findIndex((a4) => a4.id === dep)) ?? [],
213065
+ direct: artifact.direct,
213066
+ topLevelAncestors: artifact.toplevelAncestors?.map((ancestor) => artifacts.findIndex((a4) => a4.id === ancestor)) ?? []
213067
+ }));
213068
+ return { artifacts: sbomTaskArtifacts, ghsaToVulnerableArtifactIds, socketFactArtifacts: artifacts };
213069
+ }
213070
+ async function computeDirectDependencyUpgrades(artifacts, fixesFound) {
213071
+ const purlToArtifact = Object.fromEntries(artifacts.map((a4) => [simplePurl(a4.type, a4.namespace ?? null, a4.name ?? "", a4.version ?? null), a4]));
213072
+ const packageFixes = {};
213073
+ for (const [ghsa, result2] of fixesFound) {
213074
+ const directUpdates = {};
213075
+ for (const directFix of result2.fixes.filter((fix) => purlToArtifact[fix.purl]?.direct)) {
213076
+ directUpdates[directFix.purl] = { fixedVersion: directFix.fixedVersion };
213077
+ }
213078
+ const directUpdatePurls = Object.keys(directUpdates);
213079
+ for (const indirectFix of result2.fixes.filter((fix) => !purlToArtifact[fix.purl]?.direct)) {
213080
+ const directDependencies = purlToArtifact[indirectFix.purl]?.topLevelAncestors;
213081
+ for (const directDependency of directDependencies) {
213082
+ const artifact = artifacts[directDependency];
213083
+ const purl = simplePurl(artifact.type, artifact.namespace ?? null, artifact.name ?? "", artifact.version ?? null);
213084
+ if (directUpdatePurls.includes(purl))
213085
+ continue;
213086
+ if (directUpdates[purl]) {
213087
+ (directUpdates[purl].transitiveFixes ??= []).push(indirectFix);
213088
+ } else {
213089
+ directUpdates[purl] = { transitiveFixes: [indirectFix] };
213090
+ }
213091
+ directUpdates[purl] = { transitiveFixes: [indirectFix] };
213092
+ }
213093
+ }
213094
+ packageFixes[ghsa] = {
213095
+ directDependencies: Object.entries(directUpdates).map(([purl, update2]) => ({ purl, ...update2 }))
213096
+ };
213097
+ }
213098
+ const result = {
213099
+ type: "only-direct-dependency-upgrades",
213100
+ fixes: packageFixes
213101
+ };
213102
+ logger.info("Affected direct dependencies and upgrades to fix (--show-affected-direct-dependencies does not apply the upgrades):", JSON.stringify(result, null, 2));
213103
+ return result;
213104
+ }
213105
+
212390
213106
  // dist/cli-core.js
212391
213107
  import { writeFileSync as writeFileSync3 } from "fs";
212392
213108
  import { mkdir as mkdir2, writeFile as writeFile10 } from "fs/promises";
@@ -212564,7 +213280,7 @@ var bgWhiteBright = format5(107, 49);
212564
213280
  // dist/cli-core.js
212565
213281
  var import_lodash15 = __toESM(require_lodash(), 1);
212566
213282
  import os from "os";
212567
- import { join as join26, relative as relative14, resolve as resolve33 } from "path";
213283
+ import { join as join27, relative as relative15, resolve as resolve34 } from "path";
212568
213284
 
212569
213285
  // ../utils/src/dashboard-api/shared-api.ts
212570
213286
  var DashboardAPI = class {
@@ -212673,79 +213389,6 @@ var DashboardAPI = class {
212673
213389
  }
212674
213390
  };
212675
213391
 
212676
- // ../utils/src/promise-queue.ts
212677
- var PromiseQueue = class {
212678
- /*
212679
- * @param maxConcurrency The maximum number of tasks that can run in parallel.
212680
- * @param maxQueueLength The maximum number of tasks that can be queued. If the queue is full, the oldest task is removed.
212681
- */
212682
- constructor(maxConcurrency, maxQueueLength) {
212683
- this.maxConcurrency = maxConcurrency;
212684
- this.maxQueueLength = maxQueueLength;
212685
- if (maxQueueLength && maxQueueLength < 1) {
212686
- throw new Error("maxQueueLength must be at least 1");
212687
- }
212688
- this.maxConcurrency = maxConcurrency;
212689
- }
212690
- queue = [];
212691
- activeTasks = 0;
212692
- idleResolver = null;
212693
- idleRejector = null;
212694
- error = null;
212695
- async runNextTask() {
212696
- if (this.activeTasks >= this.maxConcurrency) {
212697
- return;
212698
- }
212699
- const task = this.queue.shift();
212700
- if (task) {
212701
- this.activeTasks++;
212702
- try {
212703
- await task();
212704
- } catch (e) {
212705
- this.error = e;
212706
- } finally {
212707
- this.activeTasks--;
212708
- this.runNextTask();
212709
- this.checkIdle();
212710
- }
212711
- } else {
212712
- this.checkIdle();
212713
- }
212714
- }
212715
- checkIdle() {
212716
- if (!this.idleResolver || !this.idleRejector) return;
212717
- const shouldResolve = this.queue.length === 0 && this.activeTasks === 0;
212718
- if (this.error) this.idleRejector(this.error);
212719
- else if (shouldResolve) this.idleResolver();
212720
- const resolvedOrRejected = !!this.error || shouldResolve;
212721
- if (resolvedOrRejected) {
212722
- this.error = null;
212723
- this.idleResolver = null;
212724
- this.idleRejector = null;
212725
- }
212726
- }
212727
- enqueueTask(task) {
212728
- if (this.maxQueueLength && this.queue.length >= this.maxQueueLength) {
212729
- this.queue.shift();
212730
- }
212731
- this.queue.push(task);
212732
- this.runNextTask();
212733
- }
212734
- async onIdle() {
212735
- return new Promise((resolve36, reject) => {
212736
- if (this.error) {
212737
- reject(this.error);
212738
- this.error = null;
212739
- } else if (this.queue.length === 0 && this.activeTasks === 0) {
212740
- resolve36();
212741
- } else {
212742
- this.idleResolver = resolve36;
212743
- this.idleRejector = reject;
212744
- }
212745
- });
212746
- }
212747
- };
212748
-
212749
213392
  // ../utils/src/vulnerable-paths-utils.ts
212750
213393
  function mkTrie() {
212751
213394
  return { children: {}, leaf: false };
@@ -212885,13 +213528,13 @@ var DEFAULT_REPORT_FILENAME_BASE = "coana-report";
212885
213528
  // dist/internal/exclude-dirs-from-configuration-files.js
212886
213529
  import { existsSync as existsSync20 } from "fs";
212887
213530
  import { readFile as readFile27 } from "fs/promises";
212888
- import { basename as basename10, resolve as resolve32 } from "path";
213531
+ import { basename as basename11, resolve as resolve33 } from "path";
212889
213532
  var import_yaml2 = __toESM(require_dist11(), 1);
212890
213533
  async function inferExcludeDirsFromConfigurationFiles(rootWorkingDir) {
212891
- const socketYmlConfigFile = resolve32(rootWorkingDir, "socket.yml");
213534
+ const socketYmlConfigFile = resolve33(rootWorkingDir, "socket.yml");
212892
213535
  if (existsSync20(socketYmlConfigFile))
212893
213536
  return inferExcludeDirsFromSocketConfig(socketYmlConfigFile);
212894
- const socketYamlConfigFile = resolve32(rootWorkingDir, "socket.yaml");
213537
+ const socketYamlConfigFile = resolve33(rootWorkingDir, "socket.yaml");
212895
213538
  if (existsSync20(socketYamlConfigFile))
212896
213539
  return inferExcludeDirsFromSocketConfig(socketYamlConfigFile);
212897
213540
  return void 0;
@@ -212905,7 +213548,7 @@ async function inferExcludeDirsFromSocketConfig(socketConfigFile) {
212905
213548
  return void 0;
212906
213549
  if (ignorePaths.some((ignorePath) => ignorePath.includes("!")))
212907
213550
  return void 0;
212908
- logger.info(`Inferring paths to exclude based on Socket config file: ${basename10(socketConfigFile)}`);
213551
+ logger.info(`Inferring paths to exclude based on Socket config file: ${basename11(socketConfigFile)}`);
212909
213552
  return config3.projectIgnorePaths;
212910
213553
  } catch (e) {
212911
213554
  return void 0;
@@ -212962,7 +213605,7 @@ async function scanForVulnerabilitiesSocketMode(dependencyTree) {
212962
213605
  range: vulnerability.range,
212963
213606
  name: dependencyTreeNode.packageName,
212964
213607
  dependency: dependencyTreeNode.packageName,
212965
- vulnChainDetails: computeVulnChainDetails(dependencyTree, dependencyIdentifier, parentsMap),
213608
+ vulnChainDetails: computeVulnChainDetails2(dependencyTree, dependencyIdentifier, parentsMap),
212966
213609
  vulnerabilityAccessPaths: vulnerability.reachabilityData?.pattern ?? null,
212967
213610
  ecosystem: dependencyTree.ecosystem
212968
213611
  });
@@ -212974,7 +213617,7 @@ async function scanForVulnerabilitiesSocketMode(dependencyTree) {
212974
213617
  }
212975
213618
  return vulnerabilities;
212976
213619
  }
212977
- function computeVulnChainDetails(dependencyTree, dependencyIdentifier, parentsMap) {
213620
+ function computeVulnChainDetails2(dependencyTree, dependencyIdentifier, parentsMap) {
212978
213621
  const res = {
212979
213622
  packageName: "root",
212980
213623
  version: "0.0.0",
@@ -213011,293 +213654,6 @@ function transformToVulnChainNode(dependencyTree) {
213011
213654
  };
213012
213655
  }
213013
213656
 
213014
- // dist/internal/socket-mode-helpers-socket-dependency-trees.js
213015
- var import_packageurl_js2 = __toESM(require_packageurl_js(), 1);
213016
- var import_picomatch4 = __toESM(require_picomatch2(), 1);
213017
- import { basename as basename11, dirname as dirname13, join as join24, sep as sep5 } from "path";
213018
- var REQUIREMENTS_FILES_SEARCH_DEPTH2 = 3;
213019
- function inferWorkspaceFromManifestPath(ecosystem, manifestPath, properPythonProjects) {
213020
- switch (ecosystem) {
213021
- case "NPM": {
213022
- const base = basename11(manifestPath);
213023
- const dir = dirname13(manifestPath);
213024
- return base === "package.json" ? dir || "." : void 0;
213025
- }
213026
- case "MAVEN": {
213027
- return ".";
213028
- }
213029
- case "PIP": {
213030
- const base = basename11(manifestPath);
213031
- const dir = dirname13(manifestPath);
213032
- const workspaceDir = dir === "" ? "." : dir;
213033
- if (properPythonProjects.includes(workspaceDir)) {
213034
- return workspaceDir;
213035
- }
213036
- if (base === "poetry.lock" || base === "Pipfile.lock" || base === "uv.lock") {
213037
- return workspaceDir;
213038
- }
213039
- if (base.endsWith(".txt")) {
213040
- const properProjectDirs = properPythonProjects.filter((properProjectDir) => (properProjectDir === "." || workspaceDir === "." || workspaceDir.startsWith(properProjectDir)) && workspaceDir.replace(properProjectDir, "").split(sep5).length <= REQUIREMENTS_FILES_SEARCH_DEPTH2);
213041
- const longestProperProjectDir = l5(properProjectDirs, [(d4) => d4.length, "desc"]);
213042
- if (longestProperProjectDir) {
213043
- return longestProperProjectDir;
213044
- }
213045
- return workspaceDir;
213046
- }
213047
- logger.warn(`No workspace found for manifest file ${manifestPath}`);
213048
- return void 0;
213049
- }
213050
- case "NUGET": {
213051
- return ".";
213052
- }
213053
- case "RUST": {
213054
- return dirname13(manifestPath) || ".";
213055
- }
213056
- case "GO": {
213057
- const base = basename11(manifestPath);
213058
- const dir = dirname13(manifestPath);
213059
- return base === "go.mod" ? dir || "." : void 0;
213060
- }
213061
- default: {
213062
- return ".";
213063
- }
213064
- }
213065
- }
213066
- function inferProjectFromManifestPath(ecosystem, manifestPath) {
213067
- switch (ecosystem) {
213068
- case "NPM": {
213069
- const filename = basename11(manifestPath);
213070
- if (["package-lock.json", "pnpm-lock.yaml", "pnpm-lock.yml", "yarn.lock"].includes(filename)) {
213071
- return dirname13(manifestPath) || ".";
213072
- }
213073
- return void 0;
213074
- }
213075
- }
213076
- }
213077
- function getAllToplevelAncestors(artifactMap, artifactId) {
213078
- const visited = /* @__PURE__ */ new Set();
213079
- const toplevelAncestors = /* @__PURE__ */ new Set();
213080
- function findAncestors(currentId) {
213081
- if (visited.has(currentId)) {
213082
- return;
213083
- }
213084
- visited.add(currentId);
213085
- const artifact = artifactMap.get(currentId);
213086
- if (!artifact) {
213087
- return;
213088
- }
213089
- if (artifact.toplevelAncestors && artifact.toplevelAncestors.length > 0) {
213090
- for (const ancestorId of artifact.toplevelAncestors) {
213091
- toplevelAncestors.add(ancestorId);
213092
- findAncestors(ancestorId);
213093
- }
213094
- }
213095
- }
213096
- findAncestors(artifactId);
213097
- return Array.from(toplevelAncestors);
213098
- }
213099
- async function fetchArtifactsFromSocket(rootWorkingDirectory, manifestsTarHash, mode) {
213100
- logger.info("Fetching artifacts from Socket backend using manifests tar hash", manifestsTarHash);
213101
- try {
213102
- const { artifacts } = await fetchArtifactsFromManifestsTarHash(manifestsTarHash);
213103
- const properPythonProjects = [];
213104
- const pipArtifactToRepresentativeManifest = {};
213105
- for (const artifact of artifacts) {
213106
- if (artifact.type === "pypi" && artifact.manifestFiles) {
213107
- pipArtifactToRepresentativeManifest[simplePurl(artifact.type, artifact.namespace ?? "", artifact.name, artifact.version ?? "")] = artifact;
213108
- }
213109
- }
213110
- const venvExcludes = [
213111
- "venv",
213112
- ".venv",
213113
- "env",
213114
- ".env",
213115
- "virtualenv",
213116
- ".virtualenv",
213117
- "venvs",
213118
- ".venvs",
213119
- "envs",
213120
- ".envs",
213121
- "__pycache__",
213122
- ".tox",
213123
- ".nox",
213124
- ".pytest_cache",
213125
- "site-packages",
213126
- "dist-packages",
213127
- "conda-meta",
213128
- "conda-bld",
213129
- ".mypy_cache",
213130
- ".ruff_cache",
213131
- ".hypothesis"
213132
- ];
213133
- const allFiles = await getFilesRelative(rootWorkingDirectory, venvExcludes);
213134
- for (const file of allFiles) {
213135
- const base = basename11(file);
213136
- const workspaceDir = dirname13(file) || ".";
213137
- if (base === "pyproject.toml" || base === "setup.py" && await isSetupPySetuptools(join24(rootWorkingDirectory, file))) {
213138
- if (!properPythonProjects.includes(workspaceDir)) {
213139
- properPythonProjects.push(workspaceDir);
213140
- }
213141
- }
213142
- }
213143
- const artifactMap = new Map(artifacts.map((a4) => [a4.id, a4]));
213144
- const ecosystemToWorkspaceToAnalysisData = {};
213145
- const ecosystemWorkspaceVulnIds = /* @__PURE__ */ new Set();
213146
- const ecosystemToWorkspaceToVulnerabilities = {};
213147
- const purlsFailedToFindWorkspace = /* @__PURE__ */ new Set();
213148
- for (const artifact of artifacts) {
213149
- let processToplevelAncestors2 = function(artifact2) {
213150
- const allAncestorIds = getAllToplevelAncestors(artifactMap, artifact2.id);
213151
- allAncestorIds.forEach((ancestorId) => artifactMap.get(ancestorId)?.manifestFiles?.forEach((ref) => manifestFiles.push(ref.file)));
213152
- };
213153
- var processToplevelAncestors = processToplevelAncestors2;
213154
- const ecosystem = getAdvisoryEcosystemFromPurlType(artifact.type);
213155
- if (!ecosystem)
213156
- continue;
213157
- const manifestFiles = [];
213158
- switch (ecosystem) {
213159
- case "MAVEN": {
213160
- manifestFiles.push(...(await getFilesRelative(rootWorkingDirectory)).filter((file) => (0, import_picomatch4.default)("{{*-*.,}pom{.xml,},gradle.lockfile}")(basename11(file))));
213161
- break;
213162
- }
213163
- case "NUGET": {
213164
- manifestFiles.push(...(await getFilesRelative(rootWorkingDirectory)).filter((file) => (0, import_picomatch4.default)("{*.csproj,packages.lock.json}")(basename11(file))));
213165
- break;
213166
- }
213167
- case "PIP": {
213168
- const sPurl = simplePurl(artifact.type, artifact.namespace ?? "", artifact.name, artifact.version ?? "");
213169
- if (pipArtifactToRepresentativeManifest[sPurl]) {
213170
- manifestFiles.push(...(pipArtifactToRepresentativeManifest[sPurl].manifestFiles ?? []).map((ref) => ref.file));
213171
- }
213172
- processToplevelAncestors2(artifact);
213173
- break;
213174
- }
213175
- default: {
213176
- artifact.manifestFiles?.forEach((ref) => manifestFiles.push(ref.file));
213177
- processToplevelAncestors2(artifact);
213178
- break;
213179
- }
213180
- }
213181
- const workspaceToManifestFiles = {};
213182
- manifestFiles.forEach((manifestFile) => {
213183
- const workspace = inferWorkspaceFromManifestPath(ecosystem, manifestFile, properPythonProjects);
213184
- if (!workspace)
213185
- return;
213186
- (workspaceToManifestFiles[workspace] ??= []).push(manifestFile);
213187
- });
213188
- if (Object.keys(workspaceToManifestFiles).length === 0) {
213189
- manifestFiles.forEach((manifestFile) => {
213190
- const workspace = inferProjectFromManifestPath(ecosystem, manifestFile);
213191
- if (!workspace)
213192
- return;
213193
- (workspaceToManifestFiles[workspace] ??= []).push(manifestFile);
213194
- });
213195
- }
213196
- if (Object.keys(workspaceToManifestFiles).length === 0 && artifact.vulnerabilities && artifact.vulnerabilities.length > 0) {
213197
- const purl = new import_packageurl_js2.PackageURL(artifact.type, artifact.namespace, artifact.name, artifact.version, artifact.qualifiers).toString();
213198
- purlsFailedToFindWorkspace.add(purl);
213199
- }
213200
- for (const [workspace, manifestFiles2] of Object.entries(workspaceToManifestFiles)) {
213201
- const workspaceData = (ecosystemToWorkspaceToAnalysisData[ecosystem] ??= {})[workspace] ??= {
213202
- type: "socket",
213203
- data: {
213204
- type: ecosystem,
213205
- manifestFiles: manifestFiles2,
213206
- artifacts: []
213207
- }
213208
- };
213209
- workspaceData.type;
213210
- workspaceData.data.artifacts.push(artifact);
213211
- }
213212
- if (artifact.vulnerabilities && artifact.vulnerabilities.length > 0) {
213213
- for (const workspace of Object.keys(workspaceToManifestFiles)) {
213214
- for (const vuln of artifact.vulnerabilities) {
213215
- const vulnerability = {
213216
- url: vuln.ghsaId,
213217
- purlType: artifact.type,
213218
- range: vuln.range,
213219
- name: artifact.name ?? "",
213220
- dependency: artifact.name ?? "",
213221
- vulnChainDetails: computeVulnChainDetails2(artifacts, artifact.id),
213222
- vulnerabilityAccessPaths: vuln.reachabilityData?.undeterminableReachability ? vuln.reachabilityData.publicComment ?? "" : vuln.reachabilityData?.pattern ?? null,
213223
- ecosystem,
213224
- artifactId: artifact.id
213225
- };
213226
- const vulnId = `${ecosystem}-${workspace}-${vulnerability.url}`;
213227
- if (!ecosystemWorkspaceVulnIds.has(vulnId)) {
213228
- ecosystemWorkspaceVulnIds.add(vulnId);
213229
- ((ecosystemToWorkspaceToVulnerabilities[ecosystem] ??= {})[workspace] ??= []).push(vulnerability);
213230
- }
213231
- }
213232
- }
213233
- }
213234
- }
213235
- if (purlsFailedToFindWorkspace.size > 0) {
213236
- logger.warn(`Failed to find workspace for the following purls with vulnerabilities: ${Array.from(purlsFailedToFindWorkspace).join(", ")}.
213237
- ${mode === "reachability" ? "This means that we will not do a full reachability analysis for these vulnerabilities, but fallback to the results from the pre-computed reachability analysis." : ""}`);
213238
- }
213239
- return {
213240
- artifacts,
213241
- ecosystemToWorkspaceToAnalysisData,
213242
- ecosystemToWorkspaceToVulnerabilities
213243
- };
213244
- } catch (error) {
213245
- logger.error("Failed to fetch artifacts from Socket backend", error);
213246
- throw error;
213247
- }
213248
- }
213249
- function computeVulnChainDetails2(artifacts, vulnerableArtifactId) {
213250
- const artifactMap = new Map(artifacts.map((a4) => [a4.id, a4]));
213251
- const parentsMap = /* @__PURE__ */ new Map();
213252
- for (const artifact of artifacts) {
213253
- if (artifact.dependencies) {
213254
- for (const depId of artifact.dependencies) {
213255
- if (!parentsMap.has(depId)) {
213256
- parentsMap.set(depId, []);
213257
- }
213258
- parentsMap.get(depId).push(artifact.id);
213259
- }
213260
- }
213261
- }
213262
- const res = {
213263
- packageName: "root",
213264
- version: "0.0.0",
213265
- children: [],
213266
- transitiveDependencies: {}
213267
- };
213268
- function addNode(currentId, childId, visited) {
213269
- if (visited.has(currentId))
213270
- return;
213271
- const currentArtifact = artifactMap.get(currentId);
213272
- if (!currentArtifact)
213273
- return;
213274
- const parents4 = parentsMap.get(currentId);
213275
- const newCurrentNode = {
213276
- packageName: getNameFromNamespaceAndName(currentArtifact.type, currentArtifact.namespace, currentArtifact.name),
213277
- version: currentArtifact.version ?? void 0,
213278
- children: []
213279
- };
213280
- res.transitiveDependencies[currentId] = newCurrentNode;
213281
- if (childId && !newCurrentNode.children.includes(childId)) {
213282
- newCurrentNode.children.push(childId);
213283
- }
213284
- if (currentId === vulnerableArtifactId) {
213285
- newCurrentNode.vulnerable = true;
213286
- }
213287
- if (currentArtifact.direct && !res.children.includes(currentId)) {
213288
- res.children.push(currentId);
213289
- }
213290
- visited.add(currentId);
213291
- if (parents4) {
213292
- for (const parentId of parents4) {
213293
- addNode(parentId, currentId, visited);
213294
- }
213295
- }
213296
- }
213297
- addNode(vulnerableArtifactId, void 0, /* @__PURE__ */ new Set());
213298
- return res;
213299
- }
213300
-
213301
213657
  // dist/internal/socket-report-coana-dependency-tree.js
213302
213658
  var MAX_STACKS_TO_SEND = 10;
213303
213659
  function toSocketFacts(report, dependencyTrees, subPjToWsPathToDirectDependencies) {
@@ -226988,7 +227344,7 @@ var { root: root2 } = static_exports;
226988
227344
  // ../utils/src/maven-utils.ts
226989
227345
  var import_lodash14 = __toESM(require_lodash(), 1);
226990
227346
  import { existsSync as existsSync21, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
226991
- import { join as join25 } from "path";
227347
+ import { join as join26 } from "path";
226992
227348
  var { memoize: memoize3 } = import_lodash14.default;
226993
227349
  var memoizedParseShellArgs = memoize3(parseShellArgs);
226994
227350
  var MAVEN_PUBLIC_REPOSITORIES = [
@@ -227671,12 +228027,6 @@ var InMemoryVulnerabilityMetadataStore = class {
227671
228027
  }
227672
228028
  };
227673
228029
 
227674
- // ../web-compat-utils/src/assertions.ts
227675
- function assertDefined(value) {
227676
- if (value === void 0 || value === null) throw new Error("Expected value to be defined");
227677
- return value;
227678
- }
227679
-
227680
228030
  // ../security-auditor/security-auditor-api/src/fixes-task.ts
227681
228031
  var MESSAGE_PREFIX_FOR_FAILED_TO_PICK_VERSION = `Failed to pick a version`;
227682
228032
  var MESSAGE_PREFIX_FOR_NO_POTENTIAL_VERSIONS = `No potential versions`;
@@ -228359,7 +228709,7 @@ async function onlineScan(dependencyTree, apiKey, timeout) {
228359
228709
  }
228360
228710
 
228361
228711
  // dist/version.js
228362
- var version2 = "14.12.42";
228712
+ var version2 = "14.12.44";
228363
228713
 
228364
228714
  // dist/cli-core.js
228365
228715
  var { mapValues, omit, partition, pick } = import_lodash15.default;
@@ -228389,7 +228739,7 @@ var CliCore = class {
228389
228739
  throw new Error("Invalid analysis timeout value");
228390
228740
  }
228391
228741
  }
228392
- this.rootWorkingDirectory = resolve33(rootWorkingDirectory);
228742
+ this.rootWorkingDirectory = resolve34(rootWorkingDirectory);
228393
228743
  this.spinner = Spinner.instance({
228394
228744
  text: "Running Coana CLI",
228395
228745
  isSilent: this.options.silentSpinner ?? this.options.silent
@@ -228464,7 +228814,7 @@ var CliCore = class {
228464
228814
  }
228465
228815
  }
228466
228816
  async main() {
228467
- this.coanaLogPath = join26(await createTmpDirectory("coana-cli-"), "coana-log.txt");
228817
+ this.coanaLogPath = join27(await createTmpDirectory("coana-cli-"), "coana-log.txt");
228468
228818
  logger.initWinstonLogger(this.options.debug, this.coanaLogPath);
228469
228819
  logger.silent = this.options.silent;
228470
228820
  try {
@@ -228562,7 +228912,7 @@ var CliCore = class {
228562
228912
  this.sendProgress("RUN_ON_SUBPROJECT", false, this.rootWorkingDirectory);
228563
228913
  }
228564
228914
  const socketReport = toSocketFactsSocketDependencyTree(artifacts, vulnsWithResults, this.reportId);
228565
- const outputFile = resolve33(this.options.socketMode);
228915
+ const outputFile = resolve34(this.options.socketMode);
228566
228916
  await writeFile10(outputFile, JSON.stringify(socketReport, null, 2));
228567
228917
  logger.info(kleur_default.green(`Socket report written to: ${outputFile}`));
228568
228918
  }
@@ -228580,13 +228930,13 @@ var CliCore = class {
228580
228930
  throw new Error("Dependency trees should be available when using --socket-mode");
228581
228931
  }
228582
228932
  const socketReport = toSocketFacts(report, this.reportDependencyTrees, subPjToWsPathToDirectDependencies);
228583
- const outputFile = resolve33(this.options.socketMode);
228933
+ const outputFile = resolve34(this.options.socketMode);
228584
228934
  await writeFile10(outputFile, JSON.stringify(socketReport, null, 2));
228585
228935
  logger.info(kleur_default.green(`Socket report written to: ${outputFile}`));
228586
228936
  return;
228587
228937
  }
228588
228938
  if (outputDir) {
228589
- const jsonReportPath = resolve33(outputDir, `${DEFAULT_REPORT_FILENAME_BASE}.json`);
228939
+ const jsonReportPath = resolve34(outputDir, `${DEFAULT_REPORT_FILENAME_BASE}.json`);
228590
228940
  await mkdir2(outputDir, { recursive: true });
228591
228941
  writeFileSync3(jsonReportPath, JSON.stringify(report, null, 2));
228592
228942
  logger.info(kleur_default.green(`JSON report written to: ${jsonReportPath}`));
@@ -228624,7 +228974,7 @@ var CliCore = class {
228624
228974
  const { reachabilitySupport, traditionalScaSupport, noSupport } = manager.getSubprojectsWithWorkspacePaths();
228625
228975
  await this.dashboardAPI.registerSubprojects([...reachabilitySupport, ...traditionalScaSupport, ...noSupport].map((sp) => ({
228626
228976
  ...sp,
228627
- subprojectPath: relative14(this.rootWorkingDirectory, sp.subprojectPath) || "."
228977
+ subprojectPath: relative15(this.rootWorkingDirectory, sp.subprojectPath) || "."
228628
228978
  })), this.reportId, this.apiKey);
228629
228979
  for (const unsupported of noSupport)
228630
228980
  logger.warn(unsupported.unsupportedMsg);
@@ -228653,7 +229003,7 @@ var CliCore = class {
228653
229003
  await this.spinner.succeed();
228654
229004
  } catch (error) {
228655
229005
  if (this.options.ignoreFailingWorkspaces) {
228656
- const relativeSubprojectPath = relative14(this.rootWorkingDirectory, subprojectAndWsPath.subprojectPath) || ".";
229006
+ const relativeSubprojectPath = relative15(this.rootWorkingDirectory, subprojectAndWsPath.subprojectPath) || ".";
228657
229007
  this.failedSubprojects.push({
228658
229008
  subproject: relativeSubprojectPath,
228659
229009
  error: error.message || "Unknown error"
@@ -228712,7 +229062,7 @@ Subproject: ${subproject}`);
228712
229062
  }
228713
229063
  async updateSpinnerTextOnNewSubproject(subprojectAndWsPath, numberSubprojects, index2) {
228714
229064
  this.spinner.start();
228715
- const relativeSubprojectPath = relative14(this.rootWorkingDirectory, subprojectAndWsPath.subprojectPath) || ".";
229065
+ const relativeSubprojectPath = relative15(this.rootWorkingDirectory, subprojectAndWsPath.subprojectPath) || ".";
228716
229066
  await this.spinner.setText(numberSubprojects > 1 ? `Processing subproject ${relativeSubprojectPath} (${index2 + 1}/${numberSubprojects})${+this.options.concurrency > 1 ? `. May process up to ${+this.options.concurrency - 1} other workspaces in parallel` : ""}` : `Processing ${relativeSubprojectPath}`);
228717
229067
  }
228718
229068
  async initialize() {
@@ -228790,7 +229140,7 @@ Subproject: ${subproject}`);
228790
229140
  return workspaceToAugmentedVulnerabilities[workspacePath] !== void 0;
228791
229141
  }).map((workspacePath) => {
228792
229142
  return {
228793
- subprojectPath: relative14(this.rootWorkingDirectory, subprojectPath) || ".",
229143
+ subprojectPath: relative15(this.rootWorkingDirectory, subprojectPath) || ".",
228794
229144
  workspacePath,
228795
229145
  directDependencies: projectInfo[workspacePath].dataForAnalysis.directDependenciesMap ?? {},
228796
229146
  vulnerabilities: workspaceToAugmentedVulnerabilities[workspacePath],
@@ -228889,7 +229239,7 @@ Subproject: ${subproject}`);
228889
229239
  excludeDirs: this.options.excludeDirs ?? [],
228890
229240
  changedFiles: this.options.changedFiles,
228891
229241
  includeDirs: this.options.includeDirs ?? []
228892
- }, resolve33(subprojectPath, workspacePath));
229242
+ }, resolve34(subprojectPath, workspacePath));
228893
229243
  if (shouldExcludeWorkspaceForAnalysis) {
228894
229244
  logger.info(`Skipping reachability analysis for workspace ${workspacePath} due to it being excluded.`);
228895
229245
  }
@@ -228920,7 +229270,7 @@ Subproject: ${subproject}`);
228920
229270
  async sendProgress(type, isStartEvent, subprojectPath, workspacePath) {
228921
229271
  await this.dashboardAPI.registerCLIProgress({
228922
229272
  type,
228923
- ...subprojectPath ? { subprojectPath: relative14(this.rootWorkingDirectory, subprojectPath) || "." } : {},
229273
+ ...subprojectPath ? { subprojectPath: relative15(this.rootWorkingDirectory, subprojectPath) || "." } : {},
228924
229274
  ...workspacePath ? { workspacePath } : {}
228925
229275
  }, isStartEvent, this.reportId, this.apiKey);
228926
229276
  }
@@ -228976,7 +229326,7 @@ Subproject: ${subproject}`);
228976
229326
  dependencyTree: workspaceToPlainDependencyTree[workspacePath],
228977
229327
  ecosystem: workspaceToPlainDependencyTree[workspacePath].ecosystem ?? "NPM",
228978
229328
  workspacePath,
228979
- subprojectPath: relative14(rootWorkingDirectory, subprojectPath) || "."
229329
+ subprojectPath: relative15(rootWorkingDirectory, subprojectPath) || "."
228980
229330
  }));
228981
229331
  if (this.options.socketMode) {
228982
229332
  this.reportDependencyTrees = workspacePaths.map((workspacePath) => ({
@@ -228984,7 +229334,7 @@ Subproject: ${subproject}`);
228984
229334
  dependencyTree: projectInfo[workspacePath].dataForAnalysis.data.dependencyTree,
228985
229335
  ecosystem: projectInfo[workspacePath].dataForAnalysis.data.dependencyTree.ecosystem ?? "NPM",
228986
229336
  workspacePath,
228987
- subprojectPath: relative14(rootWorkingDirectory, subprojectPath) || "."
229337
+ subprojectPath: relative15(rootWorkingDirectory, subprojectPath) || "."
228988
229338
  }));
228989
229339
  }
228990
229340
  if (this.shareWithDashboard)
@@ -229000,7 +229350,7 @@ Subproject: ${subproject}`);
229000
229350
  } catch (e) {
229001
229351
  logger.error(`Scanning for vulnerabilities failed for subproject ${subprojectPath} in workspace ${workspacePath}`);
229002
229352
  if (this.options.ignoreFailingWorkspaces) {
229003
- const relativeSubprojectPath = relative14(this.rootWorkingDirectory, subprojectPath) || ".";
229353
+ const relativeSubprojectPath = relative15(this.rootWorkingDirectory, subprojectPath) || ".";
229004
229354
  this.failedWorkspaces.push({
229005
229355
  subproject: relativeSubprojectPath,
229006
229356
  workspace: workspacePath,
@@ -229019,7 +229369,7 @@ Subproject: ${subproject}`);
229019
229369
  }
229020
229370
  };
229021
229371
  function getRelativeSubprojectPath(subprojectPath, projectDir) {
229022
- return relative14(projectDir, subprojectPath) || ".";
229372
+ return relative15(projectDir, subprojectPath) || ".";
229023
229373
  }
229024
229374
  function getDependencyType(vulnChainDetails, codeAwareScanResults, directDependencies, reachability) {
229025
229375
  if (reachability === "UNREACHABLE" || reachability === "UNKNOWN") {
@@ -229063,369 +229413,6 @@ async function getGitDataToMetadataIfAvailable(rootWorkingDirectory) {
229063
229413
  }
229064
229414
  }
229065
229415
 
229066
- // dist/cli-upgrade-purl.js
229067
- import { join as join27, relative as relative15, resolve as resolve34 } from "node:path";
229068
- var import_packageurl_js3 = __toESM(require_packageurl_js(), 1);
229069
- var ECOSYSTEMS_WITH_SOCKET_UPGRADES = ["NPM", "MAVEN", "NUGET", "GO", "RUST"];
229070
- async function upgradePurl(rootDir, upgrades, options, logFile, cliFixRunId) {
229071
- if (options.rangeStyle && options.rangeStyle !== "pin") {
229072
- throw new Error('Range style must be "pin"');
229073
- }
229074
- logger.initWinstonLogger(options.debug);
229075
- logger.silent = options.silent;
229076
- let cliRunId = cliFixRunId;
229077
- if (!cliRunId && options.manifestsTarHash) {
229078
- cliRunId = await getSocketAPI().registerAutofixOrUpgradePurlRun(options.manifestsTarHash, options, "upgrade-purls");
229079
- }
229080
- const upgradePurlRunId = cliRunId && await getSocketAPI().registerUpgradePurlRun(cliRunId, upgrades);
229081
- Spinner.instance({
229082
- text: "Running Coana Upgrade Purl CLI",
229083
- isSilent: options.silentSpinner ?? options.silent
229084
- }).start();
229085
- try {
229086
- logger.info(`Upgrading purls for ${rootDir}:
229087
- ${upgrades.map(({ purl, upgradeVersion }) => ` ${prettyPrintPurlUpgrade(purl, upgradeVersion)}`).join("\n")}`);
229088
- if (options.manifestsTarHash) {
229089
- const { supportedUpgrades, unsupportedUpgrades } = upgrades.reduce((acc, upgrade) => {
229090
- const ecosystem = getAdvisoryEcosystemFromPurl(upgrade.purl);
229091
- const target = ECOSYSTEMS_WITH_SOCKET_UPGRADES.includes(ecosystem) ? "supportedUpgrades" : "unsupportedUpgrades";
229092
- acc[target].push(upgrade);
229093
- return acc;
229094
- }, { supportedUpgrades: [], unsupportedUpgrades: [] });
229095
- if (unsupportedUpgrades.length > 0) {
229096
- logger.warn(`The following upgrades are not supported due to missing support for upgrading their ecosystem: ${unsupportedUpgrades.map(({ purl, upgradeVersion }) => ` ${prettyPrintPurlUpgrade(purl, upgradeVersion)}`).join("\n")}`);
229097
- }
229098
- if (supportedUpgrades.length === 0) {
229099
- return "fixed-none";
229100
- }
229101
- try {
229102
- const purlToUpgradeVersion = new Map(supportedUpgrades.map((upgrade) => [upgrade.purl, upgrade.upgradeVersion]));
229103
- const [manifestFiles, artifacts] = await Promise.all([
229104
- fetchManifestFilesFromManifestsTarHash(options.manifestsTarHash),
229105
- (await fetchArtifactsFromSocket(rootDir, options.manifestsTarHash, "upgrade-purls")).artifacts
229106
- ]);
229107
- const ecosystemToSocketArtifactUpgrades = /* @__PURE__ */ new Map();
229108
- artifacts.forEach((artifact, idx) => {
229109
- if (!artifact.name)
229110
- return;
229111
- if (!artifact.version)
229112
- return;
229113
- const purl = new import_packageurl_js3.PackageURL(artifact.type, artifact.namespace, artifact.name, artifact.version, artifact.qualifiers).toString();
229114
- const upgradeVersion = purlToUpgradeVersion.get(purl);
229115
- if (!upgradeVersion)
229116
- return;
229117
- const ecosystem = getAdvisoryEcosystemFromPurlType(artifact.type);
229118
- if (!ecosystemToSocketArtifactUpgrades.has(ecosystem)) {
229119
- ecosystemToSocketArtifactUpgrades.set(ecosystem, /* @__PURE__ */ new Map());
229120
- }
229121
- const currentUpgradeVersion = ecosystemToSocketArtifactUpgrades.get(ecosystem).get(idx);
229122
- if (currentUpgradeVersion === void 0) {
229123
- ecosystemToSocketArtifactUpgrades.get(ecosystem).set(idx, upgradeVersion);
229124
- } else {
229125
- const versions = sortVersions(ecosystem, [artifact.version, currentUpgradeVersion, upgradeVersion]);
229126
- if (versionSatisfiesRelation(ecosystem, artifact.version, "=", versions[0])) {
229127
- ecosystemToSocketArtifactUpgrades.get(ecosystem).set(idx, versions[versions.length - 1]);
229128
- } else if (versionSatisfiesRelation(ecosystem, artifact.version, "=", versions[versions.length - 1])) {
229129
- ecosystemToSocketArtifactUpgrades.get(ecosystem).set(idx, versions[0]);
229130
- } else {
229131
- ecosystemToSocketArtifactUpgrades.get(ecosystem).set(idx, versions[versions.length - 1]);
229132
- }
229133
- }
229134
- });
229135
- let anyErrors = false;
229136
- for (const [ecosystem, upgrades2] of ecosystemToSocketArtifactUpgrades) {
229137
- if (options.rangeStyle && !["NPM", "MAVEN", "NUGET", "RUST"].includes(ecosystem)) {
229138
- logger.warn(`Range style is not supported for ${ecosystem}, skipping upgrades`);
229139
- continue;
229140
- }
229141
- const statusUpdater = (update2) => {
229142
- const statusIcons = {
229143
- success: "\u2705",
229144
- skipped: "\u26AA",
229145
- warn: "\u26A0\uFE0F",
229146
- error: "\u274C"
229147
- };
229148
- logger.info(`${statusIcons[update2.status]} ${update2.message} \u2500 ${relative15(rootDir, resolve34(rootDir, update2.file))}`);
229149
- update2.artifacts.forEach((idx, i7) => {
229150
- logger.info(`${" ".repeat(3)}${i7 === update2.artifacts.length - 1 ? "\u2514\u2500" : "\u251C\u2500"} ${prettyPrintSocketFactArtifactUpgrade(artifacts[idx], upgrades2.get(idx))}`);
229151
- });
229152
- for (const detail of update2.details ?? []) {
229153
- logger.debug(detail);
229154
- }
229155
- if (update2.patch)
229156
- logger.debug(update2.patch);
229157
- if (update2.status === "error")
229158
- anyErrors = true;
229159
- };
229160
- const ctxt = {
229161
- manifestFiles,
229162
- upgrades: upgrades2,
229163
- artifacts,
229164
- rangeStyle: options.rangeStyle,
229165
- statusUpdater
229166
- };
229167
- await applySocketUpgrades(ecosystem, rootDir, ctxt);
229168
- }
229169
- if (upgradePurlRunId) {
229170
- await getSocketAPI().finalizeUpgradePurlRun(upgradePurlRunId, "succeeded");
229171
- }
229172
- return unsupportedUpgrades.length === 0 && !anyErrors ? "fixed-all" : "fixed-some";
229173
- } catch (error) {
229174
- if (upgradePurlRunId) {
229175
- await getSocketAPI().finalizeUpgradePurlRun(
229176
- upgradePurlRunId,
229177
- "error",
229178
- !cliFixRunId ? error.stack : void 0,
229179
- // do not send stack trace and logContent for computeFixes runs, as that will be handled by that command.
229180
- !cliFixRunId && logFile ? await logger.getLogContent(logFile) : void 0
229181
- );
229182
- }
229183
- throw error;
229184
- }
229185
- }
229186
- const otherModulesCommunicator = new OtherModulesCommunicator(rootDir, options, {
229187
- type: "missing"
229188
- });
229189
- const ecosystems = upgrades.map((upgrade) => getAdvisoryEcosystemFromPurl(upgrade.purl));
229190
- const manager = await ProjectManager.create(rootDir, otherModulesCommunicator, ecosystems);
229191
- const { reachabilitySupport, traditionalScaSupport } = manager.getSubprojectsWithWorkspacePaths();
229192
- const supportedSubprojects = reachabilitySupport.concat(traditionalScaSupport).filter((p3) => getPackageManagerSupport(p3.packageManagerName).supportsApplyingFixes);
229193
- if (supportedSubprojects.length === 0) {
229194
- throw new Error(`No supported projects found in ${rootDir}.`);
229195
- }
229196
- const subprojectPromiseQueue = new PromiseQueue(Number(options.concurrency));
229197
- supportedSubprojects.forEach((subproject) => {
229198
- subprojectPromiseQueue.enqueueTask(async () => {
229199
- const workspacePathsMatchingGlob = subproject.workspacePaths.filter((wsPath) => minimatch(join27(subproject.subprojectPath, wsPath), options.globPattern ?? "**"));
229200
- if (workspacePathsMatchingGlob.length === 0)
229201
- return;
229202
- logger.info(`Found workspaces for subproject ${subproject.subprojectPath}${options.globPattern ? `matching glob ${options.globPattern}` : ""}:
229203
- ${workspacePathsMatchingGlob.map((wsPath) => ` ${wsPath}`).join("\n")}`);
229204
- const fixingData = await otherModulesCommunicator.getFixingData(subproject.packageManagerName, subproject.subprojectPath, workspacePathsMatchingGlob);
229205
- const workspaceToFixes = {};
229206
- Object.entries(fixingData.dependencyTrees).forEach(([wsPath, depTree]) => {
229207
- const vulnerabilityFixes = [];
229208
- const simplePurlToDepId = getPurlStrings(depTree);
229209
- upgrades.forEach((upgrade) => {
229210
- const purl = import_packageurl_js3.PackageURL.fromString(upgrade.purl);
229211
- if (purl.version === void 0)
229212
- throw Error(`Undefined version for purl ${upgrade.purl}`);
229213
- const simplePurl2 = `pkg:${purl.type}/${purl.namespace ? `${purl.namespace}/` : ""}${purl.name}${purl.version ? `@${purl.version}` : ""}`;
229214
- for (const depIdMatchingPurl of simplePurlToDepId[simplePurl2] ?? []) {
229215
- const node = depTree.transitiveDependencies[depIdMatchingPurl];
229216
- if (!node)
229217
- throw Error("should not happen!");
229218
- vulnerabilityFixes.push({
229219
- dependencyName: node.packageName,
229220
- currentVersion: assertDefined(node.version),
229221
- dependencyIdentifier: depIdMatchingPurl,
229222
- fixedVersion: upgrade.upgradeVersion
229223
- });
229224
- }
229225
- });
229226
- if (vulnerabilityFixes.length === 0)
229227
- return;
229228
- logger.info(`Found ${vulnerabilityFixes.length} ${vulnerabilityFixes.length === 1 ? "dependency" : "dependencies"} matching upgrade specs for ${join27(subproject.subprojectPath, wsPath)}`);
229229
- workspaceToFixes[wsPath] = [
229230
- {
229231
- fixId: "dummy",
229232
- vulnerabilityFixes
229233
- }
229234
- ];
229235
- });
229236
- if (Object.entries(workspaceToFixes).length === 0) {
229237
- logger.info(`No dependencies matching upgrade specs found for subproject ${subproject.subprojectPath}`);
229238
- return;
229239
- }
229240
- await applySecurityFixes(subproject.packageManagerName, rootDir, relative15(rootDir, subproject.subprojectPath) || ".", otherModulesCommunicator, workspaceToFixes, fixingData, signalFixApplied);
229241
- });
229242
- });
229243
- await subprojectPromiseQueue.onIdle();
229244
- } finally {
229245
- Spinner.instance().stop();
229246
- }
229247
- }
229248
- var signalFixApplied = (_fixId, subprojectPath, workspacePath, vulnerabilityFixes) => {
229249
- logger.info(`Successfully upgraded purls for: ${join27(subprojectPath, workspacePath)}`);
229250
- logger.info(`Upgraded:
229251
- ${vulnerabilityFixes.map((fix) => ` ${fix.dependencyName} from ${fix.currentVersion} to ${fix.fixedVersion}`).join("\n")}`);
229252
- };
229253
-
229254
- // dist/cli-compute-fixes-and-upgrade-purls.js
229255
- async function computeFixesAndUpgradePurls(path2, options, logFile) {
229256
- const autofixRunId = options.manifestsTarHash && await getSocketAPI().registerAutofixOrUpgradePurlRun(options.manifestsTarHash, options, "autofix");
229257
- const { artifacts, ghsaToVulnerableArtifactIds } = await computeInputForComputingFixes(path2, options);
229258
- if (Object.keys(ghsaToVulnerableArtifactIds).length === 0) {
229259
- logger.info("No vulnerabilities to compute fixes for");
229260
- return { type: "no-vulnerabilities-found" };
229261
- }
229262
- if (options.applyFixesTo.length === 0) {
229263
- logger.info("Vulnerabilities found:", Object.keys(ghsaToVulnerableArtifactIds).join(", "));
229264
- logger.info("Run again with --apply-fixes-to GHSA_IDS to fix those vulnerabilities by computing packages to upgrade and apply them");
229265
- return { type: "no-ghsas-fix-requested", ghsas: Object.keys(ghsaToVulnerableArtifactIds) };
229266
- }
229267
- const ghsaToVulnerableArtifactIdsToApply = options.applyFixesTo.includes("all") ? ghsaToVulnerableArtifactIds : Object.fromEntries(Object.entries(ghsaToVulnerableArtifactIds).filter(([ghsa]) => options.applyFixesTo.includes(ghsa)));
229268
- const computedFix = await useSocketComputeFixEndpoint(autofixRunId, artifacts, ghsaToVulnerableArtifactIdsToApply, {
229269
- noMajorUpdates: options.disableMajorUpdates,
229270
- minimumReleaseAgeInMinutes: options.minimumReleaseAgeInMinutes
229271
- });
229272
- if (computedFix.type !== "success") {
229273
- throw new Error(`No fix found for the given vulnerabilities`);
229274
- }
229275
- const ghsasFailedToFix = Object.keys(ghsaToVulnerableArtifactIdsToApply).filter((ghsa) => {
229276
- const artifactIds = ghsaToVulnerableArtifactIdsToApply[ghsa];
229277
- if (!artifactIds)
229278
- return false;
229279
- return artifactIds.some((artifactId) => computedFix.ghsaToResult[ghsa].failedArtifacts?.includes(artifactId));
229280
- });
229281
- if (ghsasFailedToFix.length > 0) {
229282
- logger.info("Failed to compute fixes for the following vulnerabilities:");
229283
- }
229284
- for (const ghsa of ghsasFailedToFix) {
229285
- logger.info(` - ${ghsa} (${ghsaToVulnerableArtifactIdsToApply[ghsa].map((id) => simplePurl(artifacts[id].type, artifacts[id].namespace ?? null, artifacts[id].name ?? "", artifacts[id].version ?? null)).join(", ")})`);
229286
- }
229287
- const fixesFound = Object.entries(computedFix.ghsaToResult).filter(([_, result]) => result.failedArtifacts === void 0 || result.failedArtifacts.length === 0);
229288
- const combinedFixes = fixesFound.flatMap(([_, result]) => result.fixes);
229289
- if (options.dryRun) {
229290
- logger.info("Fixes found:");
229291
- for (const [ghsa, result] of fixesFound) {
229292
- logger.info(` - ${ghsa}:`);
229293
- for (const fix of result.fixes) {
229294
- logger.info(` - ${fix.purl} -> ${fix.fixedVersion}`);
229295
- }
229296
- }
229297
- return {
229298
- type: "dry-run-result",
229299
- fixes: Object.fromEntries(fixesFound.map(([ghsa, result]) => [ghsa, result.fixes])),
229300
- ...ghsasFailedToFix.length > 0 && { failedToFix: ghsasFailedToFix }
229301
- };
229302
- }
229303
- if (combinedFixes.length === 0) {
229304
- if (autofixRunId) {
229305
- await getSocketAPI().finalizeAutofixRun(autofixRunId, "fixed-none");
229306
- }
229307
- throw new Error("Failed to find a fix for the given vulnerabilities");
229308
- }
229309
- try {
229310
- const applyFixesStatus = await upgradePurl(path2, T3(combinedFixes, (fix) => `${fix.purl}${fix.fixedVersion}`).map((fix) => ({
229311
- purl: fix.purl,
229312
- upgradeVersion: fix.fixedVersion
229313
- })), {
229314
- debug: options.debug,
229315
- silent: options.silent,
229316
- runWithoutDocker: options.runWithoutDocker,
229317
- manifestsTarHash: options.manifestsTarHash,
229318
- concurrency: "1",
229319
- globPattern: options.globPattern,
229320
- rangeStyle: options.rangeStyle
229321
- }, void 0, autofixRunId) ?? "fixed-all";
229322
- if (autofixRunId) {
229323
- await getSocketAPI().finalizeAutofixRun(autofixRunId, ghsasFailedToFix.length === 0 && applyFixesStatus === "fixed-all" ? "fixed-all" : ghsasFailedToFix.length === Object.keys(ghsaToVulnerableArtifactIdsToApply).length || applyFixesStatus === "fixed-none" ? "fixed-none" : "fixed-some");
229324
- }
229325
- return {
229326
- type: "applied-fixes",
229327
- fixes: Object.fromEntries(fixesFound.map(([ghsa, result]) => [ghsa, result.fixes]))
229328
- };
229329
- } catch (error) {
229330
- if (autofixRunId) {
229331
- await getSocketAPI().finalizeAutofixRun(autofixRunId, "error", error.stack, await logger.getLogContent(logFile));
229332
- }
229333
- logger.error("Error applying fixes:", error);
229334
- throw error;
229335
- }
229336
- }
229337
- async function computeInputForComputingFixes(path2, options) {
229338
- if (options.manifestsTarHash) {
229339
- const { artifacts: artifacts2 } = await fetchArtifactsFromSocket(path2, options.manifestsTarHash, "autofix");
229340
- const ghsaToVulnerableArtifactIds2 = {};
229341
- for (const [index2, artifact] of artifacts2.entries()) {
229342
- if (!artifact.vulnerabilities)
229343
- continue;
229344
- for (const vulnerability of artifact.vulnerabilities) {
229345
- if (!(ghsaToVulnerableArtifactIds2[vulnerability.ghsaId] ??= []).includes(index2)) {
229346
- ghsaToVulnerableArtifactIds2[vulnerability.ghsaId].push(index2);
229347
- }
229348
- }
229349
- }
229350
- const sbomTaskArtifacts = artifacts2.map((artifact) => ({
229351
- type: artifact.type,
229352
- name: artifact.name ?? "",
229353
- version: artifact.version ?? "",
229354
- namespace: artifact.namespace ?? void 0,
229355
- adj: artifact.dependencies?.map((dep) => artifacts2.findIndex((a4) => a4.id === dep)) ?? []
229356
- }));
229357
- return { artifacts: sbomTaskArtifacts, ghsaToVulnerableArtifactIds: ghsaToVulnerableArtifactIds2 };
229358
- }
229359
- const otherModulesCommunicator = new OtherModulesCommunicator(path2, options, {
229360
- type: "missing"
229361
- });
229362
- const manager = await ProjectManager.create(path2, otherModulesCommunicator);
229363
- const { reachabilitySupport, traditionalScaSupport } = manager.getSubprojectsWithWorkspacePaths();
229364
- const supportedSubprojects = reachabilitySupport.concat(traditionalScaSupport).filter((p3) => getPackageManagerSupport(p3.packageManagerName).supportsApplyingFixes);
229365
- if (supportedSubprojects.length === 0) {
229366
- throw new Error(`No supported projects found in ${path2}.`);
229367
- }
229368
- const cliCore = new CliCore(path2, { ...defaultCliOptions, socketMode: "true" });
229369
- const results = await asyncMap(supportedSubprojects, async (subproject) => cliCore.getDependencyTreeAndVulnerabilities(otherModulesCommunicator, subproject));
229370
- const { artifacts, purlToIndex } = computeSBOMTaskArtifacts(results.flatMap((r3) => Object.values(r3.projectInfo).map((info) => info.dataForAnalysis.data.dependencyTree)));
229371
- const ghsaToVulnerableArtifactIds = computeVulnerableArtifactIdsPerVulnerability(results.flatMap((r3) => Object.values(r3.workspaceToVulnerabilities).flat()), purlToIndex);
229372
- return { artifacts, ghsaToVulnerableArtifactIds };
229373
- }
229374
- function computeVulnerableArtifactIdsPerVulnerability(vulnerabilities, purlToIndex) {
229375
- const vulnerableArtifactIdsPerVulnerability = {};
229376
- for (const vulnerability of vulnerabilities) {
229377
- if (!vulnerableArtifactIdsPerVulnerability[vulnerability.url]) {
229378
- vulnerableArtifactIdsPerVulnerability[vulnerability.url] = [];
229379
- }
229380
- if (!vulnerability.purl)
229381
- throw new Error(`Vulnerability ${vulnerability.url} has no purl`);
229382
- if (!purlToIndex.has(vulnerability.purl)) {
229383
- throw new Error(`Vulnerability ${vulnerability.url} has no purl in sbomTaskArtifacts`);
229384
- }
229385
- const index2 = purlToIndex.get(vulnerability.purl);
229386
- if (!vulnerableArtifactIdsPerVulnerability[vulnerability.url].includes(index2)) {
229387
- vulnerableArtifactIdsPerVulnerability[vulnerability.url].push(index2);
229388
- }
229389
- }
229390
- return vulnerableArtifactIdsPerVulnerability;
229391
- }
229392
- function computeSBOMTaskArtifacts(dependencyTrees) {
229393
- const components = [];
229394
- const purlToIndex = /* @__PURE__ */ new Map();
229395
- for (const dependencyTree of dependencyTrees) {
229396
- const depIdentifierToPurl = Object.fromEntries(Object.entries(dependencyTree.transitiveDependencies).filter(([_depIdentifier, dep]) => dep.purlObj).map(([depIdentifier, dep]) => {
229397
- const purl = dep.purlObj.purlString;
229398
- if (purl && !purlToIndex.has(purl)) {
229399
- purlToIndex.set(purl, components.length);
229400
- const depTreeNode = dependencyTree.transitiveDependencies[depIdentifier];
229401
- components[purlToIndex.get(purl)] = {
229402
- type: depTreeNode.purlObj.type,
229403
- name: depTreeNode.purlObj.name,
229404
- version: depTreeNode.purlObj.version,
229405
- namespace: depTreeNode.purlObj.namespace,
229406
- adj: []
229407
- };
229408
- }
229409
- return [depIdentifier, purl];
229410
- }));
229411
- for (const [depIdentifier, purl] of Object.entries(depIdentifierToPurl)) {
229412
- const depTreeNode = dependencyTree.transitiveDependencies[depIdentifier];
229413
- if (!depTreeNode.purlObj) {
229414
- continue;
229415
- }
229416
- const component = components[purlToIndex.get(purl)];
229417
- depTreeNode.dependencies?.forEach((dep) => {
229418
- const depPurl = depIdentifierToPurl[dep];
229419
- const depIndex = purlToIndex.get(depPurl);
229420
- if (depIndex && !component.adj?.includes(depIndex)) {
229421
- component.adj.push(depIndex);
229422
- }
229423
- });
229424
- }
229425
- }
229426
- return { artifacts: components, purlToIndex };
229427
- }
229428
-
229429
229416
  // dist/index.js
229430
229417
  var program2 = new Command();
229431
229418
  var run2 = new Command();
@@ -229459,7 +229446,7 @@ upgradePurls.name("upgrade-purls").argument("<path>", "File system path to the f
229459
229446
  });
229460
229447
  }).configureHelp({ sortOptions: true });
229461
229448
  var computeFixesAndUpgradePurlsCmd = new Command();
229462
- computeFixesAndUpgradePurlsCmd.name("compute-fixes-and-upgrade-purls").argument("<path>", "File system path to the folder containing the project").option("-a, --apply-fixes-to <ghsas...>", 'GHSA IDs to compute fixes for. Use "all" to compute fixes for all vulnerabilities.', []).option("--dry-run", "Show what changes would be made without actually making them", false).option("-g, --glob <pattern>", "Glob pattern to filter workspaces by absolute file path").option("-d, --debug", "Enable debug logging", false).option("-s, --silent", "Silence all debug/warning output", false).option("--silent-spinner", "Silence spinner", "CI" in process.env || !process.stdin.isTTY).option("--range-style <style>", 'Range style to use for the output. Currently only "pin" is supported and it only works for npm.').option("--disable-major-updates", "Do not suggest major updates. If only major update are available, the fix will not be applied.", false).option("-o, --output-file <file>", "Writes output to a JSON file").option("--minimum-release-age <minimumReleaseAge>", "Do not allow upgrades to package versions that are newer than minimumReleaseAge. Format is 2m, 5h, 3d or 1w").addOption(new Option("--run-without-docker", "Run package managers without using docker").default(process.env.RUN_WITHOUT_DOCKER === "true").hideHelp()).addOption(new Option("--manifests-tar-hash <hash>", "Hash of the tarball containing all manifest files already uploaded to Socket. If provided, Socket will be used for computing dependency trees.").hideHelp()).version(version2).action(async (path2, options) => {
229449
+ computeFixesAndUpgradePurlsCmd.name("compute-fixes-and-upgrade-purls").argument("<path>", "File system path to the folder containing the project").option("-a, --apply-fixes-to <ghsas...>", 'GHSA IDs to compute fixes for. Use "all" to compute fixes for all vulnerabilities.', []).option("--dry-run", "Show what changes would be made without actually making them", false).option("-g, --glob <pattern>", "Glob pattern to filter workspaces by absolute file path").option("-d, --debug", "Enable debug logging", false).option("-s, --silent", "Silence all debug/warning output", false).option("--silent-spinner", "Silence spinner", "CI" in process.env || !process.stdin.isTTY).option("--range-style <style>", 'Range style to use for the output. Currently only "pin" is supported and it only works for npm.').option("--disable-major-updates", "Do not suggest major updates. If only major update are available, the fix will not be applied.", false).option("-o, --output-file <file>", "Writes output to a JSON file").option("--minimum-release-age <minimumReleaseAge>", "Do not allow upgrades to package versions that are newer than minimumReleaseAge. Format is 2m, 5h, 3d or 1w").option("--show-affected-direct-dependencies", "Show the affected direct dependencies for each vulnerability and what upgrades could fix them - does not apply the upgrades.", false).addOption(new Option("--run-without-docker", "Run package managers without using docker").default(process.env.RUN_WITHOUT_DOCKER === "true").hideHelp()).addOption(new Option("--manifests-tar-hash <hash>", "Hash of the tarball containing all manifest files already uploaded to Socket. If provided, Socket will be used for computing dependency trees.").hideHelp()).version(version2).action(async (path2, options) => {
229463
229450
  process.env.DOCKER_IMAGE_TAG ??= version2;
229464
229451
  if (options.outputFile && !options.outputFile.endsWith(".json")) {
229465
229452
  throw new Error("Output file must have a .json extension");
@@ -229473,6 +229460,7 @@ computeFixesAndUpgradePurlsCmd.name("compute-fixes-and-upgrade-purls").argument(
229473
229460
  await withTmpDirectory("compute-fixes-and-upgrade-purls", async (tmpDir) => {
229474
229461
  const logFile = join28(tmpDir, "compute-fixes-and-upgrade-purls.log");
229475
229462
  logger.initWinstonLogger(options.debug, logFile);
229463
+ await initializeComputeFixesAndUpgradePurls(path2, options);
229476
229464
  const optionsToUse = {
229477
229465
  ...y8(options, ["minimumReleaseAge"]),
229478
229466
  minimumReleaseAgeInMinutes: options.minimumReleaseAge ? parseMinimumReleaseAgeToMinutes(options.minimumReleaseAge) : void 0
@@ -229486,6 +229474,22 @@ computeFixesAndUpgradePurlsCmd.name("compute-fixes-and-upgrade-purls").argument(
229486
229474
  }
229487
229475
  });
229488
229476
  }).configureHelp({ sortOptions: true });
229477
+ async function initializeComputeFixesAndUpgradePurls(path2, options) {
229478
+ logger.info(`Coana CLI version ${version2} compute fixes and upgrade purls initiated on ${path2}`);
229479
+ logger.debug("running in debug mode");
229480
+ logger.debug("using options", JSON.stringify(a3(Object.fromEntries(Object.entries(options).filter(([_, value]) => value)), [
229481
+ "debug",
229482
+ "silent",
229483
+ "applyFixesTo",
229484
+ "dryRun",
229485
+ "globPattern",
229486
+ "manifestsTarHash",
229487
+ "rangeStyle",
229488
+ "disableMajorUpdates",
229489
+ "outputFile",
229490
+ "minimumReleaseAge"
229491
+ ]), null, 2));
229492
+ }
229489
229493
  var compareReportsCommand = new Command();
229490
229494
  compareReportsCommand.name("compare-reports").argument("<baselineReportPath>", "Path to the baseline report").argument("<newReportPath>", "Path to the new report").option("--api-key <key>", "Set the Coana dashboard API key.").option("-d, --debug", "Enable debug logging", false).option("--no-pr-comment", "Disable pull request comments (only relevant when run from a PR)", true).option("--no-block", "Do not fail with a non-zero exit code when new reachable vulnerabilities are detected", true).option("--ignore-undeterminable-reachability", "Ignore vulnerabilities with undeterminable reachability", false).action(async (baselineReportPath, newReportPath, options) => {
229491
229495
  async function readReport(reportPath) {