mobbdev 0.0.148 → 0.0.152

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +1640 -1513
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -32,663 +32,174 @@ import fs4 from "node:fs";
32
32
  import path7 from "node:path";
33
33
 
34
34
  // src/constants.ts
35
- import path from "node:path";
35
+ import path2 from "node:path";
36
36
  import { fileURLToPath } from "node:url";
37
37
  import chalk from "chalk";
38
38
  import Debug from "debug";
39
39
  import * as dotenv from "dotenv";
40
- import { z } from "zod";
41
- var debug = Debug("mobbdev:constants");
42
- var __dirname = path.dirname(fileURLToPath(import.meta.url));
43
- dotenv.config({ path: path.join(__dirname, "../.env") });
44
- var ScmTypes = {
45
- Github: "GitHub",
46
- Gitlab: "GitLab",
47
- AzureDevOps: "Ado"
48
- };
49
- var SCANNERS = {
50
- Checkmarx: "checkmarx",
51
- Codeql: "codeql",
52
- Fortify: "fortify",
53
- Snyk: "snyk",
54
- Sonarqube: "sonarqube"
55
- };
56
- var SupportedScannersZ = z.enum([SCANNERS.Checkmarx, SCANNERS.Snyk]);
57
- var envVariablesSchema = z.object({
58
- WEB_APP_URL: z.string(),
59
- API_URL: z.string(),
60
- HASURA_ACCESS_KEY: z.string(),
61
- LOCAL_GRAPHQL_ENDPOINT: z.string()
62
- }).required();
63
- var envVariables = envVariablesSchema.parse(process.env);
64
- debug("config %o", envVariables);
65
- var mobbAscii = `
66
- ..
67
- ..........
68
- .................
69
- ...........................
70
- ..............................
71
- ................................
72
- ..................................
73
- ....................................
74
- .....................................
75
- .............................................
76
- .................................................
77
- ............................... .................
78
- .................................. ............
79
- .................. ............. ..........
80
- ......... ........ ......... ......
81
- ............... ....
82
- .... ..
83
-
84
- . ...
85
- ..............
86
- ......................
87
- ...........................
88
- ................................
89
- ......................................
90
- ...............................
91
- .................
92
- `;
93
- var PROJECT_DEFAULT_NAME = "My first project";
94
- var WEB_APP_URL = envVariables.WEB_APP_URL;
95
- var API_URL = envVariables.API_URL;
96
- var HASURA_ACCESS_KEY = envVariables.HASURA_ACCESS_KEY;
97
- var LOCAL_GRAPHQL_ENDPOINT = envVariables.LOCAL_GRAPHQL_ENDPOINT;
98
- var errorMessages = {
99
- missingCxProjectName: `project name ${chalk.bold(
100
- "(--cx-project-name)"
101
- )} is needed if you're using checkmarx`,
102
- missingUrl: `url ${chalk.bold(
103
- "(--url)"
104
- )} is needed if you're adding an SCM token`,
105
- invalidScmType: `SCM type ${chalk.bold(
106
- "(--scm-type)"
107
- )} is invalid, please use one of: ${Object.values(ScmTypes).join(", ")}`,
108
- missingToken: `SCM token ${chalk.bold(
109
- "(--token)"
110
- )} is needed if you're adding an SCM token`
111
- };
112
- var progressMassages = {
113
- processingVulnerabilityReportSuccess: "\u2699\uFE0F Vulnerability report proccessed successfully",
114
- processingVulnerabilityReport: "\u2699\uFE0F Proccessing vulnerability report",
115
- processingVulnerabilityReportFailed: "\u2699\uFE0F Error Proccessing vulnerability report"
40
+ import { z as z10 } from "zod";
41
+
42
+ // src/features/analysis/scm/shared/src/types.ts
43
+ var scmCloudUrl = {
44
+ GitLab: "https://gitlab.com",
45
+ GitHub: "https://github.com",
46
+ Ado: "https://dev.azure.com",
47
+ Bitbucket: "https://bitbucket.org"
116
48
  };
117
- var VUL_REPORT_DIGEST_TIMEOUT_MS = 1e3 * 60 * 20;
49
+ var ScmType = /* @__PURE__ */ ((ScmType2) => {
50
+ ScmType2["GitHub"] = "GitHub";
51
+ ScmType2["GitLab"] = "GitLab";
52
+ ScmType2["Ado"] = "Ado";
53
+ ScmType2["Bitbucket"] = "Bitbucket";
54
+ return ScmType2;
55
+ })(ScmType || {});
118
56
 
119
- // src/features/analysis/index.ts
120
- import crypto from "node:crypto";
121
- import fs3 from "node:fs";
122
- import os from "node:os";
123
- import path6 from "node:path";
124
- import { pipeline } from "node:stream/promises";
57
+ // src/features/analysis/scm/ado/constants.ts
58
+ var DEFUALT_ADO_ORIGIN = scmCloudUrl.Ado;
125
59
 
126
- // src/generates/client_generates.ts
127
- var MeDocument = `
128
- query Me {
129
- me {
130
- id
131
- email
132
- scmConfigs {
133
- id
134
- orgId
135
- refreshToken
136
- scmType
137
- scmUrl
138
- scmUsername
139
- token
140
- tokenLastUpdate
141
- userId
142
- scmOrg
143
- isTokenAvailable
60
+ // src/features/analysis/scm/ado/utils.ts
61
+ import querystring3 from "node:querystring";
62
+ import * as api from "azure-devops-node-api";
63
+ import { z as z9 } from "zod";
64
+
65
+ // src/features/analysis/scm/env.ts
66
+ import { z } from "zod";
67
+ var EnvVariablesZod = z.object({
68
+ GITLAB_API_TOKEN: z.string().optional(),
69
+ BROKERED_HOSTS: z.string().toLowerCase().transform(
70
+ (x) => x.split(",").map((url) => url.trim(), []).filter(Boolean)
71
+ ).default(""),
72
+ GITHUB_API_TOKEN: z.string().optional(),
73
+ GIT_PROXY_HOST: z.string().default("http://tinyproxy:8888")
74
+ });
75
+ var { GITLAB_API_TOKEN, BROKERED_HOSTS, GITHUB_API_TOKEN, GIT_PROXY_HOST } = EnvVariablesZod.parse(process.env);
76
+
77
+ // src/features/analysis/scm/scm.ts
78
+ import { z as z7 } from "zod";
79
+
80
+ // src/features/analysis/scm/bitbucket/bitbucket.ts
81
+ import querystring from "node:querystring";
82
+ import bitbucketPkg from "bitbucket";
83
+ import * as bitbucketPkgNode from "bitbucket";
84
+ import { z as z3 } from "zod";
85
+
86
+ // src/features/analysis/scm/shared/src/urlParser/urlParser.ts
87
+ import { z as z2 } from "zod";
88
+ function detectAdoUrl(args) {
89
+ const { pathname, hostname, scmType } = args;
90
+ const hostnameParts = hostname.split(".");
91
+ const adoCloudHostname = new URL(scmCloudUrl.Ado).hostname;
92
+ const prefixPath = pathname.at(0)?.toLowerCase() === ADO_PREFIX_PATH ? ADO_PREFIX_PATH : "";
93
+ const normilizedPath = prefixPath ? pathname.slice(1) : pathname;
94
+ if (hostnameParts.length === 3 && hostnameParts[1] === "visualstudio" && hostnameParts[2] === "com") {
95
+ if (normilizedPath.length === 2 && normilizedPath[0] === "_git") {
96
+ const [_git, projectName] = normilizedPath;
97
+ const [organization] = hostnameParts;
98
+ return {
99
+ scmType: "Ado" /* Ado */,
100
+ organization,
101
+ // project has single repo - repoName === projectName
102
+ projectName: z2.string().parse(projectName),
103
+ repoName: projectName,
104
+ prefixPath
105
+ };
106
+ }
107
+ if (normilizedPath.length === 3 && normilizedPath[1] === "_git") {
108
+ const [projectName, _git, repoName] = normilizedPath;
109
+ const [organization] = hostnameParts;
110
+ return {
111
+ scmType: "Ado" /* Ado */,
112
+ organization,
113
+ projectName: z2.string().parse(projectName),
114
+ repoName,
115
+ prefixPath
116
+ };
144
117
  }
145
118
  }
146
- }
147
- `;
148
- var GetOrgAndProjectIdDocument = `
149
- query getOrgAndProjectId($filters: organization_to_organization_role_bool_exp, $limit: Int) {
150
- organization_to_organization_role(
151
- where: $filters
152
- order_by: {organization: {createdOn: desc}}
153
- limit: $limit
154
- ) {
155
- organization {
156
- id
157
- projects(order_by: {updatedAt: desc}) {
158
- id
159
- name
119
+ if (hostname === adoCloudHostname || scmType === "Ado" /* Ado */) {
120
+ if (normilizedPath[normilizedPath.length - 2] === "_git") {
121
+ if (normilizedPath.length === 3) {
122
+ const [organization, _git, repoName] = normilizedPath;
123
+ return {
124
+ scmType: "Ado" /* Ado */,
125
+ organization,
126
+ // project has only one repo - repoName === projectName
127
+ projectName: z2.string().parse(repoName),
128
+ repoName,
129
+ prefixPath
130
+ };
131
+ }
132
+ if (normilizedPath.length === 4) {
133
+ const [organization, projectName, _git, repoName] = normilizedPath;
134
+ return {
135
+ scmType: "Ado" /* Ado */,
136
+ organization,
137
+ projectName: z2.string().parse(projectName),
138
+ repoName,
139
+ prefixPath
140
+ };
160
141
  }
161
142
  }
162
143
  }
144
+ return null;
163
145
  }
164
- `;
165
- var GetEncryptedApiTokenDocument = `
166
- query GetEncryptedApiToken($loginId: uuid!) {
167
- cli_login_by_pk(id: $loginId) {
168
- encryptedApiToken
169
- }
170
- }
171
- `;
172
- var FixReportStateDocument = `
173
- query FixReportState($id: uuid!) {
174
- fixReport_by_pk(id: $id) {
175
- state
146
+ function detectGithubUrl(args) {
147
+ const { pathname, hostname, scmType } = args;
148
+ const githubHostname = new URL(scmCloudUrl.GitHub).hostname;
149
+ if (hostname === githubHostname || scmType === "GitHub" /* GitHub */) {
150
+ if (pathname.length === 2) {
151
+ return {
152
+ scmType: "GitHub" /* GitHub */,
153
+ organization: pathname[0],
154
+ repoName: pathname[1]
155
+ };
156
+ }
176
157
  }
158
+ return null;
177
159
  }
178
- `;
179
- var GetVulnerabilityReportPathsDocument = `
180
- query GetVulnerabilityReportPaths($vulnerabilityReportId: uuid!) {
181
- vulnerability_report_path(
182
- where: {vulnerabilityReportId: {_eq: $vulnerabilityReportId}}
183
- ) {
184
- path
160
+ function detectGitlabUrl(args) {
161
+ const { pathname, hostname, scmType } = args;
162
+ const gitlabHostname = new URL(scmCloudUrl.GitLab).hostname;
163
+ if (hostname === gitlabHostname || scmType === "GitLab" /* GitLab */) {
164
+ if (pathname.length >= 2) {
165
+ return {
166
+ scmType: "GitLab" /* GitLab */,
167
+ organization: pathname[0],
168
+ repoName: pathname[pathname.length - 1]
169
+ };
170
+ }
185
171
  }
172
+ return null;
186
173
  }
187
- `;
188
- var GetAnalysisDocument = `
189
- subscription getAnalysis($analysisId: uuid!) {
190
- analysis: fixReport_by_pk(id: $analysisId) {
191
- id
192
- state
174
+ function detectBitbucketUrl(args) {
175
+ const { pathname, hostname, scmType } = args;
176
+ const bitbucketHostname = new URL(scmCloudUrl.Bitbucket).hostname;
177
+ if (hostname === bitbucketHostname || scmType === "Bitbucket" /* Bitbucket */) {
178
+ if (pathname.length === 2) {
179
+ return {
180
+ scmType: "Bitbucket" /* Bitbucket */,
181
+ organization: pathname[0],
182
+ repoName: pathname[1]
183
+ };
184
+ }
193
185
  }
186
+ return null;
194
187
  }
195
- `;
196
- var GetAnalsyisDocument = `
197
- query getAnalsyis($analysisId: uuid!) {
198
- analysis: fixReport_by_pk(id: $analysisId) {
199
- id
200
- state
201
- repo {
202
- commitSha
203
- pullRequest
204
- }
205
- vulnerabilityReportId
206
- vulnerabilityReport {
207
- projectId
208
- project {
209
- organizationId
210
- }
211
- file {
212
- signedFile {
213
- url
214
- }
215
- }
188
+ var getRepoUrlFunctionMap = {
189
+ ["GitLab" /* GitLab */]: detectGitlabUrl,
190
+ ["GitHub" /* GitHub */]: detectGithubUrl,
191
+ ["Ado" /* Ado */]: detectAdoUrl,
192
+ ["Bitbucket" /* Bitbucket */]: detectBitbucketUrl
193
+ };
194
+ function getRepoInfo(args) {
195
+ for (const detectUrl of Object.values(getRepoUrlFunctionMap)) {
196
+ const detectUrlRes = detectUrl(args);
197
+ if (detectUrlRes) {
198
+ return detectUrlRes;
216
199
  }
217
200
  }
201
+ return null;
218
202
  }
219
- `;
220
- var GetFixesDocument = `
221
- query getFixes($filters: fix_bool_exp!) {
222
- fixes: fix(where: $filters) {
223
- issueType
224
- id
225
- patchAndQuestions {
226
- __typename
227
- ... on FixData {
228
- patch
229
- }
230
- }
231
- }
232
- }
233
- `;
234
- var GetVulByNodesMetadataDocument = `
235
- query getVulByNodesMetadata($filters: [vulnerability_report_issue_code_node_bool_exp!], $vulnerabilityReportId: uuid!) {
236
- vulnerabilityReportIssueCodeNodes: vulnerability_report_issue_code_node(
237
- order_by: {index: desc}
238
- where: {_or: $filters, vulnerabilityReportIssue: {fixId: {_is_null: false}, vulnerabilityReportId: {_eq: $vulnerabilityReportId}}}
239
- ) {
240
- vulnerabilityReportIssueId
241
- path
242
- startLine
243
- vulnerabilityReportIssue {
244
- issueType
245
- fixId
246
- }
247
- }
248
- fixablePrVuls: vulnerability_report_issue_aggregate(
249
- where: {fixId: {_is_null: false}, vulnerabilityReportId: {_eq: $vulnerabilityReportId}, codeNodes: {_or: $filters}}
250
- ) {
251
- aggregate {
252
- count
253
- }
254
- }
255
- nonFixablePrVuls: vulnerability_report_issue_aggregate(
256
- where: {fixId: {_is_null: true}, vulnerabilityReportId: {_eq: $vulnerabilityReportId}, codeNodes: {_or: $filters}}
257
- ) {
258
- aggregate {
259
- count
260
- }
261
- }
262
- totalScanVulnerabilities: vulnerability_report_issue_aggregate(
263
- where: {vulnerabilityReportId: {_eq: $vulnerabilityReportId}}
264
- ) {
265
- aggregate {
266
- count
267
- }
268
- }
269
- }
270
- `;
271
- var UpdateScmTokenDocument = `
272
- mutation updateScmToken($scmType: String!, $url: String!, $token: String!, $org: String, $refreshToken: String) {
273
- updateScmToken(
274
- scmType: $scmType
275
- url: $url
276
- token: $token
277
- org: $org
278
- refreshToken: $refreshToken
279
- ) {
280
- __typename
281
- ... on ScmAccessTokenUpdateSuccess {
282
- token
283
- }
284
- ... on InvalidScmTypeError {
285
- status
286
- error
287
- }
288
- ... on BadScmCredentials {
289
- status
290
- error
291
- }
292
- }
293
- }
294
- `;
295
- var UploadS3BucketInfoDocument = `
296
- mutation uploadS3BucketInfo($fileName: String!) {
297
- uploadS3BucketInfo(fileName: $fileName) {
298
- status
299
- error
300
- reportUploadInfo: uploadInfo {
301
- url
302
- fixReportId
303
- uploadFieldsJSON
304
- uploadKey
305
- }
306
- repoUploadInfo {
307
- url
308
- fixReportId
309
- uploadFieldsJSON
310
- uploadKey
311
- }
312
- }
313
- }
314
- `;
315
- var DigestVulnerabilityReportDocument = `
316
- mutation DigestVulnerabilityReport($vulnerabilityReportFileName: String!, $fixReportId: String!, $projectId: String!, $scanSource: String!) {
317
- digestVulnerabilityReport(
318
- fixReportId: $fixReportId
319
- vulnerabilityReportFileName: $vulnerabilityReportFileName
320
- projectId: $projectId
321
- scanSource: $scanSource
322
- ) {
323
- __typename
324
- ... on VulnerabilityReport {
325
- vulnerabilityReportId
326
- fixReportId
327
- }
328
- ... on RabbitSendError {
329
- status
330
- error
331
- }
332
- ... on ReportValidationError {
333
- status
334
- error
335
- }
336
- ... on ReferenceNotFoundError {
337
- status
338
- error
339
- }
340
- }
341
- }
342
- `;
343
- var SubmitVulnerabilityReportDocument = `
344
- mutation SubmitVulnerabilityReport($fixReportId: String!, $repoUrl: String!, $reference: String!, $projectId: String!, $scanSource: String!, $sha: String, $experimentalEnabled: Boolean, $vulnerabilityReportFileName: String, $pullRequest: Int) {
345
- submitVulnerabilityReport(
346
- fixReportId: $fixReportId
347
- repoUrl: $repoUrl
348
- reference: $reference
349
- sha: $sha
350
- experimentalEnabled: $experimentalEnabled
351
- pullRequest: $pullRequest
352
- projectId: $projectId
353
- vulnerabilityReportFileName: $vulnerabilityReportFileName
354
- scanSource: $scanSource
355
- ) {
356
- __typename
357
- ... on VulnerabilityReport {
358
- vulnerabilityReportId
359
- fixReportId
360
- }
361
- }
362
- }
363
- `;
364
- var CreateCommunityUserDocument = `
365
- mutation CreateCommunityUser {
366
- initOrganizationAndProject {
367
- __typename
368
- ... on InitOrganizationAndProjectGoodResponse {
369
- projectId
370
- userId
371
- organizationId
372
- }
373
- ... on UserAlreadyInProjectError {
374
- error
375
- status
376
- }
377
- }
378
- }
379
- `;
380
- var CreateCliLoginDocument = `
381
- mutation CreateCliLogin($publicKey: String!) {
382
- insert_cli_login_one(object: {publicKey: $publicKey}) {
383
- id
384
- }
385
- }
386
- `;
387
- var PerformCliLoginDocument = `
388
- mutation performCliLogin($loginId: String!) {
389
- performCliLogin(loginId: $loginId) {
390
- status
391
- }
392
- }
393
- `;
394
- var CreateProjectDocument = `
395
- mutation CreateProject($organizationId: String!, $projectName: String!) {
396
- createProject(organizationId: $organizationId, projectName: $projectName) {
397
- projectId
398
- }
399
- }
400
- `;
401
- var defaultWrapper = (action, _operationName, _operationType, _variables) => action();
402
- function getSdk(client, withWrapper = defaultWrapper) {
403
- return {
404
- Me(variables, requestHeaders) {
405
- return withWrapper((wrappedRequestHeaders) => client.request(MeDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "Me", "query", variables);
406
- },
407
- getOrgAndProjectId(variables, requestHeaders) {
408
- return withWrapper((wrappedRequestHeaders) => client.request(GetOrgAndProjectIdDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "getOrgAndProjectId", "query", variables);
409
- },
410
- GetEncryptedApiToken(variables, requestHeaders) {
411
- return withWrapper((wrappedRequestHeaders) => client.request(GetEncryptedApiTokenDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "GetEncryptedApiToken", "query", variables);
412
- },
413
- FixReportState(variables, requestHeaders) {
414
- return withWrapper((wrappedRequestHeaders) => client.request(FixReportStateDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "FixReportState", "query", variables);
415
- },
416
- GetVulnerabilityReportPaths(variables, requestHeaders) {
417
- return withWrapper((wrappedRequestHeaders) => client.request(GetVulnerabilityReportPathsDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "GetVulnerabilityReportPaths", "query", variables);
418
- },
419
- getAnalysis(variables, requestHeaders) {
420
- return withWrapper((wrappedRequestHeaders) => client.request(GetAnalysisDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "getAnalysis", "subscription", variables);
421
- },
422
- getAnalsyis(variables, requestHeaders) {
423
- return withWrapper((wrappedRequestHeaders) => client.request(GetAnalsyisDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "getAnalsyis", "query", variables);
424
- },
425
- getFixes(variables, requestHeaders) {
426
- return withWrapper((wrappedRequestHeaders) => client.request(GetFixesDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "getFixes", "query", variables);
427
- },
428
- getVulByNodesMetadata(variables, requestHeaders) {
429
- return withWrapper((wrappedRequestHeaders) => client.request(GetVulByNodesMetadataDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "getVulByNodesMetadata", "query", variables);
430
- },
431
- updateScmToken(variables, requestHeaders) {
432
- return withWrapper((wrappedRequestHeaders) => client.request(UpdateScmTokenDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "updateScmToken", "mutation", variables);
433
- },
434
- uploadS3BucketInfo(variables, requestHeaders) {
435
- return withWrapper((wrappedRequestHeaders) => client.request(UploadS3BucketInfoDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "uploadS3BucketInfo", "mutation", variables);
436
- },
437
- DigestVulnerabilityReport(variables, requestHeaders) {
438
- return withWrapper((wrappedRequestHeaders) => client.request(DigestVulnerabilityReportDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "DigestVulnerabilityReport", "mutation", variables);
439
- },
440
- SubmitVulnerabilityReport(variables, requestHeaders) {
441
- return withWrapper((wrappedRequestHeaders) => client.request(SubmitVulnerabilityReportDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "SubmitVulnerabilityReport", "mutation", variables);
442
- },
443
- CreateCommunityUser(variables, requestHeaders) {
444
- return withWrapper((wrappedRequestHeaders) => client.request(CreateCommunityUserDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "CreateCommunityUser", "mutation", variables);
445
- },
446
- CreateCliLogin(variables, requestHeaders) {
447
- return withWrapper((wrappedRequestHeaders) => client.request(CreateCliLoginDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "CreateCliLogin", "mutation", variables);
448
- },
449
- performCliLogin(variables, requestHeaders) {
450
- return withWrapper((wrappedRequestHeaders) => client.request(PerformCliLoginDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "performCliLogin", "mutation", variables);
451
- },
452
- CreateProject(variables, requestHeaders) {
453
- return withWrapper((wrappedRequestHeaders) => client.request(CreateProjectDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "CreateProject", "mutation", variables);
454
- }
455
- };
456
- }
457
-
458
- // src/utils/index.ts
459
- var utils_exports = {};
460
- __export(utils_exports, {
461
- CliError: () => CliError,
462
- Spinner: () => Spinner,
463
- getDirName: () => getDirName,
464
- getTopLevelDirName: () => getTopLevelDirName,
465
- keypress: () => keypress,
466
- sleep: () => sleep
467
- });
468
-
469
- // src/utils/dirname.ts
470
- import path2 from "node:path";
471
- import { fileURLToPath as fileURLToPath2 } from "node:url";
472
- function getDirName() {
473
- return path2.dirname(fileURLToPath2(import.meta.url));
474
- }
475
- function getTopLevelDirName(fullPath) {
476
- return path2.parse(fullPath).name;
477
- }
478
-
479
- // src/utils/keypress.ts
480
- import readline from "node:readline";
481
- async function keypress() {
482
- const rl = readline.createInterface({
483
- input: process.stdin,
484
- output: process.stdout
485
- });
486
- return new Promise((resolve) => {
487
- rl.question("", (answer) => {
488
- rl.close();
489
- process.stderr.moveCursor(0, -1);
490
- process.stderr.clearLine(1);
491
- resolve(answer);
492
- });
493
- });
494
- }
495
-
496
- // src/utils/spinner.ts
497
- import {
498
- createSpinner as _createSpinner
499
- } from "nanospinner";
500
- var mockSpinner = {
501
- success: () => mockSpinner,
502
- error: () => mockSpinner,
503
- warn: () => mockSpinner,
504
- stop: () => mockSpinner,
505
- start: () => mockSpinner,
506
- update: () => mockSpinner,
507
- reset: () => mockSpinner,
508
- clear: () => mockSpinner,
509
- spin: () => mockSpinner
510
- };
511
- function Spinner({ ci = false } = {}) {
512
- return {
513
- createSpinner: (text, options) => ci ? mockSpinner : _createSpinner(text, options)
514
- };
515
- }
516
-
517
- // src/utils/index.ts
518
- var sleep = (ms = 2e3) => new Promise((r) => setTimeout(r, ms));
519
- var CliError = class extends Error {
520
- };
521
-
522
- // src/features/analysis/index.ts
523
- import chalk4 from "chalk";
524
- import Configstore from "configstore";
525
- import Debug12 from "debug";
526
- import extract from "extract-zip";
527
- import fetch4 from "node-fetch";
528
- import open2 from "open";
529
- import semver from "semver";
530
- import tmp2 from "tmp";
531
- import { z as z12 } from "zod";
532
-
533
- // src/features/analysis/add_fix_comments_for_pr/add_fix_comments_for_pr.ts
534
- import Debug4 from "debug";
535
-
536
- // src/features/analysis/scm/types.ts
537
- var ReferenceType = /* @__PURE__ */ ((ReferenceType2) => {
538
- ReferenceType2["BRANCH"] = "BRANCH";
539
- ReferenceType2["COMMIT"] = "COMMIT";
540
- ReferenceType2["TAG"] = "TAG";
541
- return ReferenceType2;
542
- })(ReferenceType || {});
543
- var ScmLibScmType = /* @__PURE__ */ ((ScmLibScmType2) => {
544
- ScmLibScmType2["GITHUB"] = "GITHUB";
545
- ScmLibScmType2["GITLAB"] = "GITLAB";
546
- ScmLibScmType2["ADO"] = "ADO";
547
- ScmLibScmType2["BITBUCKET"] = "BITBUCKET";
548
- return ScmLibScmType2;
549
- })(ScmLibScmType || {});
550
- var scmCloudUrl = {
551
- GitLab: "https://gitlab.com",
552
- GitHub: "https://github.com",
553
- Ado: "https://dev.azure.com",
554
- Bitbucket: "https://bitbucket.org"
555
- };
556
- var ScmType = /* @__PURE__ */ ((ScmType2) => {
557
- ScmType2["GitHub"] = "GitHub";
558
- ScmType2["GitLab"] = "GitLab";
559
- ScmType2["Ado"] = "Ado";
560
- ScmType2["Bitbucket"] = "Bitbucket";
561
- return ScmType2;
562
- })(ScmType || {});
563
-
564
- // src/features/analysis/scm/ado/constants.ts
565
- var DEFUALT_ADO_ORIGIN = scmCloudUrl.Ado;
566
-
567
- // src/features/analysis/scm/ado/utils.ts
568
- import querystring3 from "node:querystring";
569
- import * as api from "azure-devops-node-api";
570
- import { z as z9 } from "zod";
571
-
572
- // src/features/analysis/scm/env.ts
573
- import { z as z2 } from "zod";
574
- var EnvVariablesZod = z2.object({
575
- GITLAB_API_TOKEN: z2.string().optional(),
576
- BROKERED_HOSTS: z2.string().toLowerCase().transform(
577
- (x) => x.split(",").map((url) => url.trim(), []).filter(Boolean)
578
- ).default(""),
579
- GITHUB_API_TOKEN: z2.string().optional(),
580
- GIT_PROXY_HOST: z2.string().default("http://tinyproxy:8888")
581
- });
582
- var { GITLAB_API_TOKEN, BROKERED_HOSTS, GITHUB_API_TOKEN, GIT_PROXY_HOST } = EnvVariablesZod.parse(process.env);
583
-
584
- // src/features/analysis/scm/scm.ts
585
- import { z as z7 } from "zod";
586
-
587
- // src/features/analysis/scm/bitbucket/bitbucket.ts
588
- import querystring from "node:querystring";
589
- import bitbucketPkg from "bitbucket";
590
- import * as bitbucketPkgNode from "bitbucket";
591
- import { z as z3 } from "zod";
592
-
593
- // src/features/analysis/scm/urlParser.ts
594
- function detectAdoUrl(args) {
595
- const { pathname, hostname, scmType } = args;
596
- const hostnameParts = hostname.split(".");
597
- const adoHostname = new URL(scmCloudUrl.Ado).hostname;
598
- if (hostnameParts.length === 3 && hostnameParts[1] === "visualstudio" && hostnameParts[2] === "com") {
599
- if (pathname.length === 2 && pathname[0] === "_git") {
600
- return {
601
- organization: hostnameParts[0],
602
- projectName: pathname[1],
603
- repoName: pathname[1]
604
- };
605
- }
606
- if (pathname.length === 3 && pathname[1] === "_git") {
607
- return {
608
- organization: hostnameParts[0],
609
- projectName: pathname[0],
610
- repoName: pathname[2]
611
- };
612
- }
613
- }
614
- if (hostname === adoHostname || scmType === "Ado" /* Ado */) {
615
- if (pathname[pathname.length - 2] === "_git") {
616
- if (pathname.length === 3) {
617
- return {
618
- organization: pathname[0],
619
- projectName: pathname[2],
620
- repoName: pathname[2]
621
- };
622
- }
623
- if (pathname.length > 3) {
624
- return {
625
- organization: pathname[pathname.length - 4],
626
- projectName: pathname[pathname.length - 3],
627
- repoName: pathname[pathname.length - 1]
628
- };
629
- }
630
- }
631
- }
632
- return null;
633
- }
634
- function detectGithubUrl(args) {
635
- const { pathname, hostname, scmType } = args;
636
- const githubHostname = new URL(scmCloudUrl.GitHub).hostname;
637
- if (hostname === githubHostname || scmType === "GitHub" /* GitHub */) {
638
- if (pathname.length === 2) {
639
- return {
640
- organization: pathname[0],
641
- projectName: void 0,
642
- repoName: pathname[1]
643
- };
644
- }
645
- }
646
- return null;
647
- }
648
- function detectGitlabUrl(args) {
649
- const { pathname, hostname, scmType } = args;
650
- const gitlabHostname = new URL(scmCloudUrl.GitLab).hostname;
651
- if (hostname === gitlabHostname || scmType === "GitLab" /* GitLab */) {
652
- if (pathname.length >= 2) {
653
- return {
654
- organization: pathname[0],
655
- projectName: void 0,
656
- repoName: pathname[pathname.length - 1]
657
- };
658
- }
659
- }
660
- return null;
661
- }
662
- function detectBitbucketUrl(args) {
663
- const { pathname, hostname, scmType } = args;
664
- const bitbucketHostname = new URL(scmCloudUrl.Bitbucket).hostname;
665
- if (hostname === bitbucketHostname || scmType === "Bitbucket" /* Bitbucket */) {
666
- if (pathname.length === 2) {
667
- return {
668
- organization: pathname[0],
669
- projectName: void 0,
670
- repoName: pathname[1]
671
- };
672
- }
673
- }
674
- return null;
675
- }
676
- var getRepoUrlFunctionMap = {
677
- ["GitLab" /* GitLab */]: detectGitlabUrl,
678
- ["GitHub" /* GitHub */]: detectGithubUrl,
679
- ["Ado" /* Ado */]: detectAdoUrl,
680
- ["Bitbucket" /* Bitbucket */]: detectBitbucketUrl
681
- };
682
- function getRepoInfo(args) {
683
- for (const detectUrl of Object.values(getRepoUrlFunctionMap)) {
684
- const detectUrlRes = detectUrl(args);
685
- if (detectUrlRes) {
686
- return detectUrlRes;
687
- }
688
- }
689
- return null;
690
- }
691
- var NAME_REGEX = /[a-z0-9\-_.+]+/i;
692
203
  var parseScmURL = (scmURL, scmType) => {
693
204
  try {
694
205
  const url = new URL(scmURL);
@@ -701,41 +212,55 @@ var parseScmURL = (scmURL, scmType) => {
701
212
  });
702
213
  if (!repo)
703
214
  return null;
704
- const { organization, repoName, projectName } = repo;
215
+ const { organization, repoName } = repo;
705
216
  if (!organization || !repoName)
706
217
  return null;
707
218
  if (!organization.match(NAME_REGEX) || !repoName.match(NAME_REGEX))
708
- return null;
709
- return {
710
- hostname,
711
- organization,
712
- projectPath,
713
- repoName,
714
- projectName,
715
- protocol: url.protocol,
716
- pathElements: projectPath.split("/")
717
- };
718
- } catch (e) {
719
- return null;
720
- }
721
- };
722
- var sanityRepoURL = (scmURL) => {
723
- try {
724
- const url = new URL(scmURL);
725
- const projectPath = url.pathname.substring(1).replace(/.git$/i, "");
726
- const pathParts = projectPath.split("/");
727
- if (pathParts.length < 2)
728
- return false;
729
- if (pathParts.length > 4)
730
- return false;
731
- if (pathParts.some((part) => !part.match(NAME_REGEX)))
732
- return false;
733
- return true;
219
+ return null;
220
+ const res = {
221
+ hostname,
222
+ organization,
223
+ projectPath,
224
+ repoName,
225
+ protocol: url.protocol,
226
+ pathElements: projectPath.split("/")
227
+ };
228
+ if (repo.scmType === "Ado" /* Ado */) {
229
+ return {
230
+ projectName: repo.projectName,
231
+ prefixPath: repo.prefixPath,
232
+ scmType: repo.scmType,
233
+ ...res
234
+ };
235
+ }
236
+ return {
237
+ scmType: repo.scmType,
238
+ ...res
239
+ };
734
240
  } catch (e) {
735
241
  return null;
736
242
  }
737
243
  };
738
244
 
245
+ // src/features/analysis/scm/shared/src/index.ts
246
+ var NAME_REGEX = /[a-z0-9\-_.+]+/i;
247
+ var ADO_PREFIX_PATH = "tfs";
248
+
249
+ // src/features/analysis/scm/types.ts
250
+ var ReferenceType = /* @__PURE__ */ ((ReferenceType2) => {
251
+ ReferenceType2["BRANCH"] = "BRANCH";
252
+ ReferenceType2["COMMIT"] = "COMMIT";
253
+ ReferenceType2["TAG"] = "TAG";
254
+ return ReferenceType2;
255
+ })(ReferenceType || {});
256
+ var ScmLibScmType = /* @__PURE__ */ ((ScmLibScmType2) => {
257
+ ScmLibScmType2["GITHUB"] = "GITHUB";
258
+ ScmLibScmType2["GITLAB"] = "GITLAB";
259
+ ScmLibScmType2["ADO"] = "ADO";
260
+ ScmLibScmType2["BITBUCKET"] = "BITBUCKET";
261
+ return ScmLibScmType2;
262
+ })(ScmLibScmType || {});
263
+
739
264
  // src/features/analysis/scm/utils/get_issue_type.ts
740
265
  var getIssueType = (issueType) => {
741
266
  switch (issueType) {
@@ -944,6 +469,22 @@ var isUrlHasPath = (url) => {
944
469
  function shouldValidateUrl(repoUrl) {
945
470
  return repoUrl && isUrlHasPath(repoUrl);
946
471
  }
472
+ var sanityRepoURL = (scmURL) => {
473
+ try {
474
+ const url = new URL(scmURL);
475
+ const projectPath = url.pathname.substring(1).replace(/.git$/i, "");
476
+ const pathParts = projectPath.split("/");
477
+ if (pathParts.length < 2)
478
+ return false;
479
+ if (pathParts.length > 4 && pathParts.at(0) !== ADO_PREFIX_PATH)
480
+ return false;
481
+ if (pathParts.some((part) => !part.match(NAME_REGEX)))
482
+ return false;
483
+ return true;
484
+ } catch (e) {
485
+ return null;
486
+ }
487
+ };
947
488
 
948
489
  // src/features/analysis/scm/bitbucket/bitbucket.ts
949
490
  var BITBUCKET_HOSTNAME = "bitbucket.org";
@@ -2063,7 +1604,7 @@ initGitlabFetchMock();
2063
1604
  // src/features/analysis/scm/scmSubmit/index.ts
2064
1605
  import fs from "node:fs/promises";
2065
1606
  import parseDiff from "parse-diff";
2066
- import path3 from "path";
1607
+ import path from "path";
2067
1608
  import { simpleGit } from "simple-git";
2068
1609
  import tmp from "tmp";
2069
1610
  import { z as z6 } from "zod";
@@ -2195,10 +1736,10 @@ function getCloudScmLibTypeFromUrl(url) {
2195
1736
  return void 0;
2196
1737
  }
2197
1738
  var scmCloudHostname = {
2198
- GitLab: new URL(scmCloudUrl.GitLab).hostname,
2199
- GitHub: new URL(scmCloudUrl.GitHub).hostname,
2200
- Ado: new URL(scmCloudUrl.Ado).hostname,
2201
- Bitbucket: new URL(scmCloudUrl.Bitbucket).hostname
1739
+ ["GitLab" /* GitLab */]: new URL(scmCloudUrl.GitLab).hostname,
1740
+ ["GitHub" /* GitHub */]: new URL(scmCloudUrl.GitHub).hostname,
1741
+ ["Ado" /* Ado */]: new URL(scmCloudUrl.Ado).hostname,
1742
+ ["Bitbucket" /* Bitbucket */]: new URL(scmCloudUrl.Bitbucket).hostname
2202
1743
  };
2203
1744
  var scmLibScmTypeToScmType = {
2204
1745
  ["GITLAB" /* GITLAB */]: "GitLab" /* GitLab */,
@@ -2212,10 +1753,6 @@ var scmTypeToScmLibScmType = {
2212
1753
  ["Ado" /* Ado */]: "ADO" /* ADO */,
2213
1754
  ["Bitbucket" /* Bitbucket */]: "BITBUCKET" /* BITBUCKET */
2214
1755
  };
2215
- function getScmTypeFromScmLibType(scmLibType) {
2216
- const parsedScmLibType = z7.nativeEnum(ScmLibScmType).parse(scmLibType);
2217
- return scmLibScmTypeToScmType[parsedScmLibType];
2218
- }
2219
1756
  function getScmLibTypeFromScmType(scmType) {
2220
1757
  const parsedScmType = z7.nativeEnum(ScmType).parse(scmType);
2221
1758
  return scmTypeToScmLibScmType[parsedScmType];
@@ -2271,24 +1808,6 @@ function getScmConfig({
2271
1808
  scmOrg: void 0
2272
1809
  };
2273
1810
  }
2274
- async function scmCanReachRepo({
2275
- repoUrl,
2276
- scmType,
2277
- accessToken,
2278
- scmOrg
2279
- }) {
2280
- try {
2281
- await SCMLib.init({
2282
- url: repoUrl,
2283
- accessToken,
2284
- scmType: getScmLibTypeFromScmType(scmType),
2285
- scmOrg
2286
- });
2287
- return true;
2288
- } catch (e) {
2289
- return false;
2290
- }
2291
- }
2292
1811
  var InvalidRepoUrlError = class extends Error {
2293
1812
  constructor(m) {
2294
1813
  super(m);
@@ -2407,12 +1926,7 @@ var SCMLib = class {
2407
1926
  static async getIsValidBranchName(branchName) {
2408
1927
  return isValidBranchName(branchName);
2409
1928
  }
2410
- static async init({
2411
- url,
2412
- accessToken,
2413
- scmType,
2414
- scmOrg
2415
- }) {
1929
+ static async init({ url, accessToken, scmType, scmOrg }, { propagateExceptions = false } = {}) {
2416
1930
  const trimmedUrl = url ? url.trim().replace(/\/$/, "").replace(/.git$/i, "") : void 0;
2417
1931
  try {
2418
1932
  switch (scmType) {
@@ -2445,6 +1959,9 @@ var SCMLib = class {
2445
1959
  );
2446
1960
  }
2447
1961
  console.error(`error validating scm: ${scmType} `, e);
1962
+ if (propagateExceptions) {
1963
+ throw e;
1964
+ }
2448
1965
  }
2449
1966
  return new StubSCMLib(trimmedUrl, void 0, void 0);
2450
1967
  }
@@ -2943,792 +2460,1360 @@ var GithubSCMLib = class extends SCMLib {
2943
2460
  async postGeneralPrComment(params) {
2944
2461
  const { prNumber, body } = params;
2945
2462
  this._validateAccessTokenAndUrl();
2946
- const { owner, repo } = parseGithubOwnerAndRepo(this.url);
2947
- return await this.githubSdk.postGeneralPrComment({
2948
- issue_number: prNumber,
2949
- owner,
2950
- repo,
2951
- body
2952
- });
2463
+ const { owner, repo } = parseGithubOwnerAndRepo(this.url);
2464
+ return await this.githubSdk.postGeneralPrComment({
2465
+ issue_number: prNumber,
2466
+ owner,
2467
+ repo,
2468
+ body
2469
+ });
2470
+ }
2471
+ async getGeneralPrComments(params) {
2472
+ const { prNumber } = params;
2473
+ this._validateAccessTokenAndUrl();
2474
+ const { owner, repo } = parseGithubOwnerAndRepo(this.url);
2475
+ return await this.githubSdk.getGeneralPrComments({
2476
+ issue_number: prNumber,
2477
+ owner,
2478
+ repo
2479
+ });
2480
+ }
2481
+ async deleteGeneralPrComment({
2482
+ commentId
2483
+ }) {
2484
+ this._validateAccessTokenAndUrl();
2485
+ const { owner, repo } = parseGithubOwnerAndRepo(this.url);
2486
+ return this.githubSdk.deleteGeneralPrComment({
2487
+ owner,
2488
+ repo,
2489
+ comment_id: commentId
2490
+ });
2491
+ }
2492
+ };
2493
+ var StubSCMLib = class extends SCMLib {
2494
+ async createSubmitRequest(_params) {
2495
+ console.error("createSubmitRequest() not implemented");
2496
+ throw new Error("createSubmitRequest() not implemented");
2497
+ }
2498
+ getScmLibType() {
2499
+ console.error("getScmLibType() not implemented");
2500
+ throw new Error("getScmLibType() not implemented");
2501
+ }
2502
+ getAuthHeaders() {
2503
+ console.error("getAuthHeaders() not implemented");
2504
+ throw new Error("getAuthHeaders() not implemented");
2505
+ }
2506
+ getDownloadUrl(_sha) {
2507
+ console.error("getDownloadUrl() not implemented");
2508
+ throw new Error("getDownloadUrl() not implemented");
2509
+ }
2510
+ async getIsRemoteBranch(_branch) {
2511
+ console.error("getIsRemoteBranch() not implemented");
2512
+ throw new Error("getIsRemoteBranch() not implemented");
2513
+ }
2514
+ async validateParams() {
2515
+ console.error("validateParams() not implemented");
2516
+ throw new Error("validateParams() not implemented");
2517
+ }
2518
+ async getRepoList(_scmOrg) {
2519
+ console.error("getRepoList() not implemented");
2520
+ throw new Error("getRepoList() not implemented");
2521
+ }
2522
+ async getBranchList() {
2523
+ console.error("getBranchList() not implemented");
2524
+ throw new Error("getBranchList() not implemented");
2525
+ }
2526
+ async getUsername() {
2527
+ console.error("getUsername() not implemented");
2528
+ throw new Error("getUsername() not implemented");
2529
+ }
2530
+ async getSubmitRequestStatus(_scmSubmitRequestId) {
2531
+ console.error("getSubmitRequestStatus() not implemented");
2532
+ throw new Error("getSubmitRequestStatus() not implemented");
2533
+ }
2534
+ async getUserHasAccessToRepo() {
2535
+ console.error("getUserHasAccessToRepo() not implemented");
2536
+ throw new Error("getUserHasAccessToRepo() not implemented");
2537
+ }
2538
+ async getRepoBlameRanges(_ref, _path) {
2539
+ console.error("getRepoBlameRanges() not implemented");
2540
+ throw new Error("getRepoBlameRanges() not implemented");
2541
+ }
2542
+ async getReferenceData(_ref) {
2543
+ console.error("getReferenceData() not implemented");
2544
+ throw new Error("getReferenceData() not implemented");
2545
+ }
2546
+ async getRepoDefaultBranch() {
2547
+ console.error("getRepoDefaultBranch() not implemented");
2548
+ throw new Error("getRepoDefaultBranch() not implemented");
2549
+ }
2550
+ async getPrUrl(_prNumber) {
2551
+ console.error("getPr() not implemented");
2552
+ throw new Error("getPr() not implemented");
2553
+ }
2554
+ _getUsernameForAuthUrl() {
2555
+ throw new Error("Method not implemented.");
2556
+ }
2557
+ };
2558
+ function getUserAndPassword(token) {
2559
+ const [username, password] = token.split(":");
2560
+ const safePasswordAndUsername = z7.object({ username: z7.string(), password: z7.string() }).parse({ username, password });
2561
+ return {
2562
+ username: safePasswordAndUsername.username,
2563
+ password: safePasswordAndUsername.password
2564
+ };
2565
+ }
2566
+ function createBitbucketSdk(token) {
2567
+ if (!token) {
2568
+ return getBitbucketSdk({ authType: "public" });
2569
+ }
2570
+ if (token.includes(":")) {
2571
+ const { password, username } = getUserAndPassword(token);
2572
+ return getBitbucketSdk({
2573
+ authType: "basic",
2574
+ username,
2575
+ password
2576
+ });
2577
+ }
2578
+ return getBitbucketSdk({ authType: "token", token });
2579
+ }
2580
+ var BitbucketSCMLib = class extends SCMLib {
2581
+ constructor(url, accessToken, scmOrg) {
2582
+ super(url, accessToken, scmOrg);
2583
+ __publicField(this, "bitbucketSdk");
2584
+ const bitbucketSdk = createBitbucketSdk(accessToken);
2585
+ this.bitbucketSdk = bitbucketSdk;
2586
+ }
2587
+ getAuthData() {
2588
+ const authType = this.bitbucketSdk.getAuthType();
2589
+ switch (authType) {
2590
+ case "basic": {
2591
+ this._validateAccessToken();
2592
+ const { username, password } = getUserAndPassword(this.accessToken);
2593
+ return { username, password, authType };
2594
+ }
2595
+ case "token": {
2596
+ return { authType, token: z7.string().parse(this.accessToken) };
2597
+ }
2598
+ case "public":
2599
+ return { authType };
2600
+ }
2601
+ }
2602
+ async createSubmitRequest(params) {
2603
+ this._validateAccessTokenAndUrl();
2604
+ const pullRequestRes = await this.bitbucketSdk.createPullRequest({
2605
+ ...params,
2606
+ repoUrl: this.url
2607
+ });
2608
+ return String(z7.number().parse(pullRequestRes.id));
2609
+ }
2610
+ async validateParams() {
2611
+ return validateBitbucketParams({
2612
+ bitbucketClient: this.bitbucketSdk,
2613
+ url: this.url
2614
+ });
2615
+ }
2616
+ async getRepoList(scmOrg) {
2617
+ this._validateAccessToken();
2618
+ return this.bitbucketSdk.getRepos({
2619
+ workspaceSlug: scmOrg
2620
+ });
2621
+ }
2622
+ async getBranchList() {
2623
+ this._validateAccessTokenAndUrl();
2624
+ return this.bitbucketSdk.getBranchList({
2625
+ repoUrl: this.url
2626
+ });
2627
+ }
2628
+ getScmLibType() {
2629
+ return "BITBUCKET" /* BITBUCKET */;
2630
+ }
2631
+ getAuthHeaders() {
2632
+ const authType = this.bitbucketSdk.getAuthType();
2633
+ switch (authType) {
2634
+ case "public":
2635
+ return {};
2636
+ case "token":
2637
+ return { authorization: `Bearer ${this.accessToken}` };
2638
+ case "basic": {
2639
+ this._validateAccessToken();
2640
+ const { username, password } = getUserAndPassword(this.accessToken);
2641
+ return {
2642
+ authorization: `Basic ${Buffer.from(
2643
+ username + ":" + password
2644
+ ).toString("base64")}`
2645
+ };
2646
+ }
2647
+ }
2648
+ }
2649
+ async getDownloadUrl(sha) {
2650
+ this._validateUrl();
2651
+ return this.bitbucketSdk.getDownloadUrl({ url: this.url, sha });
2652
+ }
2653
+ async _getUsernameForAuthUrl() {
2654
+ this._validateAccessTokenAndUrl();
2655
+ const user = await this.bitbucketSdk.getUser();
2656
+ if (!user.username) {
2657
+ throw new Error("no username found");
2658
+ }
2659
+ return user.username;
2953
2660
  }
2954
- async getGeneralPrComments(params) {
2955
- const { prNumber } = params;
2661
+ async getIsRemoteBranch(branch) {
2956
2662
  this._validateAccessTokenAndUrl();
2957
- const { owner, repo } = parseGithubOwnerAndRepo(this.url);
2958
- return await this.githubSdk.getGeneralPrComments({
2959
- issue_number: prNumber,
2960
- owner,
2961
- repo
2962
- });
2663
+ try {
2664
+ const res = await this.bitbucketSdk.getBranch({
2665
+ branchName: branch,
2666
+ repoUrl: this.url
2667
+ });
2668
+ return res.name === branch;
2669
+ } catch (e) {
2670
+ return false;
2671
+ }
2963
2672
  }
2964
- async deleteGeneralPrComment({
2965
- commentId
2966
- }) {
2673
+ async getUserHasAccessToRepo() {
2967
2674
  this._validateAccessTokenAndUrl();
2968
- const { owner, repo } = parseGithubOwnerAndRepo(this.url);
2969
- return this.githubSdk.deleteGeneralPrComment({
2970
- owner,
2971
- repo,
2972
- comment_id: commentId
2973
- });
2675
+ return this.bitbucketSdk.getIsUserCollaborator({ repoUrl: this.url });
2974
2676
  }
2975
- };
2976
- var StubSCMLib = class extends SCMLib {
2977
- async createSubmitRequest(_params) {
2978
- console.error("createSubmitRequest() not implemented");
2979
- throw new Error("createSubmitRequest() not implemented");
2677
+ async getUsername() {
2678
+ this._validateAccessToken();
2679
+ const res = await this.bitbucketSdk.getUser();
2680
+ return z7.string().parse(res.username);
2980
2681
  }
2981
- getScmLibType() {
2982
- console.error("getScmLibType() not implemented");
2983
- throw new Error("getScmLibType() not implemented");
2682
+ async getSubmitRequestStatus(_scmSubmitRequestId) {
2683
+ this._validateAccessTokenAndUrl();
2684
+ const pullRequestRes = await this.bitbucketSdk.getPullRequest({
2685
+ prNumber: Number(_scmSubmitRequestId),
2686
+ url: this.url
2687
+ });
2688
+ switch (pullRequestRes.state) {
2689
+ case "OPEN":
2690
+ return "open";
2691
+ case "MERGED":
2692
+ return "merged";
2693
+ case "DECLINED":
2694
+ return "closed";
2695
+ default:
2696
+ throw new Error(`unknown state ${pullRequestRes.state} `);
2697
+ }
2984
2698
  }
2985
- getAuthHeaders() {
2986
- console.error("getAuthHeaders() not implemented");
2987
- throw new Error("getAuthHeaders() not implemented");
2699
+ async getRepoBlameRanges(_ref, _path) {
2700
+ return [];
2988
2701
  }
2989
- getDownloadUrl(_sha) {
2990
- console.error("getDownloadUrl() not implemented");
2991
- throw new Error("getDownloadUrl() not implemented");
2702
+ async getReferenceData(ref) {
2703
+ this._validateUrl();
2704
+ return this.bitbucketSdk.getReferenceData({ url: this.url, ref });
2992
2705
  }
2993
- async getIsRemoteBranch(_branch) {
2994
- console.error("getIsRemoteBranch() not implemented");
2995
- throw new Error("getIsRemoteBranch() not implemented");
2706
+ async getRepoDefaultBranch() {
2707
+ this._validateUrl();
2708
+ const repoRes = await this.bitbucketSdk.getRepo({ repoUrl: this.url });
2709
+ return z7.string().parse(repoRes.mainbranch?.name);
2996
2710
  }
2997
- async validateParams() {
2998
- console.error("validateParams() not implemented");
2999
- throw new Error("validateParams() not implemented");
2711
+ getPrUrl(prNumber) {
2712
+ this._validateUrl();
2713
+ const { repoSlug, workspace } = parseBitbucketOrganizationAndRepo(this.url);
2714
+ return Promise.resolve(
2715
+ `https://bitbucket.org/${workspace}/${repoSlug}/pull-requests/${prNumber}`
2716
+ );
3000
2717
  }
3001
- async getRepoList(_scmOrg) {
3002
- console.error("getRepoList() not implemented");
3003
- throw new Error("getRepoList() not implemented");
2718
+ async refreshToken(params) {
2719
+ const getBitbucketTokenResponse = await getBitbucketToken({
2720
+ authType: "refresh_token",
2721
+ ...params
2722
+ });
2723
+ return {
2724
+ accessToken: getBitbucketTokenResponse.access_token,
2725
+ refreshToken: getBitbucketTokenResponse.refresh_token
2726
+ };
3004
2727
  }
3005
- async getBranchList() {
3006
- console.error("getBranchList() not implemented");
3007
- throw new Error("getBranchList() not implemented");
2728
+ };
2729
+
2730
+ // src/features/analysis/scm/ado/validation.ts
2731
+ import { z as z8 } from "zod";
2732
+ var ValidPullRequestStatusZ = z8.union([
2733
+ z8.literal(1 /* Active */),
2734
+ z8.literal(2 /* Abandoned */),
2735
+ z8.literal(3 /* Completed */)
2736
+ ]);
2737
+ var AdoAuthResultZ = z8.object({
2738
+ access_token: z8.string().min(1),
2739
+ token_type: z8.string().min(1),
2740
+ refresh_token: z8.string().min(1)
2741
+ });
2742
+ var profileZ = z8.object({
2743
+ displayName: z8.string(),
2744
+ publicAlias: z8.string().min(1),
2745
+ emailAddress: z8.string(),
2746
+ coreRevision: z8.number(),
2747
+ timeStamp: z8.string(),
2748
+ id: z8.string(),
2749
+ revision: z8.number()
2750
+ });
2751
+ var accountsZ = z8.object({
2752
+ count: z8.number(),
2753
+ value: z8.array(
2754
+ z8.object({
2755
+ accountId: z8.string(),
2756
+ accountUri: z8.string(),
2757
+ accountName: z8.string()
2758
+ })
2759
+ )
2760
+ });
2761
+
2762
+ // src/features/analysis/scm/ado/utils.ts
2763
+ function _getPublicAdoClient({
2764
+ orgName,
2765
+ origin: origin2
2766
+ }) {
2767
+ const orgUrl = `${origin2}/${orgName}`;
2768
+ const authHandler = api.getPersonalAccessTokenHandler("");
2769
+ authHandler.canHandleAuthentication = () => false;
2770
+ authHandler.prepareRequest = (_options) => {
2771
+ return;
2772
+ };
2773
+ const connection = new api.WebApi(orgUrl, authHandler);
2774
+ return connection;
2775
+ }
2776
+ function removeTrailingSlash2(str) {
2777
+ return str.trim().replace(/\/+$/, "");
2778
+ }
2779
+ function parseAdoOwnerAndRepo(adoUrl) {
2780
+ adoUrl = removeTrailingSlash2(adoUrl);
2781
+ const parsingResult = parseScmURL(adoUrl, "Ado" /* Ado */);
2782
+ if (!parsingResult || parsingResult.scmType !== "Ado" /* Ado */) {
2783
+ throw new InvalidUrlPatternError(`
2784
+ : ${adoUrl}`);
3008
2785
  }
3009
- async getUsername() {
3010
- console.error("getUsername() not implemented");
3011
- throw new Error("getUsername() not implemented");
2786
+ const {
2787
+ organization,
2788
+ repoName,
2789
+ projectName,
2790
+ projectPath,
2791
+ pathElements,
2792
+ hostname,
2793
+ protocol
2794
+ } = parsingResult;
2795
+ return {
2796
+ owner: decodeURI(organization),
2797
+ repo: decodeURI(repoName),
2798
+ projectName: projectName ? decodeURI(projectName) : void 0,
2799
+ projectPath,
2800
+ pathElements,
2801
+ prefixPath: parsingResult.prefixPath,
2802
+ origin: `${protocol}//${hostname}`
2803
+ };
2804
+ }
2805
+ async function getAdoConnectData({
2806
+ url,
2807
+ tokenOrg,
2808
+ adoTokenInfo
2809
+ }) {
2810
+ if (url) {
2811
+ const urlObject = new URL(url);
2812
+ if (tokenOrg && (urlObject.origin === url || `${urlObject.origin}/tfs` === url)) {
2813
+ return {
2814
+ origin: url,
2815
+ org: tokenOrg
2816
+ };
2817
+ }
2818
+ const { owner, origin: origin2, prefixPath } = parseAdoOwnerAndRepo(url);
2819
+ return {
2820
+ org: owner,
2821
+ origin: prefixPath ? `${origin2}/${prefixPath}` : origin2
2822
+ };
3012
2823
  }
3013
- async getSubmitRequestStatus(_scmSubmitRequestId) {
3014
- console.error("getSubmitRequestStatus() not implemented");
3015
- throw new Error("getSubmitRequestStatus() not implemented");
2824
+ if (!tokenOrg) {
2825
+ if (adoTokenInfo.type === "OAUTH" /* OAUTH */) {
2826
+ const [org] = await _getOrgsForOauthToken({
2827
+ oauthToken: adoTokenInfo.accessToken
2828
+ });
2829
+ return {
2830
+ org: z9.string().parse(org),
2831
+ origin: DEFUALT_ADO_ORIGIN
2832
+ };
2833
+ }
2834
+ throw new InvalidRepoUrlError("ADO URL is null");
3016
2835
  }
3017
- async getUserHasAccessToRepo() {
3018
- console.error("getUserHasAccessToRepo() not implemented");
3019
- throw new Error("getUserHasAccessToRepo() not implemented");
2836
+ return {
2837
+ org: tokenOrg,
2838
+ origin: DEFUALT_ADO_ORIGIN
2839
+ };
2840
+ }
2841
+ function isAdoOnCloud(url) {
2842
+ const urlObj = new URL(url);
2843
+ return urlObj.origin.toLowerCase() === DEFUALT_ADO_ORIGIN || urlObj.hostname.toLowerCase().endsWith(".visualstudio.com");
2844
+ }
2845
+ async function getAdoApiClient(params) {
2846
+ const { origin: origin2 = DEFUALT_ADO_ORIGIN, orgName } = params;
2847
+ if (params.tokenType === "NONE" /* NONE */ || // note: move to public client if the token is not associated with the PAT org
2848
+ // we're only doing it the ado on the cloud
2849
+ params.tokenType === "PAT" /* PAT */ && params.patTokenOrg !== orgName && isAdoOnCloud(origin2)) {
2850
+ return _getPublicAdoClient({ orgName, origin: origin2 });
3020
2851
  }
3021
- async getRepoBlameRanges(_ref, _path) {
3022
- console.error("getRepoBlameRanges() not implemented");
3023
- throw new Error("getRepoBlameRanges() not implemented");
2852
+ const orgUrl = `${origin2}/${orgName}`;
2853
+ if (params.tokenType === "OAUTH" /* OAUTH */) {
2854
+ if (isAdoOnCloud(origin2)) {
2855
+ throw new Error(
2856
+ `Oauth token is not supported for ADO on prem - ${origin2} `
2857
+ );
2858
+ }
2859
+ const connection2 = new api.WebApi(
2860
+ orgUrl,
2861
+ api.getBearerHandler(params.accessToken),
2862
+ {}
2863
+ );
2864
+ return connection2;
3024
2865
  }
3025
- async getReferenceData(_ref) {
3026
- console.error("getReferenceData() not implemented");
3027
- throw new Error("getReferenceData() not implemented");
2866
+ const authHandler = api.getPersonalAccessTokenHandler(params.accessToken);
2867
+ const isBroker = BROKERED_HOSTS.includes(new URL(orgUrl).origin);
2868
+ const connection = new api.WebApi(
2869
+ orgUrl,
2870
+ authHandler,
2871
+ isBroker ? {
2872
+ proxy: {
2873
+ proxyUrl: GIT_PROXY_HOST
2874
+ },
2875
+ ignoreSslError: true
2876
+ } : void 0
2877
+ );
2878
+ return connection;
2879
+ }
2880
+ function getAdoTokenInfo(token) {
2881
+ if (!token) {
2882
+ return { type: "NONE" /* NONE */ };
3028
2883
  }
3029
- async getRepoDefaultBranch() {
3030
- console.error("getRepoDefaultBranch() not implemented");
3031
- throw new Error("getRepoDefaultBranch() not implemented");
2884
+ if (token.includes(".")) {
2885
+ return { type: "OAUTH" /* OAUTH */, accessToken: token };
3032
2886
  }
3033
- async getPrUrl(_prNumber) {
3034
- console.error("getPr() not implemented");
3035
- throw new Error("getPr() not implemented");
2887
+ return { type: "PAT" /* PAT */, accessToken: token };
2888
+ }
2889
+ async function getAdoClientParams(params) {
2890
+ const { url, accessToken, tokenOrg } = params;
2891
+ const adoTokenInfo = getAdoTokenInfo(accessToken);
2892
+ const { org, origin: origin2 } = await getAdoConnectData({
2893
+ url,
2894
+ tokenOrg,
2895
+ adoTokenInfo
2896
+ });
2897
+ switch (adoTokenInfo.type) {
2898
+ case "NONE" /* NONE */:
2899
+ return {
2900
+ tokenType: "NONE" /* NONE */,
2901
+ origin: origin2,
2902
+ orgName: org.toLowerCase()
2903
+ };
2904
+ case "OAUTH" /* OAUTH */: {
2905
+ return {
2906
+ tokenType: "OAUTH" /* OAUTH */,
2907
+ accessToken: adoTokenInfo.accessToken,
2908
+ origin: origin2,
2909
+ orgName: org.toLowerCase()
2910
+ };
2911
+ }
2912
+ case "PAT" /* PAT */: {
2913
+ return {
2914
+ tokenType: "PAT" /* PAT */,
2915
+ accessToken: adoTokenInfo.accessToken,
2916
+ patTokenOrg: z9.string().parse(tokenOrg).toLowerCase(),
2917
+ origin: origin2,
2918
+ orgName: org.toLowerCase()
2919
+ };
2920
+ }
3036
2921
  }
3037
- _getUsernameForAuthUrl() {
3038
- throw new Error("Method not implemented.");
2922
+ }
2923
+ async function adoValidateParams({
2924
+ url,
2925
+ accessToken,
2926
+ tokenOrg
2927
+ }) {
2928
+ try {
2929
+ const api2 = await getAdoApiClient(
2930
+ await getAdoClientParams({ url, accessToken, tokenOrg })
2931
+ );
2932
+ await api2.connect();
2933
+ } catch (e) {
2934
+ console.log("adoValidateParams error", e);
2935
+ const error = e;
2936
+ const code = error.code || error.status || error.statusCode || error.response?.status || error.response?.statusCode || error.response?.code;
2937
+ const description = error.description || `${e}`;
2938
+ if (code === 401 || code === 403 || description.includes("401") || description.includes("403")) {
2939
+ throw new InvalidAccessTokenError(`invalid ADO access token`);
2940
+ }
2941
+ if (code === 404 || description.includes("404") || description.includes("Not Found")) {
2942
+ throw new InvalidRepoUrlError(`invalid ADO repo URL ${url}`);
2943
+ }
2944
+ throw e;
3039
2945
  }
3040
- };
3041
- function getUserAndPassword(token) {
3042
- const [username, password] = token.split(":");
3043
- const safePasswordAndUsername = z7.object({ username: z7.string(), password: z7.string() }).parse({ username, password });
2946
+ }
2947
+ async function _getOrgsForOauthToken({
2948
+ oauthToken
2949
+ }) {
2950
+ const profileRes = await fetch(
2951
+ "https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=6.0",
2952
+ {
2953
+ method: "GET",
2954
+ headers: {
2955
+ Authorization: `Bearer ${oauthToken}`
2956
+ }
2957
+ }
2958
+ );
2959
+ const profileJson = await profileRes.json();
2960
+ const profile = profileZ.parse(profileJson);
2961
+ const accountsRes = await fetch(
2962
+ `https://app.vssps.visualstudio.com/_apis/accounts?memberId=${profile.publicAlias}&api-version=6.0`,
2963
+ {
2964
+ method: "GET",
2965
+ headers: {
2966
+ Authorization: `Bearer ${oauthToken}`
2967
+ }
2968
+ }
2969
+ );
2970
+ const accountsJson = await accountsRes.json();
2971
+ const accounts = accountsZ.parse(accountsJson);
2972
+ const orgs = accounts.value.map((account) => account.accountName).filter((value, index, array) => array.indexOf(value) === index);
2973
+ return orgs;
2974
+ }
2975
+
2976
+ // src/features/analysis/scm/ado/ado.ts
2977
+ async function getAdoSdk(params) {
2978
+ const api2 = await getAdoApiClient(params);
3044
2979
  return {
3045
- username: safePasswordAndUsername.username,
3046
- password: safePasswordAndUsername.password
2980
+ async getAdoIsUserCollaborator({ repoUrl }) {
2981
+ try {
2982
+ const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
2983
+ const git = await api2.getGitApi();
2984
+ const branches = await git.getBranches(repo, projectName);
2985
+ if (!branches || branches.length === 0) {
2986
+ throw new InvalidRepoUrlError("no branches");
2987
+ }
2988
+ return true;
2989
+ } catch (e) {
2990
+ return false;
2991
+ }
2992
+ },
2993
+ async getAdoPullRequestStatus({
2994
+ repoUrl,
2995
+ prNumber
2996
+ }) {
2997
+ const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
2998
+ const git = await api2.getGitApi();
2999
+ const res = await git.getPullRequest(repo, prNumber, projectName);
3000
+ const parsedPullRequestStatus = ValidPullRequestStatusZ.safeParse(
3001
+ res.status
3002
+ );
3003
+ if (!parsedPullRequestStatus.success) {
3004
+ throw new Error("bad pr status for ADO");
3005
+ }
3006
+ return parsedPullRequestStatus.data;
3007
+ },
3008
+ async getAdoIsRemoteBranch({
3009
+ repoUrl,
3010
+ branch
3011
+ }) {
3012
+ const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3013
+ const git = await api2.getGitApi();
3014
+ try {
3015
+ const branchStatus = await git.getBranch(repo, branch, projectName);
3016
+ if (!branchStatus || !branchStatus.commit) {
3017
+ throw new InvalidRepoUrlError("no branch status");
3018
+ }
3019
+ return branchStatus.name === branch;
3020
+ } catch (e) {
3021
+ return false;
3022
+ }
3023
+ },
3024
+ async getAdoPrUrl({ url, prNumber }) {
3025
+ const { repo, projectName } = parseAdoOwnerAndRepo(url);
3026
+ const git = await api2.getGitApi();
3027
+ const getRepositoryRes = await git.getRepository(
3028
+ decodeURI(repo),
3029
+ projectName ? decodeURI(projectName) : void 0
3030
+ );
3031
+ return `${getRepositoryRes.webUrl}/pullrequest/${prNumber}`;
3032
+ },
3033
+ getAdoDownloadUrl({
3034
+ repoUrl,
3035
+ branch
3036
+ }) {
3037
+ const { owner, repo, projectName, prefixPath } = parseAdoOwnerAndRepo(repoUrl);
3038
+ const url = new URL(repoUrl);
3039
+ const origin2 = url.origin.toLowerCase().endsWith(".visualstudio.com") ? DEFUALT_ADO_ORIGIN : url.origin.toLowerCase();
3040
+ const params2 = `path=/&versionDescriptor[versionOptions]=0&versionDescriptor[versionType]=commit&versionDescriptor[version]=${branch}&resolveLfs=true&$format=zip&api-version=5.0&download=true`;
3041
+ const path9 = [
3042
+ prefixPath,
3043
+ owner,
3044
+ projectName,
3045
+ "_apis",
3046
+ "git",
3047
+ "repositories",
3048
+ repo,
3049
+ "items",
3050
+ "items"
3051
+ ].filter(Boolean).join("/");
3052
+ return new URL(`${path9}?${params2}`, origin2).toString();
3053
+ },
3054
+ async getAdoBranchList({ repoUrl }) {
3055
+ const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3056
+ const git = await api2.getGitApi();
3057
+ try {
3058
+ const res = await git.getBranches(repo, projectName);
3059
+ res.sort((a, b) => {
3060
+ if (!a.commit?.committer?.date || !b.commit?.committer?.date) {
3061
+ return 0;
3062
+ }
3063
+ return b.commit?.committer?.date.getTime() - a.commit?.committer?.date.getTime();
3064
+ });
3065
+ return res.reduce((acc, branch) => {
3066
+ if (!branch.name) {
3067
+ return acc;
3068
+ }
3069
+ acc.push(branch.name);
3070
+ return acc;
3071
+ }, []);
3072
+ } catch (e) {
3073
+ return [];
3074
+ }
3075
+ },
3076
+ async createAdoPullRequest(options) {
3077
+ const { repoUrl, sourceBranchName, targetBranchName, title, body } = options;
3078
+ const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3079
+ const git = await api2.getGitApi();
3080
+ const res = await git.createPullRequest(
3081
+ {
3082
+ sourceRefName: `refs/heads/${sourceBranchName}`,
3083
+ targetRefName: `refs/heads/${targetBranchName}`,
3084
+ title,
3085
+ description: body
3086
+ },
3087
+ repo,
3088
+ projectName
3089
+ );
3090
+ return res.pullRequestId;
3091
+ },
3092
+ async getAdoRepoDefaultBranch({
3093
+ repoUrl
3094
+ }) {
3095
+ const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3096
+ const git = await api2.getGitApi();
3097
+ const getRepositoryRes = await git.getRepository(
3098
+ decodeURI(repo),
3099
+ projectName ? decodeURI(projectName) : void 0
3100
+ );
3101
+ if (!getRepositoryRes?.defaultBranch) {
3102
+ throw new InvalidRepoUrlError("no default branch");
3103
+ }
3104
+ return getRepositoryRes.defaultBranch.replace("refs/heads/", "");
3105
+ },
3106
+ // todo: refactor this function
3107
+ async getAdoReferenceData({
3108
+ ref,
3109
+ repoUrl
3110
+ }) {
3111
+ const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3112
+ if (!projectName) {
3113
+ throw new InvalidUrlPatternError("no project name");
3114
+ }
3115
+ const git = await api2.getGitApi();
3116
+ const results = await Promise.allSettled([
3117
+ (async () => {
3118
+ const res = await git.getBranch(repo, ref, projectName);
3119
+ if (!res.commit || !res.commit.commitId) {
3120
+ throw new InvalidRepoUrlError("no commit on branch");
3121
+ }
3122
+ return {
3123
+ sha: res.commit.commitId,
3124
+ type: "BRANCH" /* BRANCH */,
3125
+ date: res.commit.committer?.date || /* @__PURE__ */ new Date()
3126
+ };
3127
+ })(),
3128
+ (async () => {
3129
+ const res = await git.getCommits(
3130
+ repo,
3131
+ {
3132
+ fromCommitId: ref,
3133
+ toCommitId: ref,
3134
+ $top: 1
3135
+ },
3136
+ projectName
3137
+ );
3138
+ const commit = res[0];
3139
+ if (!commit || !commit.commitId) {
3140
+ throw new Error("no commit");
3141
+ }
3142
+ return {
3143
+ sha: commit.commitId,
3144
+ type: "COMMIT" /* COMMIT */,
3145
+ date: commit.committer?.date || /* @__PURE__ */ new Date()
3146
+ };
3147
+ })(),
3148
+ (async () => {
3149
+ const res = await git.getRefs(repo, projectName, `tags/${ref}`);
3150
+ if (!res[0] || !res[0].objectId) {
3151
+ throw new Error("no tag ref");
3152
+ }
3153
+ let objectId = res[0].objectId;
3154
+ try {
3155
+ const tag = await git.getAnnotatedTag(projectName, repo, objectId);
3156
+ if (tag.taggedObject?.objectId) {
3157
+ objectId = tag.taggedObject.objectId;
3158
+ }
3159
+ } catch (e) {
3160
+ }
3161
+ const commitRes2 = await git.getCommits(
3162
+ repo,
3163
+ {
3164
+ fromCommitId: objectId,
3165
+ toCommitId: objectId,
3166
+ $top: 1
3167
+ },
3168
+ projectName
3169
+ );
3170
+ const commit = commitRes2[0];
3171
+ if (!commit) {
3172
+ throw new Error("no commit");
3173
+ }
3174
+ return {
3175
+ sha: objectId,
3176
+ type: "TAG" /* TAG */,
3177
+ date: commit.committer?.date || /* @__PURE__ */ new Date()
3178
+ };
3179
+ })()
3180
+ ]);
3181
+ const [branchRes, commitRes, tagRes] = results;
3182
+ if (tagRes.status === "fulfilled") {
3183
+ return tagRes.value;
3184
+ }
3185
+ if (branchRes.status === "fulfilled") {
3186
+ return branchRes.value;
3187
+ }
3188
+ if (commitRes.status === "fulfilled") {
3189
+ return commitRes.value;
3190
+ }
3191
+ throw new RefNotFoundError(`ref: ${ref} does not exist`);
3192
+ },
3193
+ getAdoBlameRanges() {
3194
+ return [];
3195
+ }
3047
3196
  };
3048
3197
  }
3049
- function createBitbucketSdk(token) {
3050
- if (!token) {
3051
- return getBitbucketSdk({ authType: "public" });
3198
+ async function getAdoRepoList({
3199
+ orgName,
3200
+ tokenOrg,
3201
+ accessToken
3202
+ }) {
3203
+ let orgs = [];
3204
+ const adoTokenInfo = getAdoTokenInfo(accessToken);
3205
+ if (adoTokenInfo.type === "NONE" /* NONE */) {
3206
+ return [];
3052
3207
  }
3053
- if (token.includes(":")) {
3054
- const { password, username } = getUserAndPassword(token);
3055
- return getBitbucketSdk({
3056
- authType: "basic",
3057
- username,
3058
- password
3059
- });
3208
+ if (adoTokenInfo.type === "OAUTH" /* OAUTH */) {
3209
+ orgs = await _getOrgsForOauthToken({ oauthToken: accessToken });
3060
3210
  }
3061
- return getBitbucketSdk({ authType: "token", token });
3211
+ if (orgs.length === 0 && !orgName) {
3212
+ throw new Error(`no orgs for ADO`);
3213
+ } else if (orgs.length === 0 && orgName) {
3214
+ orgs = [orgName];
3215
+ }
3216
+ const repos = (await Promise.allSettled(
3217
+ orgs.map(async (org) => {
3218
+ const orgApi = await getAdoApiClient({
3219
+ ...await getAdoClientParams({
3220
+ accessToken,
3221
+ tokenOrg: tokenOrg || org,
3222
+ url: void 0
3223
+ }),
3224
+ orgName: org
3225
+ });
3226
+ const gitOrg = await orgApi.getGitApi();
3227
+ const orgRepos = await gitOrg.getRepositories();
3228
+ const repoInfoList = (await Promise.allSettled(
3229
+ orgRepos.map(async (repo) => {
3230
+ if (!repo.name || !repo.remoteUrl || !repo.defaultBranch) {
3231
+ throw new InvalidRepoUrlError("bad repo");
3232
+ }
3233
+ const branch = await gitOrg.getBranch(
3234
+ repo.name,
3235
+ repo.defaultBranch.replace(/^refs\/heads\//, ""),
3236
+ repo.project?.name
3237
+ );
3238
+ return {
3239
+ repoName: repo.name,
3240
+ repoUrl: repo.remoteUrl.replace(
3241
+ /^[hH][tT][tT][pP][sS]:\/\/[^/]+@/,
3242
+ "https://"
3243
+ ),
3244
+ repoOwner: org,
3245
+ repoIsPublic: repo.project?.visibility === 2 /* Public */,
3246
+ repoLanguages: [],
3247
+ repoUpdatedAt: branch.commit?.committer?.date?.toDateString() || repo.project?.lastUpdateTime?.toDateString() || (/* @__PURE__ */ new Date()).toDateString()
3248
+ };
3249
+ })
3250
+ )).reduce((acc, res) => {
3251
+ if (res.status === "fulfilled") {
3252
+ acc.push(res.value);
3253
+ }
3254
+ return acc;
3255
+ }, []);
3256
+ return repoInfoList;
3257
+ })
3258
+ )).reduce((acc, res) => {
3259
+ if (res.status === "fulfilled") {
3260
+ return acc.concat(res.value);
3261
+ }
3262
+ return acc;
3263
+ }, []);
3264
+ return repos;
3062
3265
  }
3063
- var BitbucketSCMLib = class extends SCMLib {
3064
- constructor(url, accessToken, scmOrg) {
3065
- super(url, accessToken, scmOrg);
3066
- __publicField(this, "bitbucketSdk");
3067
- const bitbucketSdk = createBitbucketSdk(accessToken);
3068
- this.bitbucketSdk = bitbucketSdk;
3266
+
3267
+ // src/features/analysis/scm/constants.ts
3268
+ var MOBB_ICON_IMG = "https://app.mobb.ai/gh-action/Logo_Rounded_Icon.svg";
3269
+
3270
+ // src/constants.ts
3271
+ var debug = Debug("mobbdev:constants");
3272
+ var __dirname = path2.dirname(fileURLToPath(import.meta.url));
3273
+ dotenv.config({ path: path2.join(__dirname, "../.env") });
3274
+ var scmFriendlyText = {
3275
+ ["Ado" /* Ado */]: "Azure DevOps",
3276
+ ["Bitbucket" /* Bitbucket */]: "Bitbucket",
3277
+ ["GitHub" /* GitHub */]: "GitGub",
3278
+ ["GitLab" /* GitLab */]: "GitLab"
3279
+ };
3280
+ var SCANNERS = {
3281
+ Checkmarx: "checkmarx",
3282
+ Codeql: "codeql",
3283
+ Fortify: "fortify",
3284
+ Snyk: "snyk",
3285
+ Sonarqube: "sonarqube"
3286
+ };
3287
+ var SupportedScannersZ = z10.enum([SCANNERS.Checkmarx, SCANNERS.Snyk]);
3288
+ var envVariablesSchema = z10.object({
3289
+ WEB_APP_URL: z10.string(),
3290
+ API_URL: z10.string(),
3291
+ HASURA_ACCESS_KEY: z10.string(),
3292
+ LOCAL_GRAPHQL_ENDPOINT: z10.string()
3293
+ }).required();
3294
+ var envVariables = envVariablesSchema.parse(process.env);
3295
+ debug("config %o", envVariables);
3296
+ var mobbAscii = `
3297
+ ..
3298
+ ..........
3299
+ .................
3300
+ ...........................
3301
+ ..............................
3302
+ ................................
3303
+ ..................................
3304
+ ....................................
3305
+ .....................................
3306
+ .............................................
3307
+ .................................................
3308
+ ............................... .................
3309
+ .................................. ............
3310
+ .................. ............. ..........
3311
+ ......... ........ ......... ......
3312
+ ............... ....
3313
+ .... ..
3314
+
3315
+ . ...
3316
+ ..............
3317
+ ......................
3318
+ ...........................
3319
+ ................................
3320
+ ......................................
3321
+ ...............................
3322
+ .................
3323
+ `;
3324
+ var PROJECT_DEFAULT_NAME = "My first project";
3325
+ var WEB_APP_URL = envVariables.WEB_APP_URL;
3326
+ var API_URL = envVariables.API_URL;
3327
+ var HASURA_ACCESS_KEY = envVariables.HASURA_ACCESS_KEY;
3328
+ var LOCAL_GRAPHQL_ENDPOINT = envVariables.LOCAL_GRAPHQL_ENDPOINT;
3329
+ var errorMessages = {
3330
+ missingCxProjectName: `project name ${chalk.bold(
3331
+ "(--cx-project-name)"
3332
+ )} is needed if you're using checkmarx`,
3333
+ missingUrl: `url ${chalk.bold(
3334
+ "(--url)"
3335
+ )} is needed if you're adding an SCM token`,
3336
+ invalidScmType: `SCM type ${chalk.bold(
3337
+ "(--scm-type)"
3338
+ )} is invalid, please use one of: ${Object.values(ScmType).join(", ")}`,
3339
+ missingToken: `SCM token ${chalk.bold(
3340
+ "(--token)"
3341
+ )} is needed if you're adding an SCM token`
3342
+ };
3343
+ var progressMassages = {
3344
+ processingVulnerabilityReportSuccess: "\u2699\uFE0F Vulnerability report proccessed successfully",
3345
+ processingVulnerabilityReport: "\u2699\uFE0F Proccessing vulnerability report",
3346
+ processingVulnerabilityReportFailed: "\u2699\uFE0F Error Proccessing vulnerability report"
3347
+ };
3348
+ var VUL_REPORT_DIGEST_TIMEOUT_MS = 1e3 * 60 * 20;
3349
+
3350
+ // src/features/analysis/index.ts
3351
+ import crypto from "node:crypto";
3352
+ import fs3 from "node:fs";
3353
+ import os from "node:os";
3354
+ import path6 from "node:path";
3355
+ import { pipeline } from "node:stream/promises";
3356
+
3357
+ // src/generates/client_generates.ts
3358
+ var MeDocument = `
3359
+ query Me {
3360
+ me {
3361
+ id
3362
+ email
3363
+ scmConfigs {
3364
+ id
3365
+ orgId
3366
+ refreshToken
3367
+ scmType
3368
+ scmUrl
3369
+ scmUsername
3370
+ token
3371
+ tokenLastUpdate
3372
+ userId
3373
+ scmOrg
3374
+ isTokenAvailable
3375
+ }
3069
3376
  }
3070
- getAuthData() {
3071
- const authType = this.bitbucketSdk.getAuthType();
3072
- switch (authType) {
3073
- case "basic": {
3074
- this._validateAccessToken();
3075
- const { username, password } = getUserAndPassword(this.accessToken);
3076
- return { username, password, authType };
3077
- }
3078
- case "token": {
3079
- return { authType, token: z7.string().parse(this.accessToken) };
3377
+ }
3378
+ `;
3379
+ var GetOrgAndProjectIdDocument = `
3380
+ query getOrgAndProjectId($filters: organization_to_organization_role_bool_exp, $limit: Int) {
3381
+ organization_to_organization_role(
3382
+ where: $filters
3383
+ order_by: {organization: {createdOn: desc}}
3384
+ limit: $limit
3385
+ ) {
3386
+ organization {
3387
+ id
3388
+ projects(order_by: {updatedAt: desc}) {
3389
+ id
3390
+ name
3080
3391
  }
3081
- case "public":
3082
- return { authType };
3083
3392
  }
3084
3393
  }
3085
- async createSubmitRequest(params) {
3086
- this._validateAccessTokenAndUrl();
3087
- const pullRequestRes = await this.bitbucketSdk.createPullRequest({
3088
- ...params,
3089
- repoUrl: this.url
3090
- });
3091
- return String(z7.number().parse(pullRequestRes.id));
3092
- }
3093
- async validateParams() {
3094
- return validateBitbucketParams({
3095
- bitbucketClient: this.bitbucketSdk,
3096
- url: this.url
3097
- });
3394
+ }
3395
+ `;
3396
+ var GetEncryptedApiTokenDocument = `
3397
+ query GetEncryptedApiToken($loginId: uuid!) {
3398
+ cli_login_by_pk(id: $loginId) {
3399
+ encryptedApiToken
3098
3400
  }
3099
- async getRepoList(scmOrg) {
3100
- this._validateAccessToken();
3101
- return this.bitbucketSdk.getRepos({
3102
- workspaceSlug: scmOrg
3103
- });
3401
+ }
3402
+ `;
3403
+ var FixReportStateDocument = `
3404
+ query FixReportState($id: uuid!) {
3405
+ fixReport_by_pk(id: $id) {
3406
+ state
3104
3407
  }
3105
- async getBranchList() {
3106
- this._validateAccessTokenAndUrl();
3107
- return this.bitbucketSdk.getBranchList({
3108
- repoUrl: this.url
3109
- });
3408
+ }
3409
+ `;
3410
+ var GetVulnerabilityReportPathsDocument = `
3411
+ query GetVulnerabilityReportPaths($vulnerabilityReportId: uuid!) {
3412
+ vulnerability_report_path(
3413
+ where: {vulnerabilityReportId: {_eq: $vulnerabilityReportId}}
3414
+ ) {
3415
+ path
3110
3416
  }
3111
- getScmLibType() {
3112
- return "BITBUCKET" /* BITBUCKET */;
3417
+ }
3418
+ `;
3419
+ var GetAnalysisDocument = `
3420
+ subscription getAnalysis($analysisId: uuid!) {
3421
+ analysis: fixReport_by_pk(id: $analysisId) {
3422
+ id
3423
+ state
3113
3424
  }
3114
- getAuthHeaders() {
3115
- const authType = this.bitbucketSdk.getAuthType();
3116
- switch (authType) {
3117
- case "public":
3118
- return {};
3119
- case "token":
3120
- return { authorization: `Bearer ${this.accessToken}` };
3121
- case "basic": {
3122
- this._validateAccessToken();
3123
- const { username, password } = getUserAndPassword(this.accessToken);
3124
- return {
3125
- authorization: `Basic ${Buffer.from(
3126
- username + ":" + password
3127
- ).toString("base64")}`
3128
- };
3425
+ }
3426
+ `;
3427
+ var GetAnalsyisDocument = `
3428
+ query getAnalsyis($analysisId: uuid!) {
3429
+ analysis: fixReport_by_pk(id: $analysisId) {
3430
+ id
3431
+ state
3432
+ repo {
3433
+ commitSha
3434
+ pullRequest
3435
+ }
3436
+ vulnerabilityReportId
3437
+ vulnerabilityReport {
3438
+ projectId
3439
+ project {
3440
+ organizationId
3441
+ }
3442
+ file {
3443
+ signedFile {
3444
+ url
3445
+ }
3129
3446
  }
3130
3447
  }
3131
3448
  }
3132
- async getDownloadUrl(sha) {
3133
- this._validateUrl();
3134
- return this.bitbucketSdk.getDownloadUrl({ url: this.url, sha });
3135
- }
3136
- async _getUsernameForAuthUrl() {
3137
- this._validateAccessTokenAndUrl();
3138
- const user = await this.bitbucketSdk.getUser();
3139
- if (!user.username) {
3140
- throw new Error("no username found");
3449
+ }
3450
+ `;
3451
+ var GetFixesDocument = `
3452
+ query getFixes($filters: fix_bool_exp!) {
3453
+ fixes: fix(where: $filters) {
3454
+ issueType
3455
+ id
3456
+ patchAndQuestions {
3457
+ __typename
3458
+ ... on FixData {
3459
+ patch
3460
+ }
3141
3461
  }
3142
- return user.username;
3143
3462
  }
3144
- async getIsRemoteBranch(branch) {
3145
- this._validateAccessTokenAndUrl();
3146
- try {
3147
- const res = await this.bitbucketSdk.getBranch({
3148
- branchName: branch,
3149
- repoUrl: this.url
3150
- });
3151
- return res.name === branch;
3152
- } catch (e) {
3153
- return false;
3463
+ }
3464
+ `;
3465
+ var GetVulByNodesMetadataDocument = `
3466
+ query getVulByNodesMetadata($filters: [vulnerability_report_issue_code_node_bool_exp!], $vulnerabilityReportId: uuid!) {
3467
+ vulnerabilityReportIssueCodeNodes: vulnerability_report_issue_code_node(
3468
+ order_by: {index: desc}
3469
+ where: {_or: $filters, vulnerabilityReportIssue: {fixId: {_is_null: false}, vulnerabilityReportId: {_eq: $vulnerabilityReportId}}}
3470
+ ) {
3471
+ vulnerabilityReportIssueId
3472
+ path
3473
+ startLine
3474
+ vulnerabilityReportIssue {
3475
+ issueType
3476
+ fixId
3154
3477
  }
3155
3478
  }
3156
- async getUserHasAccessToRepo() {
3157
- this._validateAccessTokenAndUrl();
3158
- return this.bitbucketSdk.getIsUserCollaborator({ repoUrl: this.url });
3159
- }
3160
- async getUsername() {
3161
- this._validateAccessToken();
3162
- const res = await this.bitbucketSdk.getUser();
3163
- return z7.string().parse(res.username);
3164
- }
3165
- async getSubmitRequestStatus(_scmSubmitRequestId) {
3166
- this._validateAccessTokenAndUrl();
3167
- const pullRequestRes = await this.bitbucketSdk.getPullRequest({
3168
- prNumber: Number(_scmSubmitRequestId),
3169
- url: this.url
3170
- });
3171
- switch (pullRequestRes.state) {
3172
- case "OPEN":
3173
- return "open";
3174
- case "MERGED":
3175
- return "merged";
3176
- case "DECLINED":
3177
- return "closed";
3178
- default:
3179
- throw new Error(`unknown state ${pullRequestRes.state} `);
3479
+ fixablePrVuls: vulnerability_report_issue_aggregate(
3480
+ where: {fixId: {_is_null: false}, vulnerabilityReportId: {_eq: $vulnerabilityReportId}, codeNodes: {_or: $filters}}
3481
+ ) {
3482
+ aggregate {
3483
+ count
3180
3484
  }
3181
3485
  }
3182
- async getRepoBlameRanges(_ref, _path) {
3183
- return [];
3184
- }
3185
- async getReferenceData(ref) {
3186
- this._validateUrl();
3187
- return this.bitbucketSdk.getReferenceData({ url: this.url, ref });
3188
- }
3189
- async getRepoDefaultBranch() {
3190
- this._validateUrl();
3191
- const repoRes = await this.bitbucketSdk.getRepo({ repoUrl: this.url });
3192
- return z7.string().parse(repoRes.mainbranch?.name);
3193
- }
3194
- getPrUrl(prNumber) {
3195
- this._validateUrl();
3196
- const { repoSlug, workspace } = parseBitbucketOrganizationAndRepo(this.url);
3197
- return Promise.resolve(
3198
- `https://bitbucket.org/${workspace}/${repoSlug}/pull-requests/${prNumber}`
3199
- );
3200
- }
3201
- async refreshToken(params) {
3202
- const getBitbucketTokenResponse = await getBitbucketToken({
3203
- authType: "refresh_token",
3204
- ...params
3205
- });
3206
- return {
3207
- accessToken: getBitbucketTokenResponse.access_token,
3208
- refreshToken: getBitbucketTokenResponse.refresh_token
3209
- };
3486
+ nonFixablePrVuls: vulnerability_report_issue_aggregate(
3487
+ where: {fixId: {_is_null: true}, vulnerabilityReportId: {_eq: $vulnerabilityReportId}, codeNodes: {_or: $filters}}
3488
+ ) {
3489
+ aggregate {
3490
+ count
3491
+ }
3492
+ }
3493
+ totalScanVulnerabilities: vulnerability_report_issue_aggregate(
3494
+ where: {vulnerabilityReportId: {_eq: $vulnerabilityReportId}}
3495
+ ) {
3496
+ aggregate {
3497
+ count
3498
+ }
3210
3499
  }
3211
- };
3212
-
3213
- // src/features/analysis/scm/ado/validation.ts
3214
- import { z as z8 } from "zod";
3215
- var ValidPullRequestStatusZ = z8.union([
3216
- z8.literal(1 /* Active */),
3217
- z8.literal(2 /* Abandoned */),
3218
- z8.literal(3 /* Completed */)
3219
- ]);
3220
- var AdoAuthResultZ = z8.object({
3221
- access_token: z8.string().min(1),
3222
- token_type: z8.string().min(1),
3223
- refresh_token: z8.string().min(1)
3224
- });
3225
- var profileZ = z8.object({
3226
- displayName: z8.string(),
3227
- publicAlias: z8.string().min(1),
3228
- emailAddress: z8.string(),
3229
- coreRevision: z8.number(),
3230
- timeStamp: z8.string(),
3231
- id: z8.string(),
3232
- revision: z8.number()
3233
- });
3234
- var accountsZ = z8.object({
3235
- count: z8.number(),
3236
- value: z8.array(
3237
- z8.object({
3238
- accountId: z8.string(),
3239
- accountUri: z8.string(),
3240
- accountName: z8.string()
3241
- })
3242
- )
3243
- });
3244
-
3245
- // src/features/analysis/scm/ado/utils.ts
3246
- function _getPublicAdoClient({
3247
- orgName,
3248
- origin: origin2
3249
- }) {
3250
- const orgUrl = `${origin2}/${orgName}`;
3251
- const authHandler = api.getPersonalAccessTokenHandler("");
3252
- authHandler.canHandleAuthentication = () => false;
3253
- authHandler.prepareRequest = (_options) => {
3254
- return;
3255
- };
3256
- const connection = new api.WebApi(orgUrl, authHandler);
3257
- return connection;
3258
- }
3259
- function removeTrailingSlash2(str) {
3260
- return str.trim().replace(/\/+$/, "");
3261
3500
  }
3262
- function parseAdoOwnerAndRepo(adoUrl) {
3263
- adoUrl = removeTrailingSlash2(adoUrl);
3264
- const parsingResult = parseScmURL(adoUrl, "Ado" /* Ado */);
3265
- if (!parsingResult) {
3266
- throw new InvalidUrlPatternError(`
3267
- : ${adoUrl}`);
3501
+ `;
3502
+ var UpdateScmTokenDocument = `
3503
+ mutation updateScmToken($scmType: String!, $url: String!, $token: String!, $org: String, $refreshToken: String) {
3504
+ updateScmToken(
3505
+ scmType: $scmType
3506
+ url: $url
3507
+ token: $token
3508
+ org: $org
3509
+ refreshToken: $refreshToken
3510
+ ) {
3511
+ __typename
3512
+ ... on ScmAccessTokenUpdateSuccess {
3513
+ token
3514
+ }
3515
+ ... on InvalidScmTypeError {
3516
+ status
3517
+ error
3518
+ }
3519
+ ... on BadScmCredentials {
3520
+ status
3521
+ error
3522
+ }
3268
3523
  }
3269
- const {
3270
- organization,
3271
- repoName,
3272
- projectName,
3273
- projectPath,
3274
- pathElements,
3275
- hostname,
3276
- protocol
3277
- } = parsingResult;
3278
- return {
3279
- owner: decodeURI(organization),
3280
- repo: decodeURI(repoName),
3281
- projectName: projectName ? decodeURI(projectName) : void 0,
3282
- projectPath,
3283
- pathElements,
3284
- origin: `${protocol}//${hostname}`
3285
- };
3286
3524
  }
3287
- async function getAdoConnectData({
3288
- url,
3289
- tokenOrg,
3290
- adoTokenInfo
3291
- }) {
3292
- if (url && new URL(url).origin !== url) {
3293
- const { owner, origin: origin2 } = parseAdoOwnerAndRepo(url);
3294
- return {
3295
- org: owner,
3296
- origin: origin2
3297
- };
3525
+ `;
3526
+ var UploadS3BucketInfoDocument = `
3527
+ mutation uploadS3BucketInfo($fileName: String!) {
3528
+ uploadS3BucketInfo(fileName: $fileName) {
3529
+ status
3530
+ error
3531
+ reportUploadInfo: uploadInfo {
3532
+ url
3533
+ fixReportId
3534
+ uploadFieldsJSON
3535
+ uploadKey
3536
+ }
3537
+ repoUploadInfo {
3538
+ url
3539
+ fixReportId
3540
+ uploadFieldsJSON
3541
+ uploadKey
3542
+ }
3298
3543
  }
3299
- if (!tokenOrg) {
3300
- if (adoTokenInfo.type === "OAUTH" /* OAUTH */) {
3301
- const [org] = await _getOrgsForOauthToken({
3302
- oauthToken: adoTokenInfo.accessToken
3303
- });
3304
- return {
3305
- org: z9.string().parse(org),
3306
- origin: DEFUALT_ADO_ORIGIN
3307
- };
3544
+ }
3545
+ `;
3546
+ var DigestVulnerabilityReportDocument = `
3547
+ mutation DigestVulnerabilityReport($vulnerabilityReportFileName: String!, $fixReportId: String!, $projectId: String!, $scanSource: String!) {
3548
+ digestVulnerabilityReport(
3549
+ fixReportId: $fixReportId
3550
+ vulnerabilityReportFileName: $vulnerabilityReportFileName
3551
+ projectId: $projectId
3552
+ scanSource: $scanSource
3553
+ ) {
3554
+ __typename
3555
+ ... on VulnerabilityReport {
3556
+ vulnerabilityReportId
3557
+ fixReportId
3558
+ }
3559
+ ... on RabbitSendError {
3560
+ status
3561
+ error
3562
+ }
3563
+ ... on ReportValidationError {
3564
+ status
3565
+ error
3566
+ }
3567
+ ... on ReferenceNotFoundError {
3568
+ status
3569
+ error
3308
3570
  }
3309
- throw new InvalidRepoUrlError("ADO URL is null");
3310
3571
  }
3311
- return {
3312
- org: tokenOrg,
3313
- origin: DEFUALT_ADO_ORIGIN
3314
- };
3315
3572
  }
3316
- async function getAdoApiClient(params) {
3317
- const { origin: origin2 = DEFUALT_ADO_ORIGIN, orgName } = params;
3318
- if (params.tokenType === "NONE" /* NONE */ || // move to public client if the token is not associated with the PAT org
3319
- params.tokenType === "PAT" /* PAT */ && params.patTokenOrg !== orgName) {
3320
- return _getPublicAdoClient({ orgName, origin: origin2 });
3573
+ `;
3574
+ var SubmitVulnerabilityReportDocument = `
3575
+ mutation SubmitVulnerabilityReport($fixReportId: String!, $repoUrl: String!, $reference: String!, $projectId: String!, $scanSource: String!, $sha: String, $experimentalEnabled: Boolean, $vulnerabilityReportFileName: String, $pullRequest: Int) {
3576
+ submitVulnerabilityReport(
3577
+ fixReportId: $fixReportId
3578
+ repoUrl: $repoUrl
3579
+ reference: $reference
3580
+ sha: $sha
3581
+ experimentalEnabled: $experimentalEnabled
3582
+ pullRequest: $pullRequest
3583
+ projectId: $projectId
3584
+ vulnerabilityReportFileName: $vulnerabilityReportFileName
3585
+ scanSource: $scanSource
3586
+ ) {
3587
+ __typename
3588
+ ... on VulnerabilityReport {
3589
+ vulnerabilityReportId
3590
+ fixReportId
3591
+ }
3321
3592
  }
3322
- const orgUrl = `${origin2}/${orgName}`;
3323
- if (params.tokenType === "OAUTH" /* OAUTH */) {
3324
- if (origin2 !== DEFUALT_ADO_ORIGIN) {
3325
- throw new Error(
3326
- `Oauth token is not supported for ADO on prem - ${origin2} `
3327
- );
3593
+ }
3594
+ `;
3595
+ var CreateCommunityUserDocument = `
3596
+ mutation CreateCommunityUser {
3597
+ initOrganizationAndProject {
3598
+ __typename
3599
+ ... on InitOrganizationAndProjectGoodResponse {
3600
+ projectId
3601
+ userId
3602
+ organizationId
3603
+ }
3604
+ ... on UserAlreadyInProjectError {
3605
+ error
3606
+ status
3328
3607
  }
3329
- const connection2 = new api.WebApi(
3330
- orgUrl,
3331
- api.getBearerHandler(params.accessToken),
3332
- {}
3333
- );
3334
- return connection2;
3335
3608
  }
3336
- const authHandler = api.getPersonalAccessTokenHandler(params.accessToken);
3337
- const isBroker = BROKERED_HOSTS.includes(new URL(orgUrl).origin);
3338
- const connection = new api.WebApi(
3339
- orgUrl,
3340
- authHandler,
3341
- isBroker ? {
3342
- proxy: {
3343
- proxyUrl: GIT_PROXY_HOST
3344
- },
3345
- ignoreSslError: true
3346
- } : void 0
3347
- );
3348
- return connection;
3349
3609
  }
3350
- function getAdoTokenInfo(token) {
3351
- if (!token) {
3352
- return { type: "NONE" /* NONE */ };
3610
+ `;
3611
+ var CreateCliLoginDocument = `
3612
+ mutation CreateCliLogin($publicKey: String!) {
3613
+ insert_cli_login_one(object: {publicKey: $publicKey}) {
3614
+ id
3353
3615
  }
3354
- if (token.includes(".")) {
3355
- return { type: "OAUTH" /* OAUTH */, accessToken: token };
3616
+ }
3617
+ `;
3618
+ var PerformCliLoginDocument = `
3619
+ mutation performCliLogin($loginId: String!) {
3620
+ performCliLogin(loginId: $loginId) {
3621
+ status
3356
3622
  }
3357
- return { type: "PAT" /* PAT */, accessToken: token };
3358
3623
  }
3359
- async function getAdoClientParams(params) {
3360
- const { url, accessToken, tokenOrg } = params;
3361
- const adoTokenInfo = getAdoTokenInfo(accessToken);
3362
- const { org, origin: origin2 } = await getAdoConnectData({
3363
- url,
3364
- tokenOrg,
3365
- adoTokenInfo
3366
- });
3367
- switch (adoTokenInfo.type) {
3368
- case "NONE" /* NONE */:
3369
- return {
3370
- tokenType: "NONE" /* NONE */,
3371
- origin: origin2,
3372
- orgName: org.toLowerCase()
3373
- };
3374
- case "OAUTH" /* OAUTH */: {
3375
- return {
3376
- tokenType: "OAUTH" /* OAUTH */,
3377
- accessToken: adoTokenInfo.accessToken,
3378
- origin: origin2,
3379
- orgName: org.toLowerCase()
3380
- };
3381
- }
3382
- case "PAT" /* PAT */: {
3383
- return {
3384
- tokenType: "PAT" /* PAT */,
3385
- accessToken: adoTokenInfo.accessToken,
3386
- patTokenOrg: z9.string().parse(tokenOrg).toLowerCase(),
3387
- origin: origin2,
3388
- orgName: org.toLowerCase()
3389
- };
3390
- }
3624
+ `;
3625
+ var CreateProjectDocument = `
3626
+ mutation CreateProject($organizationId: String!, $projectName: String!) {
3627
+ createProject(organizationId: $organizationId, projectName: $projectName) {
3628
+ projectId
3391
3629
  }
3392
3630
  }
3393
- async function adoValidateParams({
3394
- url,
3395
- accessToken,
3396
- tokenOrg
3397
- }) {
3398
- try {
3399
- const api2 = await getAdoApiClient(
3400
- await getAdoClientParams({ url, accessToken, tokenOrg })
3401
- );
3402
- await api2.connect();
3403
- } catch (e) {
3404
- console.log("adoValidateParams error", e);
3405
- const error = e;
3406
- const code = error.code || error.status || error.statusCode || error.response?.status || error.response?.statusCode || error.response?.code;
3407
- const description = error.description || `${e}`;
3408
- if (code === 401 || code === 403 || description.includes("401") || description.includes("403")) {
3409
- throw new InvalidAccessTokenError(`invalid ADO access token`);
3631
+ `;
3632
+ var ValidateRepoUrlDocument = `
3633
+ query validateRepoUrl($repoUrl: String!) {
3634
+ validateRepoUrl(repoUrl: $repoUrl) {
3635
+ __typename
3636
+ ... on RepoValidationSuccess {
3637
+ status
3638
+ defaultBranch
3639
+ defaultBranchLastModified
3640
+ defaultBranchSha
3641
+ scmType
3410
3642
  }
3411
- if (code === 404 || description.includes("404") || description.includes("Not Found")) {
3412
- throw new InvalidRepoUrlError(`invalid ADO repo URL ${url}`);
3643
+ ... on RepoUnreachableError {
3644
+ status
3645
+ error
3646
+ scmType
3647
+ }
3648
+ ... on BadScmCredentials {
3649
+ status
3650
+ error
3651
+ scmType
3413
3652
  }
3414
- throw e;
3415
3653
  }
3416
3654
  }
3417
- async function _getOrgsForOauthToken({
3418
- oauthToken
3419
- }) {
3420
- const profileRes = await fetch(
3421
- "https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=6.0",
3422
- {
3423
- method: "GET",
3424
- headers: {
3425
- Authorization: `Bearer ${oauthToken}`
3426
- }
3655
+ `;
3656
+ var GitReferenceDocument = `
3657
+ query gitReference($repoUrl: String!, $reference: String!) {
3658
+ gitReference(repoUrl: $repoUrl, reference: $reference) {
3659
+ __typename
3660
+ ... on GitReferenceData {
3661
+ status
3662
+ sha
3663
+ date
3427
3664
  }
3428
- );
3429
- const profileJson = await profileRes.json();
3430
- const profile = profileZ.parse(profileJson);
3431
- const accountsRes = await fetch(
3432
- `https://app.vssps.visualstudio.com/_apis/accounts?memberId=${profile.publicAlias}&api-version=6.0`,
3433
- {
3434
- method: "GET",
3435
- headers: {
3436
- Authorization: `Bearer ${oauthToken}`
3437
- }
3665
+ ... on ReferenceNotFoundError {
3666
+ status
3667
+ error
3438
3668
  }
3439
- );
3440
- const accountsJson = await accountsRes.json();
3441
- const accounts = accountsZ.parse(accountsJson);
3442
- const orgs = accounts.value.map((account) => account.accountName).filter((value, index, array) => array.indexOf(value) === index);
3443
- return orgs;
3669
+ }
3444
3670
  }
3445
-
3446
- // src/features/analysis/scm/ado/ado.ts
3447
- async function getAdoSdk(params) {
3448
- const api2 = await getAdoApiClient(params);
3671
+ `;
3672
+ var defaultWrapper = (action, _operationName, _operationType, _variables) => action();
3673
+ function getSdk(client, withWrapper = defaultWrapper) {
3449
3674
  return {
3450
- async getAdoIsUserCollaborator({ repoUrl }) {
3451
- try {
3452
- const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3453
- const git = await api2.getGitApi();
3454
- const branches = await git.getBranches(repo, projectName);
3455
- if (!branches || branches.length === 0) {
3456
- throw new InvalidRepoUrlError("no branches");
3457
- }
3458
- return true;
3459
- } catch (e) {
3460
- return false;
3461
- }
3675
+ Me(variables, requestHeaders) {
3676
+ return withWrapper((wrappedRequestHeaders) => client.request(MeDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "Me", "query", variables);
3462
3677
  },
3463
- async getAdoPullRequestStatus({
3464
- repoUrl,
3465
- prNumber
3466
- }) {
3467
- const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3468
- const git = await api2.getGitApi();
3469
- const res = await git.getPullRequest(repo, prNumber, projectName);
3470
- const parsedPullRequestStatus = ValidPullRequestStatusZ.safeParse(
3471
- res.status
3472
- );
3473
- if (!parsedPullRequestStatus.success) {
3474
- throw new Error("bad pr status for ADO");
3475
- }
3476
- return parsedPullRequestStatus.data;
3678
+ getOrgAndProjectId(variables, requestHeaders) {
3679
+ return withWrapper((wrappedRequestHeaders) => client.request(GetOrgAndProjectIdDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "getOrgAndProjectId", "query", variables);
3477
3680
  },
3478
- async getAdoIsRemoteBranch({
3479
- repoUrl,
3480
- branch
3481
- }) {
3482
- const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3483
- const git = await api2.getGitApi();
3484
- try {
3485
- const branchStatus = await git.getBranch(repo, branch, projectName);
3486
- if (!branchStatus || !branchStatus.commit) {
3487
- throw new InvalidRepoUrlError("no branch status");
3488
- }
3489
- return branchStatus.name === branch;
3490
- } catch (e) {
3491
- return false;
3492
- }
3681
+ GetEncryptedApiToken(variables, requestHeaders) {
3682
+ return withWrapper((wrappedRequestHeaders) => client.request(GetEncryptedApiTokenDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "GetEncryptedApiToken", "query", variables);
3493
3683
  },
3494
- async getAdoPrUrl({ url, prNumber }) {
3495
- const { repo, projectName } = parseAdoOwnerAndRepo(url);
3496
- const git = await api2.getGitApi();
3497
- const getRepositoryRes = await git.getRepository(
3498
- decodeURI(repo),
3499
- projectName ? decodeURI(projectName) : void 0
3500
- );
3501
- return `${getRepositoryRes.webUrl}/pullrequest/${prNumber}`;
3684
+ FixReportState(variables, requestHeaders) {
3685
+ return withWrapper((wrappedRequestHeaders) => client.request(FixReportStateDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "FixReportState", "query", variables);
3502
3686
  },
3503
- getAdoDownloadUrl({
3504
- repoUrl,
3505
- branch
3506
- }) {
3507
- const { owner, repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3508
- const url = new URL(repoUrl);
3509
- const origin2 = url.origin.toLowerCase().endsWith(".visualstudio.com") ? DEFUALT_ADO_ORIGIN : url.origin.toLowerCase();
3510
- return `${origin2}/${owner}/${projectName}/_apis/git/repositories/${repo}/items/items?path=/&versionDescriptor[versionOptions]=0&versionDescriptor[versionType]=commit&versionDescriptor[version]=${branch}&resolveLfs=true&$format=zip&api-version=5.0&download=true`;
3687
+ GetVulnerabilityReportPaths(variables, requestHeaders) {
3688
+ return withWrapper((wrappedRequestHeaders) => client.request(GetVulnerabilityReportPathsDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "GetVulnerabilityReportPaths", "query", variables);
3511
3689
  },
3512
- async getAdoBranchList({ repoUrl }) {
3513
- const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3514
- const git = await api2.getGitApi();
3515
- try {
3516
- const res = await git.getBranches(repo, projectName);
3517
- res.sort((a, b) => {
3518
- if (!a.commit?.committer?.date || !b.commit?.committer?.date) {
3519
- return 0;
3520
- }
3521
- return b.commit?.committer?.date.getTime() - a.commit?.committer?.date.getTime();
3522
- });
3523
- return res.reduce((acc, branch) => {
3524
- if (!branch.name) {
3525
- return acc;
3526
- }
3527
- acc.push(branch.name);
3528
- return acc;
3529
- }, []);
3530
- } catch (e) {
3531
- return [];
3532
- }
3690
+ getAnalysis(variables, requestHeaders) {
3691
+ return withWrapper((wrappedRequestHeaders) => client.request(GetAnalysisDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "getAnalysis", "subscription", variables);
3533
3692
  },
3534
- async createAdoPullRequest(options) {
3535
- const { repoUrl, sourceBranchName, targetBranchName, title, body } = options;
3536
- const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3537
- const git = await api2.getGitApi();
3538
- const res = await git.createPullRequest(
3539
- {
3540
- sourceRefName: `refs/heads/${sourceBranchName}`,
3541
- targetRefName: `refs/heads/${targetBranchName}`,
3542
- title,
3543
- description: body
3544
- },
3545
- repo,
3546
- projectName
3547
- );
3548
- return res.pullRequestId;
3693
+ getAnalsyis(variables, requestHeaders) {
3694
+ return withWrapper((wrappedRequestHeaders) => client.request(GetAnalsyisDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "getAnalsyis", "query", variables);
3549
3695
  },
3550
- async getAdoRepoDefaultBranch({
3551
- repoUrl
3552
- }) {
3553
- const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3554
- const git = await api2.getGitApi();
3555
- const getRepositoryRes = await git.getRepository(
3556
- decodeURI(repo),
3557
- projectName ? decodeURI(projectName) : void 0
3558
- );
3559
- if (!getRepositoryRes?.defaultBranch) {
3560
- throw new InvalidRepoUrlError("no default branch");
3561
- }
3562
- return getRepositoryRes.defaultBranch.replace("refs/heads/", "");
3696
+ getFixes(variables, requestHeaders) {
3697
+ return withWrapper((wrappedRequestHeaders) => client.request(GetFixesDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "getFixes", "query", variables);
3563
3698
  },
3564
- // todo: refactor this function
3565
- async getAdoReferenceData({
3566
- ref,
3567
- repoUrl
3568
- }) {
3569
- const { repo, projectName } = parseAdoOwnerAndRepo(repoUrl);
3570
- if (!projectName) {
3571
- throw new InvalidUrlPatternError("no project name");
3572
- }
3573
- const git = await api2.getGitApi();
3574
- const results = await Promise.allSettled([
3575
- (async () => {
3576
- const res = await git.getBranch(repo, ref, projectName);
3577
- if (!res.commit || !res.commit.commitId) {
3578
- throw new InvalidRepoUrlError("no commit on branch");
3579
- }
3580
- return {
3581
- sha: res.commit.commitId,
3582
- type: "BRANCH" /* BRANCH */,
3583
- date: res.commit.committer?.date || /* @__PURE__ */ new Date()
3584
- };
3585
- })(),
3586
- (async () => {
3587
- const res = await git.getCommits(
3588
- repo,
3589
- {
3590
- fromCommitId: ref,
3591
- toCommitId: ref,
3592
- $top: 1
3593
- },
3594
- projectName
3595
- );
3596
- const commit = res[0];
3597
- if (!commit || !commit.commitId) {
3598
- throw new Error("no commit");
3599
- }
3600
- return {
3601
- sha: commit.commitId,
3602
- type: "COMMIT" /* COMMIT */,
3603
- date: commit.committer?.date || /* @__PURE__ */ new Date()
3604
- };
3605
- })(),
3606
- (async () => {
3607
- const res = await git.getRefs(repo, projectName, `tags/${ref}`);
3608
- if (!res[0] || !res[0].objectId) {
3609
- throw new Error("no tag ref");
3610
- }
3611
- let objectId = res[0].objectId;
3612
- try {
3613
- const tag = await git.getAnnotatedTag(projectName, repo, objectId);
3614
- if (tag.taggedObject?.objectId) {
3615
- objectId = tag.taggedObject.objectId;
3616
- }
3617
- } catch (e) {
3618
- }
3619
- const commitRes2 = await git.getCommits(
3620
- repo,
3621
- {
3622
- fromCommitId: objectId,
3623
- toCommitId: objectId,
3624
- $top: 1
3625
- },
3626
- projectName
3627
- );
3628
- const commit = commitRes2[0];
3629
- if (!commit) {
3630
- throw new Error("no commit");
3631
- }
3632
- return {
3633
- sha: objectId,
3634
- type: "TAG" /* TAG */,
3635
- date: commit.committer?.date || /* @__PURE__ */ new Date()
3636
- };
3637
- })()
3638
- ]);
3639
- const [branchRes, commitRes, tagRes] = results;
3640
- if (tagRes.status === "fulfilled") {
3641
- return tagRes.value;
3642
- }
3643
- if (branchRes.status === "fulfilled") {
3644
- return branchRes.value;
3645
- }
3646
- if (commitRes.status === "fulfilled") {
3647
- return commitRes.value;
3648
- }
3649
- throw new RefNotFoundError(`ref: ${ref} does not exist`);
3699
+ getVulByNodesMetadata(variables, requestHeaders) {
3700
+ return withWrapper((wrappedRequestHeaders) => client.request(GetVulByNodesMetadataDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "getVulByNodesMetadata", "query", variables);
3701
+ },
3702
+ updateScmToken(variables, requestHeaders) {
3703
+ return withWrapper((wrappedRequestHeaders) => client.request(UpdateScmTokenDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "updateScmToken", "mutation", variables);
3650
3704
  },
3651
- getAdoBlameRanges() {
3652
- return [];
3705
+ uploadS3BucketInfo(variables, requestHeaders) {
3706
+ return withWrapper((wrappedRequestHeaders) => client.request(UploadS3BucketInfoDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "uploadS3BucketInfo", "mutation", variables);
3707
+ },
3708
+ DigestVulnerabilityReport(variables, requestHeaders) {
3709
+ return withWrapper((wrappedRequestHeaders) => client.request(DigestVulnerabilityReportDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "DigestVulnerabilityReport", "mutation", variables);
3710
+ },
3711
+ SubmitVulnerabilityReport(variables, requestHeaders) {
3712
+ return withWrapper((wrappedRequestHeaders) => client.request(SubmitVulnerabilityReportDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "SubmitVulnerabilityReport", "mutation", variables);
3713
+ },
3714
+ CreateCommunityUser(variables, requestHeaders) {
3715
+ return withWrapper((wrappedRequestHeaders) => client.request(CreateCommunityUserDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "CreateCommunityUser", "mutation", variables);
3716
+ },
3717
+ CreateCliLogin(variables, requestHeaders) {
3718
+ return withWrapper((wrappedRequestHeaders) => client.request(CreateCliLoginDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "CreateCliLogin", "mutation", variables);
3719
+ },
3720
+ performCliLogin(variables, requestHeaders) {
3721
+ return withWrapper((wrappedRequestHeaders) => client.request(PerformCliLoginDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "performCliLogin", "mutation", variables);
3722
+ },
3723
+ CreateProject(variables, requestHeaders) {
3724
+ return withWrapper((wrappedRequestHeaders) => client.request(CreateProjectDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "CreateProject", "mutation", variables);
3725
+ },
3726
+ validateRepoUrl(variables, requestHeaders) {
3727
+ return withWrapper((wrappedRequestHeaders) => client.request(ValidateRepoUrlDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "validateRepoUrl", "query", variables);
3728
+ },
3729
+ gitReference(variables, requestHeaders) {
3730
+ return withWrapper((wrappedRequestHeaders) => client.request(GitReferenceDocument, variables, { ...requestHeaders, ...wrappedRequestHeaders }), "gitReference", "query", variables);
3653
3731
  }
3654
3732
  };
3655
3733
  }
3656
- async function getAdoRepoList({
3657
- orgName,
3658
- tokenOrg,
3659
- accessToken
3660
- }) {
3661
- let orgs = [];
3662
- const adoTokenInfo = getAdoTokenInfo(accessToken);
3663
- if (adoTokenInfo.type === "NONE" /* NONE */) {
3664
- return [];
3665
- }
3666
- if (adoTokenInfo.type === "OAUTH" /* OAUTH */) {
3667
- orgs = await _getOrgsForOauthToken({ oauthToken: accessToken });
3668
- }
3669
- if (orgs.length === 0 && !orgName) {
3670
- throw new Error(`no orgs for ADO`);
3671
- } else if (orgs.length === 0 && orgName) {
3672
- orgs = [orgName];
3673
- }
3674
- const repos = (await Promise.allSettled(
3675
- orgs.map(async (org) => {
3676
- const orgApi = await getAdoApiClient({
3677
- ...await getAdoClientParams({
3678
- accessToken,
3679
- tokenOrg: tokenOrg || org,
3680
- url: void 0
3681
- }),
3682
- orgName: org
3683
- });
3684
- const gitOrg = await orgApi.getGitApi();
3685
- const orgRepos = await gitOrg.getRepositories();
3686
- const repoInfoList = (await Promise.allSettled(
3687
- orgRepos.map(async (repo) => {
3688
- if (!repo.name || !repo.remoteUrl || !repo.defaultBranch) {
3689
- throw new InvalidRepoUrlError("bad repo");
3690
- }
3691
- const branch = await gitOrg.getBranch(
3692
- repo.name,
3693
- repo.defaultBranch.replace(/^refs\/heads\//, ""),
3694
- repo.project?.name
3695
- );
3696
- return {
3697
- repoName: repo.name,
3698
- repoUrl: repo.remoteUrl.replace(
3699
- /^[hH][tT][tT][pP][sS]:\/\/[^/]+@/,
3700
- "https://"
3701
- ),
3702
- repoOwner: org,
3703
- repoIsPublic: repo.project?.visibility === 2 /* Public */,
3704
- repoLanguages: [],
3705
- repoUpdatedAt: branch.commit?.committer?.date?.toDateString() || repo.project?.lastUpdateTime?.toDateString() || (/* @__PURE__ */ new Date()).toDateString()
3706
- };
3707
- })
3708
- )).reduce((acc, res) => {
3709
- if (res.status === "fulfilled") {
3710
- acc.push(res.value);
3711
- }
3712
- return acc;
3713
- }, []);
3714
- return repoInfoList;
3715
- })
3716
- )).reduce((acc, res) => {
3717
- if (res.status === "fulfilled") {
3718
- return acc.concat(res.value);
3719
- }
3720
- return acc;
3721
- }, []);
3722
- return repos;
3734
+
3735
+ // src/utils/index.ts
3736
+ var utils_exports = {};
3737
+ __export(utils_exports, {
3738
+ CliError: () => CliError,
3739
+ Spinner: () => Spinner,
3740
+ getDirName: () => getDirName,
3741
+ getTopLevelDirName: () => getTopLevelDirName,
3742
+ keypress: () => keypress,
3743
+ sleep: () => sleep
3744
+ });
3745
+
3746
+ // src/utils/dirname.ts
3747
+ import path3 from "node:path";
3748
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
3749
+ function getDirName() {
3750
+ return path3.dirname(fileURLToPath2(import.meta.url));
3751
+ }
3752
+ function getTopLevelDirName(fullPath) {
3753
+ return path3.parse(fullPath).name;
3723
3754
  }
3724
3755
 
3725
- // src/features/analysis/scm/constants.ts
3726
- var MOBB_ICON_IMG = "https://app.mobb.ai/gh-action/Logo_Rounded_Icon.svg";
3756
+ // src/utils/keypress.ts
3757
+ import readline from "node:readline";
3758
+ async function keypress() {
3759
+ const rl = readline.createInterface({
3760
+ input: process.stdin,
3761
+ output: process.stdout
3762
+ });
3763
+ return new Promise((resolve) => {
3764
+ rl.question("", (answer) => {
3765
+ rl.close();
3766
+ process.stderr.moveCursor(0, -1);
3767
+ process.stderr.clearLine(1);
3768
+ resolve(answer);
3769
+ });
3770
+ });
3771
+ }
3772
+
3773
+ // src/utils/spinner.ts
3774
+ import {
3775
+ createSpinner as _createSpinner
3776
+ } from "nanospinner";
3777
+ var mockSpinner = {
3778
+ success: () => mockSpinner,
3779
+ error: () => mockSpinner,
3780
+ warn: () => mockSpinner,
3781
+ stop: () => mockSpinner,
3782
+ start: () => mockSpinner,
3783
+ update: () => mockSpinner,
3784
+ reset: () => mockSpinner,
3785
+ clear: () => mockSpinner,
3786
+ spin: () => mockSpinner
3787
+ };
3788
+ function Spinner({ ci = false } = {}) {
3789
+ return {
3790
+ createSpinner: (text, options) => ci ? mockSpinner : _createSpinner(text, options)
3791
+ };
3792
+ }
3793
+
3794
+ // src/utils/index.ts
3795
+ var sleep = (ms = 2e3) => new Promise((r) => setTimeout(r, ms));
3796
+ var CliError = class extends Error {
3797
+ };
3798
+
3799
+ // src/features/analysis/index.ts
3800
+ import chalk4 from "chalk";
3801
+ import Configstore from "configstore";
3802
+ import Debug12 from "debug";
3803
+ import extract from "extract-zip";
3804
+ import fetch4 from "node-fetch";
3805
+ import open2 from "open";
3806
+ import semver from "semver";
3807
+ import tmp2 from "tmp";
3808
+ import { z as z13 } from "zod";
3809
+
3810
+ // src/features/analysis/add_fix_comments_for_pr/add_fix_comments_for_pr.ts
3811
+ import Debug4 from "debug";
3727
3812
 
3728
3813
  // src/features/analysis/add_fix_comments_for_pr/utils.ts
3729
3814
  import Debug3 from "debug";
3730
3815
  import parseDiff2 from "parse-diff";
3731
- import { z as z10 } from "zod";
3816
+ import { z as z11 } from "zod";
3732
3817
 
3733
3818
  // src/features/analysis/utils/by_key.ts
3734
3819
  function keyBy(array, keyBy2) {
@@ -3960,7 +4045,7 @@ async function getRelevantVulenrabilitiesFromDiff(params) {
3960
4045
  });
3961
4046
  const lineAddedRanges = calculateRanges(fileNumbers);
3962
4047
  const fileFilter = {
3963
- path: z10.string().parse(file.to),
4048
+ path: z11.string().parse(file.to),
3964
4049
  ranges: lineAddedRanges.map(([startLine, endLine]) => ({
3965
4050
  endLine,
3966
4051
  startLine
@@ -4267,30 +4352,30 @@ function subscribe(query, variables, callback, wsClientOptions) {
4267
4352
  }
4268
4353
 
4269
4354
  // src/features/analysis/graphql/types.ts
4270
- import { z as z11 } from "zod";
4271
- var VulnerabilityReportIssueCodeNodeZ = z11.object({
4272
- vulnerabilityReportIssueId: z11.string(),
4273
- path: z11.string(),
4274
- startLine: z11.number(),
4275
- vulnerabilityReportIssue: z11.object({
4276
- fixId: z11.string()
4355
+ import { z as z12 } from "zod";
4356
+ var VulnerabilityReportIssueCodeNodeZ = z12.object({
4357
+ vulnerabilityReportIssueId: z12.string(),
4358
+ path: z12.string(),
4359
+ startLine: z12.number(),
4360
+ vulnerabilityReportIssue: z12.object({
4361
+ fixId: z12.string()
4277
4362
  })
4278
4363
  });
4279
- var GetVulByNodesMetadataZ = z11.object({
4280
- vulnerabilityReportIssueCodeNodes: z11.array(VulnerabilityReportIssueCodeNodeZ),
4281
- nonFixablePrVuls: z11.object({
4282
- aggregate: z11.object({
4283
- count: z11.number()
4364
+ var GetVulByNodesMetadataZ = z12.object({
4365
+ vulnerabilityReportIssueCodeNodes: z12.array(VulnerabilityReportIssueCodeNodeZ),
4366
+ nonFixablePrVuls: z12.object({
4367
+ aggregate: z12.object({
4368
+ count: z12.number()
4284
4369
  })
4285
4370
  }),
4286
- fixablePrVuls: z11.object({
4287
- aggregate: z11.object({
4288
- count: z11.number()
4371
+ fixablePrVuls: z12.object({
4372
+ aggregate: z12.object({
4373
+ count: z12.number()
4289
4374
  })
4290
4375
  }),
4291
- totalScanVulnerabilities: z11.object({
4292
- aggregate: z11.object({
4293
- count: z11.number()
4376
+ totalScanVulnerabilities: z12.object({
4377
+ aggregate: z12.object({
4378
+ count: z12.number()
4294
4379
  })
4295
4380
  })
4296
4381
  });
@@ -4563,6 +4648,12 @@ var GQLClient = class {
4563
4648
  });
4564
4649
  return res;
4565
4650
  }
4651
+ async validateRepoUrl(args) {
4652
+ return this._clientSdk.validateRepoUrl(args);
4653
+ }
4654
+ async getReferenceData(args) {
4655
+ return this._clientSdk.gitReference(args);
4656
+ }
4566
4657
  };
4567
4658
 
4568
4659
  // src/features/analysis/pack.ts
@@ -5063,6 +5154,70 @@ function _getUrlForScmType({
5063
5154
  };
5064
5155
  }
5065
5156
  }
5157
+ async function getScmTokenInfo(params) {
5158
+ const { gqlClient, repo } = params;
5159
+ const userInfo = await gqlClient.getUserInfo();
5160
+ if (!userInfo) {
5161
+ throw new Error("userInfo is null");
5162
+ }
5163
+ const scmConfigs = getFromArraySafe(userInfo.scmConfigs);
5164
+ return getScmConfig({
5165
+ url: repo,
5166
+ scmConfigs,
5167
+ includeOrgTokens: false
5168
+ });
5169
+ }
5170
+ async function getReport(params, { skipPrompts }) {
5171
+ const {
5172
+ scanner,
5173
+ repoUrl,
5174
+ gqlClient,
5175
+ sha,
5176
+ dirname,
5177
+ reference,
5178
+ cxProjectName,
5179
+ ci
5180
+ } = params;
5181
+ const tokenInfo = await getScmTokenInfo({ gqlClient, repo: repoUrl });
5182
+ const scm = await SCMLib.init(
5183
+ {
5184
+ url: repoUrl,
5185
+ accessToken: tokenInfo.accessToken,
5186
+ scmOrg: tokenInfo.scmOrg,
5187
+ scmType: tokenInfo.scmLibType
5188
+ },
5189
+ { propagateExceptions: true }
5190
+ );
5191
+ const downloadUrl = await scm.getDownloadUrl(sha);
5192
+ const repositoryRoot = await downloadRepo({
5193
+ repoUrl,
5194
+ dirname,
5195
+ ci,
5196
+ authHeaders: scm.getAuthHeaders(),
5197
+ downloadUrl
5198
+ });
5199
+ const reportPath = path6.join(dirname, "report.json");
5200
+ switch (scanner) {
5201
+ case "snyk":
5202
+ await getSnykReport(reportPath, repositoryRoot, { skipPrompts });
5203
+ break;
5204
+ case "checkmarx":
5205
+ if (!cxProjectName) {
5206
+ throw new Error("cxProjectName is required for checkmarx scanner");
5207
+ }
5208
+ await getCheckmarxReport(
5209
+ {
5210
+ reportPath,
5211
+ repositoryRoot,
5212
+ branch: reference,
5213
+ projectName: cxProjectName
5214
+ },
5215
+ { skipPrompts }
5216
+ );
5217
+ break;
5218
+ }
5219
+ return reportPath;
5220
+ }
5066
5221
  async function _scan(params, { skipPrompts = false } = {}) {
5067
5222
  const {
5068
5223
  dirname,
@@ -5106,68 +5261,64 @@ async function _scan(params, { skipPrompts = false } = {}) {
5106
5261
  if (!repo) {
5107
5262
  throw new Error("repo is required in case srcPath is not provided");
5108
5263
  }
5109
- const userInfo = await gqlClient.getUserInfo();
5110
- if (!userInfo) {
5111
- throw new Error("userInfo is null");
5112
- }
5113
- const scmConfigs = getFromArraySafe(userInfo.scmConfigs);
5114
- const tokenInfo = getScmConfig({
5115
- url: repo,
5116
- scmConfigs,
5117
- includeOrgTokens: false
5118
- });
5119
- const isRepoAvailable = await scmCanReachRepo({
5120
- repoUrl: repo,
5121
- accessToken: tokenInfo.accessToken,
5122
- scmOrg: tokenInfo.scmOrg,
5123
- scmType: getScmTypeFromScmLibType(tokenInfo.scmLibType)
5124
- });
5264
+ const tokenInfo = await getScmTokenInfo({ gqlClient, repo });
5265
+ const validateRes = await gqlClient.validateRepoUrl({ repoUrl: repo });
5266
+ const isRepoAvailable = validateRes.validateRepoUrl?.__typename === "RepoValidationSuccess";
5125
5267
  const cloudScmLibType = getCloudScmLibTypeFromUrl(repo);
5126
5268
  const { authUrl: scmAuthUrl } = _getUrlForScmType({
5127
5269
  scmLibType: cloudScmLibType
5128
5270
  });
5129
- let myToken = tokenInfo.accessToken;
5130
5271
  if (!isRepoAvailable) {
5131
5272
  if (ci || !cloudScmLibType || !scmAuthUrl) {
5132
5273
  const errorMessage = scmAuthUrl ? `Cannot access repo ${repo}` : `Cannot access repo ${repo} with the provided token, please visit ${scmAuthUrl} to refresh your source control management system token`;
5133
5274
  throw new Error(errorMessage);
5134
5275
  }
5135
5276
  if (cloudScmLibType && scmAuthUrl) {
5136
- myToken = await handleScmIntegration(tokenInfo.accessToken, scmAuthUrl, repo) || "";
5137
- const isRepoAvailable2 = await scmCanReachRepo({
5138
- repoUrl: repo,
5139
- accessToken: myToken,
5140
- scmOrg: tokenInfo.scmOrg,
5141
- scmType: getScmTypeFromScmLibType(tokenInfo.scmLibType)
5277
+ await handleScmIntegration(tokenInfo.accessToken, scmAuthUrl, repo);
5278
+ const repoValidationResponse = await gqlClient.validateRepoUrl({
5279
+ repoUrl: repo
5142
5280
  });
5281
+ const isRepoAvailable2 = repoValidationResponse.validateRepoUrl?.__typename === "RepoValidationSuccess";
5143
5282
  if (!isRepoAvailable2) {
5144
5283
  throw new Error(
5145
- `Cannot access repo ${repo} with the provided credentials`
5284
+ `Cannot access repo ${repo} with the provided credentials: ${repoValidationResponse.validateRepoUrl?.__typename}`
5146
5285
  );
5147
5286
  }
5148
5287
  }
5149
5288
  }
5150
- const scm = await SCMLib.init({
5151
- url: repo,
5152
- accessToken: myToken,
5153
- scmOrg: tokenInfo.scmOrg,
5154
- scmType: tokenInfo.scmLibType
5289
+ const revalidateRes = await gqlClient.validateRepoUrl({ repoUrl: repo });
5290
+ if (revalidateRes.validateRepoUrl?.__typename !== "RepoValidationSuccess") {
5291
+ throw new Error(
5292
+ `could not reach repo ${repo}: ${revalidateRes.validateRepoUrl?.__typename}`
5293
+ );
5294
+ }
5295
+ const reference = ref ?? revalidateRes.validateRepoUrl.defaultBranch;
5296
+ const getReferenceDataRes = await gqlClient.getReferenceData({
5297
+ reference,
5298
+ repoUrl: repo
5155
5299
  });
5156
- const reference = ref ?? await scm.getRepoDefaultBranch();
5157
- const { sha } = await scm.getReferenceData(reference);
5158
- const downloadUrl = await scm.getDownloadUrl(sha);
5159
- debug11("org id %s", organizationId);
5300
+ if (getReferenceDataRes.gitReference?.__typename !== "GitReferenceData") {
5301
+ throw new Error(
5302
+ `Could not get reference data for ${reference}: ${getReferenceDataRes.gitReference?.__typename}`
5303
+ );
5304
+ }
5305
+ const { sha } = getReferenceDataRes.gitReference;
5160
5306
  debug11("project id %s", projectId);
5161
5307
  debug11("default branch %s", reference);
5162
- const repositoryRoot = await downloadRepo({
5163
- repoUrl: repo,
5164
- dirname,
5165
- ci,
5166
- authHeaders: scm.getAuthHeaders(),
5167
- downloadUrl
5168
- });
5169
5308
  if (command === "scan") {
5170
- reportPath = await getReport(SupportedScannersZ.parse(scanner));
5309
+ reportPath = await getReport(
5310
+ {
5311
+ scanner: SupportedScannersZ.parse(scanner),
5312
+ repoUrl: repo,
5313
+ sha,
5314
+ gqlClient,
5315
+ cxProjectName,
5316
+ dirname,
5317
+ reference,
5318
+ ci
5319
+ },
5320
+ { skipPrompts }
5321
+ );
5171
5322
  }
5172
5323
  if (!reportPath) {
5173
5324
  throw new Error("reportPath is null");
@@ -5191,7 +5342,7 @@ async function _scan(params, { skipPrompts = false } = {}) {
5191
5342
  spinner: mobbSpinner,
5192
5343
  submitVulnerabilityReportVariables: {
5193
5344
  fixReportId: reportUploadInfo.fixReportId,
5194
- repoUrl: z12.string().parse(repo),
5345
+ repoUrl: z13.string().parse(repo),
5195
5346
  reference,
5196
5347
  projectId,
5197
5348
  vulnerabilityReportFileName: "report.json",
@@ -5210,29 +5361,6 @@ async function _scan(params, { skipPrompts = false } = {}) {
5210
5361
  });
5211
5362
  await askToOpenAnalysis();
5212
5363
  return reportUploadInfo.fixReportId;
5213
- async function getReport(scanner2) {
5214
- const reportPath2 = path6.join(dirname, "report.json");
5215
- switch (scanner2) {
5216
- case "snyk":
5217
- await getSnykReport(reportPath2, repositoryRoot, { skipPrompts });
5218
- break;
5219
- case "checkmarx":
5220
- if (!cxProjectName) {
5221
- throw new Error("cxProjectName is required for checkmarx scanner");
5222
- }
5223
- await getCheckmarxReport(
5224
- {
5225
- reportPath: reportPath2,
5226
- repositoryRoot,
5227
- branch: reference,
5228
- projectName: cxProjectName
5229
- },
5230
- { skipPrompts }
5231
- );
5232
- break;
5233
- }
5234
- return reportPath2;
5235
- }
5236
5364
  async function askToOpenAnalysis() {
5237
5365
  if (!repoUploadInfo || !reportUploadInfo) {
5238
5366
  throw new Error("uploadS3BucketInfo is null");
@@ -5329,14 +5457,14 @@ async function _scan(params, { skipPrompts = false } = {}) {
5329
5457
  );
5330
5458
  await open2(scmAuthUrl2);
5331
5459
  for (let i = 0; i < LOGIN_MAX_WAIT / LOGIN_CHECK_DELAY; i++) {
5332
- const userInfo2 = await gqlClient.getUserInfo();
5333
- if (!userInfo2) {
5460
+ const userInfo = await gqlClient.getUserInfo();
5461
+ if (!userInfo) {
5334
5462
  throw new CliError2("User info not found");
5335
5463
  }
5336
- const scmConfigs2 = getFromArraySafe(userInfo2.scmConfigs);
5464
+ const scmConfigs = getFromArraySafe(userInfo.scmConfigs);
5337
5465
  const tokenInfo2 = getScmConfig({
5338
5466
  url: repoUrl,
5339
- scmConfigs: scmConfigs2,
5467
+ scmConfigs,
5340
5468
  includeOrgTokens: false
5341
5469
  });
5342
5470
  if (tokenInfo2.accessToken && tokenInfo2.accessToken !== oldToken) {
@@ -5443,16 +5571,21 @@ async function _scan(params, { skipPrompts = false } = {}) {
5443
5571
  }
5444
5572
  });
5445
5573
  if (command === "review") {
5446
- const params2 = z12.object({
5447
- repo: z12.string().url(),
5448
- githubActionToken: z12.string()
5574
+ const params2 = z13.object({
5575
+ repo: z13.string().url(),
5576
+ githubActionToken: z13.string()
5449
5577
  }).parse({ repo, githubActionToken });
5450
- const scm2 = await SCMLib.init({
5451
- url: params2.repo,
5452
- accessToken: params2.githubActionToken,
5453
- scmOrg: "",
5454
- scmType: "GITHUB" /* GITHUB */
5455
- });
5578
+ const scm = await SCMLib.init(
5579
+ {
5580
+ url: params2.repo,
5581
+ accessToken: params2.githubActionToken,
5582
+ scmOrg: "",
5583
+ scmType: "GITHUB" /* GITHUB */
5584
+ },
5585
+ {
5586
+ propagateExceptions: true
5587
+ }
5588
+ );
5456
5589
  await gqlClient.subscribeToAnalysis({
5457
5590
  subscribeToAnalysisParams: {
5458
5591
  analysisId: reportUploadInfo.fixReportId
@@ -5461,8 +5594,8 @@ async function _scan(params, { skipPrompts = false } = {}) {
5461
5594
  return addFixCommentsForPr({
5462
5595
  analysisId,
5463
5596
  gqlClient,
5464
- scm: scm2,
5465
- scanner: z12.nativeEnum(SCANNERS).parse(scanner)
5597
+ scm,
5598
+ scanner: z13.nativeEnum(SCANNERS).parse(scanner)
5466
5599
  });
5467
5600
  },
5468
5601
  callbackStates: ["Finished" /* Finished */]
@@ -5648,12 +5781,12 @@ var commitHashOption = {
5648
5781
  };
5649
5782
  var scmTypeOption = {
5650
5783
  demandOption: true,
5651
- describe: chalk5.bold("SCM type (GitHub, GitLab, Ado, Bitbucket)"),
5652
- type: "string"
5784
+ describe: chalk5.bold("SCM type"),
5785
+ choices: Object.values(ScmType)
5653
5786
  };
5654
5787
  var urlOption = {
5655
5788
  describe: chalk5.bold(
5656
- "URL of the repository (used in GitHub, GitLab, Azure DevOps, Bitbucket)"
5789
+ `URL of the repository (used in ${Object.values(ScmType).join(", ")})`
5657
5790
  ),
5658
5791
  type: "string",
5659
5792
  demandOption: true
@@ -5675,7 +5808,7 @@ var scmTokenOption = {
5675
5808
  // src/args/validation.ts
5676
5809
  import chalk6 from "chalk";
5677
5810
  import path8 from "path";
5678
- import { z as z13 } from "zod";
5811
+ import { z as z14 } from "zod";
5679
5812
  function throwRepoUrlErrorMessage({
5680
5813
  error,
5681
5814
  repoUrl,
@@ -5692,13 +5825,13 @@ Example:
5692
5825
  )}`;
5693
5826
  throw new CliError(formattedErrorMessage);
5694
5827
  }
5695
- var UrlZ = z13.string({
5696
- invalid_type_error: "is not a valid GitHub / GitLab / ADO URL"
5828
+ var UrlZ = z14.string({
5829
+ invalid_type_error: `is not a valid ${Object.values(ScmType).join("/ ")} URL`
5697
5830
  }).refine((data) => !!sanityRepoURL(data), {
5698
- message: "is not a valid GitHub / GitLab / ADO URL"
5831
+ message: `is not a valid ${Object.values(ScmType).join(" / ")} URL`
5699
5832
  });
5700
5833
  function validateOrganizationId(organizationId) {
5701
- const orgIdValidation = z13.string().uuid().nullish().safeParse(organizationId);
5834
+ const orgIdValidation = z14.string().uuid().nullish().safeParse(organizationId);
5702
5835
  if (!orgIdValidation.success) {
5703
5836
  throw new CliError(`organizationId: ${organizationId} is not a valid UUID`);
5704
5837
  }
@@ -5855,20 +5988,15 @@ async function scanHandler(args) {
5855
5988
  }
5856
5989
 
5857
5990
  // src/args/commands/token.ts
5858
- import { z as z14 } from "zod";
5859
5991
  function addScmTokenBuilder(args) {
5860
5992
  return args.option("scm-type", scmTypeOption).option("url", urlOption).option("token", scmTokenOption).option("organization", scmOrgOption).option("refresh-token", scmRefreshTokenOption).option("api-key", apiKeyOption).example(
5861
5993
  "$0 add-scm-token --scm-type Ado --url https://dev.azure.com/adoorg/test/_git/repo --token abcdef0123456 --organization myOrg",
5862
- "Add your SCM (Github, Gitlab, Azure DevOps) token to Mobb to enable automated fixes."
5994
+ `Add your SCM (${Object.values(scmFriendlyText).join(", ")}) token to Mobb to enable automated fixes.`
5863
5995
  ).help().demandOption(["url", "token"]);
5864
5996
  }
5865
- function validateAddScmTokenOptions(argv) {
5866
- if (!z14.nativeEnum(ScmType).safeParse(argv.scmType).success) {
5867
- throw new CliError(
5868
- "\nError: --scm-type must reference a valid SCM type (GitHub, GitLab, Ado, Bitbutcket)"
5869
- );
5870
- }
5871
- Object.values(scmValidationMap).forEach((validate) => validate(argv));
5997
+ async function validateAddScmTokenOptions(argv) {
5998
+ const scmType = argv["scm-type"];
5999
+ scmValidationMap[scmType];
5872
6000
  }
5873
6001
  var scmValidationMap = {
5874
6002
  ["GitHub" /* GitHub */]: () => {
@@ -5883,15 +6011,14 @@ var scmValidationMap = {
5883
6011
  }
5884
6012
  };
5885
6013
  function validateAdo(argv) {
5886
- const urlObj = new URL(argv.url);
5887
- if ((urlObj.hostname.toLowerCase() === scmCloudHostname.Ado || urlObj.hostname.toLowerCase().endsWith(".visualstudio.com")) && !argv.organization) {
6014
+ if (!argv.organization) {
5888
6015
  throw new CliError(
5889
6016
  "\nError: --organization flag is required for Azure DevOps"
5890
6017
  );
5891
6018
  }
5892
6019
  }
5893
6020
  async function addScmTokenHandler(args) {
5894
- validateAddScmTokenOptions(args);
6021
+ await validateAddScmTokenOptions(args);
5895
6022
  await addScmToken(args);
5896
6023
  }
5897
6024