@trustify-da/trustify-da-javascript-client 0.3.0-ea.7ed8d8c → 0.3.0-ea.7ee4047

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 (98) hide show
  1. package/README.md +388 -20
  2. package/dist/package.json +39 -26
  3. package/dist/src/analysis.d.ts +58 -20
  4. package/dist/src/analysis.js +134 -78
  5. package/dist/src/batch_opts.d.ts +24 -0
  6. package/dist/src/batch_opts.js +35 -0
  7. package/dist/src/cli.js +427 -12
  8. package/dist/src/config.d.ts +120 -0
  9. package/dist/src/config.js +260 -0
  10. package/dist/src/cyclone_dx_sbom.d.ts +30 -2
  11. package/dist/src/cyclone_dx_sbom.js +95 -9
  12. package/dist/src/index.d.ts +154 -16
  13. package/dist/src/index.js +372 -36
  14. package/dist/src/license/index.d.ts +28 -0
  15. package/dist/src/license/index.js +106 -0
  16. package/dist/src/license/license_utils.d.ts +40 -0
  17. package/dist/src/license/license_utils.js +137 -0
  18. package/dist/src/license/licenses_api.d.ts +34 -0
  19. package/dist/src/license/licenses_api.js +98 -0
  20. package/dist/src/license/project_license.d.ts +20 -0
  21. package/dist/src/license/project_license.js +62 -0
  22. package/dist/src/oci_image/images.d.ts +1 -1
  23. package/dist/src/oci_image/images.js +15 -1
  24. package/dist/src/oci_image/utils.d.ts +5 -5
  25. package/dist/src/oci_image/utils.js +11 -2
  26. package/dist/src/package_version.d.ts +8 -0
  27. package/dist/src/package_version.js +31 -0
  28. package/dist/src/provider.d.ts +16 -3
  29. package/dist/src/provider.js +33 -5
  30. package/dist/src/providers/base_java.d.ts +67 -12
  31. package/dist/src/providers/base_java.js +82 -61
  32. package/dist/src/providers/base_javascript.d.ts +99 -12
  33. package/dist/src/providers/base_javascript.js +244 -28
  34. package/dist/src/providers/base_pyproject.d.ts +158 -0
  35. package/dist/src/providers/base_pyproject.js +322 -0
  36. package/dist/src/providers/containerfile_parser.d.ts +5 -0
  37. package/dist/src/providers/containerfile_parser.js +20 -0
  38. package/dist/src/providers/golang_gomodules.d.ts +30 -13
  39. package/dist/src/providers/golang_gomodules.js +219 -122
  40. package/dist/src/providers/gomod_parser.d.ts +4 -0
  41. package/dist/src/providers/gomod_parser.js +16 -0
  42. package/dist/src/providers/java_gradle.d.ts +73 -0
  43. package/dist/src/providers/java_gradle.js +331 -23
  44. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  45. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  46. package/dist/src/providers/java_maven.d.ts +44 -9
  47. package/dist/src/providers/java_maven.js +299 -13
  48. package/dist/src/providers/javascript_bun.d.ts +22 -0
  49. package/dist/src/providers/javascript_bun.js +141 -0
  50. package/dist/src/providers/javascript_npm.d.ts +19 -0
  51. package/dist/src/providers/javascript_npm.js +61 -1
  52. package/dist/src/providers/javascript_pnpm.d.ts +14 -1
  53. package/dist/src/providers/javascript_pnpm.js +55 -5
  54. package/dist/src/providers/javascript_yarn.d.ts +12 -0
  55. package/dist/src/providers/javascript_yarn.js +75 -2
  56. package/dist/src/providers/manifest.d.ts +2 -0
  57. package/dist/src/providers/manifest.js +28 -7
  58. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  59. package/dist/src/providers/marker_evaluator.js +191 -0
  60. package/dist/src/providers/oci_dockerfile.d.ts +51 -0
  61. package/dist/src/providers/oci_dockerfile.js +177 -0
  62. package/dist/src/providers/processors/yarn_berry_processor.d.ts +6 -2
  63. package/dist/src/providers/processors/yarn_berry_processor.js +91 -7
  64. package/dist/src/providers/processors/yarn_classic_processor.d.ts +6 -2
  65. package/dist/src/providers/processors/yarn_classic_processor.js +8 -6
  66. package/dist/src/providers/python_controller.d.ts +5 -1
  67. package/dist/src/providers/python_controller.js +69 -8
  68. package/dist/src/providers/python_pip.d.ts +12 -0
  69. package/dist/src/providers/python_pip.js +18 -8
  70. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  71. package/dist/src/providers/python_pip_pyproject.js +146 -0
  72. package/dist/src/providers/python_poetry.d.ts +98 -0
  73. package/dist/src/providers/python_poetry.js +286 -0
  74. package/dist/src/providers/python_uv.d.ts +46 -0
  75. package/dist/src/providers/python_uv.js +275 -0
  76. package/dist/src/providers/requirements_parser.js +6 -9
  77. package/dist/src/providers/rust_cargo.d.ts +56 -0
  78. package/dist/src/providers/rust_cargo.js +682 -0
  79. package/dist/src/providers/tree-sitter-containerfile.wasm +0 -0
  80. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  81. package/dist/src/providers/tree-sitter-requirements.wasm +0 -0
  82. package/dist/src/remediate.d.ts +107 -0
  83. package/dist/src/remediate.js +244 -0
  84. package/dist/src/remediation.d.ts +81 -0
  85. package/dist/src/remediation.js +475 -0
  86. package/dist/src/remediation_report.d.ts +23 -0
  87. package/dist/src/remediation_report.js +180 -0
  88. package/dist/src/sbom.d.ts +28 -2
  89. package/dist/src/sbom.js +26 -4
  90. package/dist/src/tools.d.ts +53 -11
  91. package/dist/src/tools.js +147 -13
  92. package/dist/src/updaters/maven_updater.d.ts +58 -0
  93. package/dist/src/updaters/maven_updater.js +345 -0
  94. package/dist/src/updaters/toml_updater.d.ts +62 -0
  95. package/dist/src/updaters/toml_updater.js +276 -0
  96. package/dist/src/workspace.d.ts +71 -0
  97. package/dist/src/workspace.js +257 -0
  98. package/package.json +40 -27
package/dist/src/index.js CHANGED
@@ -1,16 +1,29 @@
1
+ import fs from 'node:fs';
1
2
  import path from "node:path";
2
3
  import { EOL } from "os";
3
- import { availableProviders, match } from './provider.js';
4
+ import pLimit from 'p-limit';
4
5
  import analysis from './analysis.js';
5
- import fs from 'node:fs';
6
+ import { resolveBatchMetadata, resolveContinueOnError } from './batch_opts.js';
7
+ import { getPackageVersion } from './package_version.js';
8
+ import { availableProviders, match } from './provider.js';
9
+ import { discoverGoWorkspaceModules } from './providers/golang_gomodules.js';
10
+ import { discoverGradleSubprojects } from './providers/java_gradle.js';
11
+ import { discoverMavenModules } from './providers/java_maven.js';
12
+ import { discoverUvWorkspaceMembers } from './providers/python_uv.js';
6
13
  import { getCustom } from "./tools.js";
7
- import.meta.dirname;
8
- import * as url from 'url';
14
+ import { discoverWorkspaceCrates, discoverWorkspacePackages, filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, validatePackageJson, } from './workspace.js';
9
15
  export { parseImageRef } from "./oci_image/utils.js";
10
16
  export { ImageRef } from "./oci_image/images.js";
11
- export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken };
17
+ export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
18
+ export { extractRemediations, maxSeverity } from "./remediation.js";
19
+ export { generateReport, generateDeduplicationKey } from './remediation_report.js';
20
+ export { loadConfig, mergeConfig, resolveConfig, CONFIG_FILENAMES } from './config.js';
21
+ export { runRemediation, findManifests } from './remediate.js';
22
+ export default { componentAnalysis, stackAnalysis, stackAnalysisBatch, imageAnalysis, validateToken, generateSbom };
23
+ export { discoverMavenModules, discoverGradleSubprojects, discoverGoWorkspaceModules, discoverUvWorkspaceMembers, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
12
24
  /**
13
25
  * @typedef {{
26
+ * TRUSTIFY_DA_CARGO_PATH?: string | undefined,
14
27
  * TRUSTIFY_DA_DOCKER_PATH?: string | undefined,
15
28
  * TRUSTIFY_DA_GO_MVS_LOGIC_ENABLED?: string | undefined,
16
29
  * TRUSTIFY_DA_GO_PATH?: string | undefined,
@@ -29,19 +42,44 @@ export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken
29
42
  * TRUSTIFY_DA_PYTHON_PATH?: string | undefined,
30
43
  * TRUSTIFY_DA_PYTHON_VIRTUAL_ENV?: string | undefined,
31
44
  * TRUSTIFY_DA_PYTHON3_PATH?: string | undefined,
32
- * TRUSTIFY_DA_RECOMMENDATIONS_ENABLED?: string | undefined,
45
+ * TRUSTIFY_DA_PROVIDERS?: string | undefined,
46
+ * TRUSTIFY_DA_RECOMMEND?: string | undefined,
47
+ * TRUSTIFY_DA_SOURCES?: string | undefined,
33
48
  * TRUSTIFY_DA_SKOPEO_CONFIG_PATH?: string | undefined,
34
49
  * TRUSTIFY_DA_SKOPEO_PATH?: string | undefined,
35
50
  * TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined,
36
51
  * TRUSTIFY_DA_SYFT_PATH?: string | undefined,
37
52
  * TRUSTIFY_DA_YARN_PATH?: string | undefined,
53
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
54
+ * TRUSTIFY_DA_LICENSE_CHECK?: string | undefined,
55
+ * licenseCheck?: boolean | undefined,
38
56
  * MATCH_MANIFEST_VERSIONS?: string | undefined,
39
57
  * TRUSTIFY_DA_SOURCE?: string | undefined,
40
58
  * TRUSTIFY_DA_TOKEN?: string | undefined,
41
59
  * TRUSTIFY_DA_TELEMETRY_ID?: string | undefined,
42
- * [key: string]: string | undefined,
60
+ * batchConcurrency?: number | undefined,
61
+ * TRUSTIFY_DA_BATCH_CONCURRENCY?: string | undefined,
62
+ * workspaceDiscoveryIgnore?: string[] | undefined,
63
+ * TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string | undefined,
64
+ * continueOnError?: boolean | undefined,
65
+ * TRUSTIFY_DA_CONTINUE_ON_ERROR?: string | undefined,
66
+ * batchMetadata?: boolean | undefined,
67
+ * TRUSTIFY_DA_BATCH_METADATA?: string | undefined,
68
+ * TRUSTIFY_DA_UV_PATH?: string | undefined,
69
+ * TRUSTIFY_DA_POETRY_PATH?: string | undefined,
70
+ * [key: string]: string | number | boolean | string[] | undefined,
43
71
  * }} Options
44
72
  */
73
+ /**
74
+ * @typedef {{
75
+ * workspaceRoot: string,
76
+ * ecosystem: 'javascript' | 'cargo' | 'pyproject' | 'unknown',
77
+ * total: number,
78
+ * successful: number,
79
+ * failed: number,
80
+ * errors: Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>
81
+ * }} BatchAnalysisMetadata
82
+ */
45
83
  /**
46
84
  * Logs messages to the console if the TRUSTIFY_DA_DEBUG environment variable is set to "true".
47
85
  * @param {string} alongsideText - The text to prepend to the log message.
@@ -58,29 +96,11 @@ function logOptionsAndEnvironmentsVariables(alongsideText, valueToBePrinted) {
58
96
  * @private
59
97
  */
60
98
  function readAndPrintVersionFromPackageJson() {
61
- let dirName;
62
- // new ESM way in nodeJS ( since node version 22 ) to bring module directory.
63
- dirName = import.meta.dirname;
64
- // old ESM way in nodeJS ( before node versions 22.00 to bring module directory)
65
- if (!dirName) {
66
- dirName = url.fileURLToPath(new URL('.', import.meta.url));
67
- }
68
- try {
69
- if (__dirname) {
70
- dirName = __dirname;
71
- }
72
- }
73
- catch (e) {
74
- console.log("__dirname is not defined, continue with fileUrlPath");
75
- }
76
- let packageJson = JSON.parse(fs.readFileSync(path.join(dirName, "..", "package.json")).toString());
77
- logOptionsAndEnvironmentsVariables("trustify-da-javascript-client analysis started, version: ", packageJson.version);
99
+ logOptionsAndEnvironmentsVariables("trustify-da-javascript-client analysis started, version: ", getPackageVersion());
78
100
  }
79
101
  /**
80
- * This function is used to determine the Trustify DA backend URL.
81
- * The TRUSTIFY_DA_BACKEND_URL is evaluated in the following order and selected when it finds it first:
82
- * 1. Environment Variable
83
- * 2. (key,value) from opts object
102
+ * Selects the Trustify DA backend URL from opts.TRUSTIFY_DA_BACKEND_URL, then environment
103
+ * variable TRUSTIFY_DA_BACKEND_URL. Options take precedence over environment variables.
84
104
  * If TRUSTIFY_DA_BACKEND_URL is not set, the function will throw an error.
85
105
  * @param {{TRUSTIFY_DA_DEBUG?: string | undefined; TRUSTIFY_DA_BACKEND_URL?: string | undefined}} [opts={}]
86
106
  * @return {string} - The selected Trustify DA backend URL
@@ -111,7 +131,7 @@ export function selectTrustifyDABackend(opts = {}) {
111
131
  * @param {string} manifest
112
132
  * @param {false} html
113
133
  * @param {Options} [opts={}]
114
- * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
134
+ * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>}
115
135
  * @throws {Error}
116
136
  */
117
137
  /**
@@ -120,29 +140,31 @@ export function selectTrustifyDABackend(opts = {}) {
120
140
  * @param {string} manifest - path for the manifest
121
141
  * @param {boolean} [html=false] - true will return a html string, false will return AnalysisReport object.
122
142
  * @param {Options} [opts={}] - optional various options to pass along the application
123
- * @returns {Promise<string|import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
143
+ * @returns {Promise<string|import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>}
124
144
  * @throws {Error} if manifest inaccessible, no matching provider, failed to get create content,
125
145
  * or backend request failed
126
146
  */
127
147
  async function stackAnalysis(manifest, html = false, opts = {}) {
128
148
  const theUrl = selectTrustifyDABackend(opts);
129
149
  fs.accessSync(manifest, fs.constants.R_OK); // throws error if file unreadable
130
- let provider = match(manifest, availableProviders); // throws error if no matching provider
150
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
131
151
  return await analysis.requestStack(provider, manifest, theUrl, html, opts); // throws error request sending failed
132
152
  }
133
153
  /**
134
154
  * Get component analysis report for a manifest content.
135
155
  * @param {string} manifest - path to the manifest
136
156
  * @param {Options} [opts={}] - optional various options to pass along the application
137
- * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
157
+ * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>}
138
158
  * @throws {Error} if no matching provider, failed to get create content, or backend request failed
139
159
  */
140
160
  async function componentAnalysis(manifest, opts = {}) {
141
161
  const theUrl = selectTrustifyDABackend(opts);
142
162
  fs.accessSync(manifest, fs.constants.R_OK);
143
163
  opts["manifest-type"] = path.basename(manifest);
144
- let provider = match(manifest, availableProviders); // throws error if no matching provider
145
- return await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
164
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
165
+ const result = await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
166
+ result.packageManager = provider.packageManagerName();
167
+ return result;
146
168
  }
147
169
  /**
148
170
  * @overload
@@ -157,7 +179,7 @@ async function componentAnalysis(manifest, opts = {}) {
157
179
  * @param {Array<string>} imageRefs
158
180
  * @param {false} html
159
181
  * @param {Options} [opts={}]
160
- * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
182
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>>}
161
183
  * @throws {Error}
162
184
  */
163
185
  /**
@@ -166,7 +188,7 @@ async function componentAnalysis(manifest, opts = {}) {
166
188
  * @param {Array<string>} imageRefs - OCI image references
167
189
  * @param {boolean} [html=false] - true will return a html string, false will return AnalysisReport
168
190
  * @param {Options} [opts={}] - optional various options to pass along the application
169
- * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
191
+ * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>>}
170
192
  * @throws {Error} if manifest inaccessible, no matching provider, failed to get create content,
171
193
  * or backend request failed
172
194
  */
@@ -174,6 +196,320 @@ async function imageAnalysis(imageRefs, html = false, opts = {}) {
174
196
  const theUrl = selectTrustifyDABackend(opts);
175
197
  return await analysis.requestImages(imageRefs, theUrl, html, opts);
176
198
  }
199
+ /**
200
+ * Max concurrent SBOM generations for batch workspace analysis. Options override environment;
201
+ * environment overrides the default of 10.
202
+ * @param {Options} opts
203
+ * @returns {number}
204
+ * @private
205
+ */
206
+ function resolveBatchConcurrency(opts) {
207
+ const fromEnv = getCustom('TRUSTIFY_DA_BATCH_CONCURRENCY', null, opts);
208
+ const raw = opts.batchConcurrency ?? fromEnv ?? '10';
209
+ const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10);
210
+ if (!Number.isFinite(n) || n < 1) {
211
+ return 10;
212
+ }
213
+ return Math.min(256, n);
214
+ }
215
+ /**
216
+ * @param {string} root
217
+ * @param {'javascript' | 'cargo' | 'unknown'} ecosystem
218
+ * @param {number} totalSbomAttempts
219
+ * @param {number} successfulSbomCount
220
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} errors
221
+ * @returns {BatchAnalysisMetadata}
222
+ * @private
223
+ */
224
+ function buildBatchAnalysisMetadata(root, ecosystem, totalSbomAttempts, successfulSbomCount, errors) {
225
+ return {
226
+ workspaceRoot: root,
227
+ ecosystem,
228
+ total: totalSbomAttempts,
229
+ successful: successfulSbomCount,
230
+ failed: errors.length,
231
+ errors: [...errors],
232
+ };
233
+ }
234
+ /**
235
+ * Generate a CycloneDX SBOM from a manifest file. No backend HTTP request is made.
236
+ *
237
+ * @param {string} manifestPath - path to the manifest file (e.g. pom.xml, package.json)
238
+ * @param {Options} [opts={}] - optional options (e.g. workspace dir, tool paths)
239
+ * @returns {Promise<object>} parsed CycloneDX SBOM JSON object
240
+ * @throws {Error} if the manifest is unsupported or SBOM generation fails
241
+ */
242
+ export async function generateSbom(manifestPath, opts = {}) {
243
+ fs.accessSync(manifestPath, fs.constants.R_OK);
244
+ const result = await generateOneSbom(manifestPath, opts);
245
+ if (!result.ok) {
246
+ throw new Error(`Failed to generate SBOM for ${result.manifestPath}: ${result.reason}`);
247
+ }
248
+ return result.sbom;
249
+ }
250
+ /**
251
+ * @typedef {{ ok: true, purl: string, sbom: object } | { ok: false, manifestPath: string, reason: string }} SbomResult
252
+ */
253
+ /**
254
+ * Generate an SBOM for a single manifest, returning a normalized result.
255
+ *
256
+ * @param {string} manifestPath
257
+ * @param {Options} workspaceOpts - opts with `TRUSTIFY_DA_WORKSPACE_DIR` set
258
+ * @returns {Promise<SbomResult>}
259
+ * @private
260
+ */
261
+ async function generateOneSbom(manifestPath, workspaceOpts) {
262
+ const provider = match(manifestPath, availableProviders, workspaceOpts);
263
+ const provided = await provider.provideStack(manifestPath, workspaceOpts);
264
+ const sbom = JSON.parse(provided.content);
265
+ const purl = sbom?.metadata?.component?.purl || sbom?.metadata?.component?.['bom-ref'];
266
+ if (!purl) {
267
+ return { ok: false, manifestPath, reason: 'missing purl in SBOM' };
268
+ }
269
+ return { ok: true, purl, sbom };
270
+ }
271
+ /**
272
+ * Detect the workspace ecosystem and discover manifest paths.
273
+ *
274
+ * @param {string} root - Resolved workspace root
275
+ * @param {Options} opts
276
+ * @returns {Promise<{ ecosystem: 'javascript' | 'cargo' | 'maven' | 'gradle' | 'gomodules' | 'pyproject' | 'unknown', manifestPaths: string[] }>}
277
+ * @private
278
+ */
279
+ async function detectWorkspaceManifests(root, opts) {
280
+ const cargoToml = path.join(root, 'Cargo.toml');
281
+ const cargoLock = path.join(root, 'Cargo.lock');
282
+ const packageJson = path.join(root, 'package.json');
283
+ const pomXml = path.join(root, 'pom.xml');
284
+ if (fs.existsSync(cargoToml) && fs.existsSync(cargoLock)) {
285
+ return { ecosystem: 'cargo', manifestPaths: await discoverWorkspaceCrates(root, opts) };
286
+ }
287
+ if (fs.existsSync(pomXml)) {
288
+ const manifestPaths = await discoverMavenModules(root, opts);
289
+ if (manifestPaths.length > 0) {
290
+ return { ecosystem: 'maven', manifestPaths };
291
+ }
292
+ }
293
+ const hasGradleSettings = fs.existsSync(path.join(root, 'settings.gradle'))
294
+ || fs.existsSync(path.join(root, 'settings.gradle.kts'));
295
+ if (hasGradleSettings) {
296
+ const manifestPaths = await discoverGradleSubprojects(root, opts);
297
+ if (manifestPaths.length > 0) {
298
+ return { ecosystem: 'gradle', manifestPaths };
299
+ }
300
+ }
301
+ if (fs.existsSync(path.join(root, 'go.work'))) {
302
+ const manifestPaths = await discoverGoWorkspaceModules(root, opts);
303
+ if (manifestPaths.length > 0) {
304
+ return { ecosystem: 'gomodules', manifestPaths };
305
+ }
306
+ }
307
+ if (fs.existsSync(path.join(root, 'pyproject.toml')) && fs.existsSync(path.join(root, 'uv.lock'))) {
308
+ const manifestPaths = await discoverUvWorkspaceMembers(root, opts);
309
+ if (manifestPaths.length > 0) {
310
+ return { ecosystem: 'pyproject', manifestPaths };
311
+ }
312
+ }
313
+ const hasJsLock = fs.existsSync(path.join(root, 'bun.lock'))
314
+ || fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
315
+ || fs.existsSync(path.join(root, 'yarn.lock'))
316
+ || fs.existsSync(path.join(root, 'package-lock.json'));
317
+ if (fs.existsSync(packageJson) && hasJsLock) {
318
+ let manifestPaths = await discoverWorkspacePackages(root, opts);
319
+ if (manifestPaths.length === 0) {
320
+ manifestPaths = [packageJson];
321
+ }
322
+ return { ecosystem: 'javascript', manifestPaths };
323
+ }
324
+ return { ecosystem: 'unknown', manifestPaths: [] };
325
+ }
326
+ /**
327
+ * Validate discovered JS package.json manifests, collecting errors.
328
+ *
329
+ * @param {string[]} manifestPaths
330
+ * @param {boolean} continueOnError
331
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
332
+ * @returns {{ validPaths: string[] }}
333
+ * @throws {Error} on first invalid manifest when `continueOnError` is false
334
+ * @private
335
+ */
336
+ function validateJsManifests(manifestPaths, continueOnError, collectedErrors) {
337
+ const validPaths = [];
338
+ for (const p of manifestPaths) {
339
+ const v = validatePackageJson(p);
340
+ if (v.valid) {
341
+ validPaths.push(p);
342
+ }
343
+ else {
344
+ collectedErrors.push({ manifestPath: p, phase: 'validation', reason: v.error });
345
+ console.warn(`Skipping invalid package.json (${v.error}): ${p}`);
346
+ if (!continueOnError) {
347
+ throw new Error(`Invalid package.json (${v.error}): ${p}`);
348
+ }
349
+ }
350
+ }
351
+ return { validPaths };
352
+ }
353
+ /**
354
+ * Generate SBOMs for all manifests. In fail-fast mode, stops on first error.
355
+ * In continue-on-error mode, runs concurrently and collects failures.
356
+ *
357
+ * @param {string[]} manifestPaths
358
+ * @param {Options} workspaceOpts
359
+ * @param {boolean} continueOnError
360
+ * @param {number} concurrency
361
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
362
+ * @returns {Promise<Object.<string, object>>} sbomByPurl map
363
+ * @throws {Error} on first SBOM failure when `continueOnError` is false
364
+ * @private
365
+ */
366
+ async function generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors) {
367
+ /** @type {SbomResult[]} */
368
+ const results = [];
369
+ if (!continueOnError) {
370
+ for (const manifestPath of manifestPaths) {
371
+ const result = await generateOneSbom(manifestPath, workspaceOpts);
372
+ if (!result.ok) {
373
+ collectedErrors.push({ manifestPath: result.manifestPath, phase: 'sbom', reason: result.reason });
374
+ throw new Error(`${result.manifestPath}: ${result.reason}`);
375
+ }
376
+ results.push(result);
377
+ }
378
+ }
379
+ else {
380
+ const limit = pLimit(concurrency);
381
+ const settled = await Promise.all(manifestPaths.map(manifestPath => limit(async () => {
382
+ try {
383
+ return await generateOneSbom(manifestPath, workspaceOpts);
384
+ }
385
+ catch (err) {
386
+ const msg = err instanceof Error ? err.message : String(err);
387
+ if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
388
+ console.log(`Skipping ${manifestPath}: ${msg}`);
389
+ }
390
+ return { ok: false, manifestPath, reason: msg };
391
+ }
392
+ })));
393
+ for (const r of settled) {
394
+ results.push(r);
395
+ if (!r.ok) {
396
+ collectedErrors.push({ manifestPath: r.manifestPath, phase: 'sbom', reason: r.reason });
397
+ }
398
+ }
399
+ }
400
+ const sbomByPurl = {};
401
+ for (const r of results) {
402
+ if (r.ok) {
403
+ sbomByPurl[r.purl] = r.sbom;
404
+ }
405
+ }
406
+ return sbomByPurl;
407
+ }
408
+ /**
409
+ * Create an Error with optional `batchMetadata` attached.
410
+ * @param {string} message
411
+ * @param {boolean} wantMetadata
412
+ * @param {BatchAnalysisMetadata} [metadata]
413
+ * @returns {Error}
414
+ * @private
415
+ */
416
+ function batchError(message, wantMetadata, metadata) {
417
+ const err = new Error(message);
418
+ if (wantMetadata && metadata) {
419
+ err.batchMetadata = metadata;
420
+ }
421
+ return err;
422
+ }
423
+ /**
424
+ * @overload
425
+ * @param {string} workspaceRoot
426
+ * @param {true} html
427
+ * @param {Options & { batchMetadata: true }} opts
428
+ * @returns {Promise<{ analysis: string, metadata: BatchAnalysisMetadata }>}
429
+ * @throws {Error}
430
+ */
431
+ /**
432
+ * @overload
433
+ * @param {string} workspaceRoot
434
+ * @param {true} html
435
+ * @param {Options & { batchMetadata?: false }} [opts={}]
436
+ * @returns {Promise<string>}
437
+ * @throws {Error}
438
+ */
439
+ /**
440
+ * @overload
441
+ * @param {string} workspaceRoot
442
+ * @param {false} html
443
+ * @param {Options & { batchMetadata: true }} opts
444
+ * @returns {Promise<{ analysis: Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
445
+ * @throws {Error}
446
+ */
447
+ /**
448
+ * @overload
449
+ * @param {string} workspaceRoot
450
+ * @param {false} html
451
+ * @param {Options & { batchMetadata?: false }} [opts={}]
452
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>>}
453
+ * @throws {Error}
454
+ */
455
+ /**
456
+ * Get stack analysis for all workspace packages/crates (batch).
457
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
458
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
459
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
460
+ *
461
+ * @overload
462
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
463
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
464
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
465
+ * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>|{ analysis: string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
466
+ * @throws {Error} if workspace root invalid, no manifests found, no packages pass validation, no SBOMs produced, or backend request failed. When `opts.batchMetadata` is set, `error.batchMetadata` may be set on thrown errors.
467
+ */
468
+ async function stackAnalysisBatch(workspaceRoot, html = false, opts = {}) {
469
+ const theUrl = selectTrustifyDABackend(opts);
470
+ const root = path.resolve(workspaceRoot);
471
+ fs.accessSync(root, fs.constants.R_OK);
472
+ const continueOnError = resolveContinueOnError(opts);
473
+ const wantMetadata = resolveBatchMetadata(opts);
474
+ /** @type {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} */
475
+ const collectedErrors = [];
476
+ const { ecosystem, manifestPaths: discovered } = await detectWorkspaceManifests(root, opts);
477
+ let manifestPaths = discovered;
478
+ if (ecosystem === 'javascript') {
479
+ try {
480
+ const { validPaths } = validateJsManifests(manifestPaths, continueOnError, collectedErrors);
481
+ manifestPaths = validPaths;
482
+ }
483
+ catch (err) {
484
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
485
+ }
486
+ if (manifestPaths.length === 0 && discovered.length > 0) {
487
+ const detail = collectedErrors.map(e => `${e.manifestPath}: ${e.reason}`).join('; ');
488
+ throw batchError(`No valid packages after validation at ${root}. ${detail}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
489
+ }
490
+ }
491
+ if (manifestPaths.length === 0) {
492
+ throw new Error(`No workspace manifests found at ${root}. Ensure a supported workspace root exists (Cargo.toml+Cargo.lock, pom.xml, build.gradle, go.work, pyproject.toml+uv.lock, or package.json+lock file).`);
493
+ }
494
+ const workspaceOpts = { ...opts, TRUSTIFY_DA_WORKSPACE_DIR: root };
495
+ const concurrency = resolveBatchConcurrency(opts);
496
+ let sbomByPurl;
497
+ try {
498
+ sbomByPurl = await generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors);
499
+ }
500
+ catch (err) {
501
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
502
+ }
503
+ if (Object.keys(sbomByPurl).length === 0) {
504
+ throw batchError(`No valid SBOMs produced from ${manifestPaths.length} manifest(s) at ${root}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
505
+ }
506
+ const analysisResult = await analysis.requestStackBatch(sbomByPurl, theUrl, html, opts);
507
+ const meta = buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, Object.keys(sbomByPurl).length, collectedErrors);
508
+ if (wantMetadata) {
509
+ return { analysis: analysisResult, metadata: meta };
510
+ }
511
+ return analysisResult;
512
+ }
177
513
  /**
178
514
  * Validates the Exhort token.
179
515
  * @param {Options} [opts={}] - Optional parameters, potentially including token override.
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Run full license check: resolve project license (with backend identification and details),
3
+ * get dependency licenses from analysis report, and compute incompatibilities.
4
+ *
5
+ * @param {string} sbomContent - CycloneDX SBOM JSON string (the one sent for component analysis)
6
+ * @param {string} manifestPath - path to manifest
7
+ * @param {string} url - the backend url to send the request to
8
+ * @param {import('../index.js').Options} [opts={}]
9
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport} [analysisResult] - analysis result that includes licenses array from backend
10
+ * @returns {Promise<{ projectLicense: { manifest: Object|null, file: Object|null, mismatch: boolean }, incompatibleDependencies: Array<{ purl: string, licenses: string[], category?: string, reason: string }>, error?: string }>}
11
+ */
12
+ export function runLicenseCheck(sbomContent: string, manifestPath: string, url: string, opts?: import("../index.js").Options, analysisResult?: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts").AnalysisReport): Promise<{
13
+ projectLicense: {
14
+ manifest: Object | null;
15
+ file: Object | null;
16
+ mismatch: boolean;
17
+ };
18
+ incompatibleDependencies: Array<{
19
+ purl: string;
20
+ licenses: string[];
21
+ category?: string;
22
+ reason: string;
23
+ }>;
24
+ error?: string;
25
+ }>;
26
+ export { getCompatibility } from "./license_utils.js";
27
+ export { getProjectLicense, findLicenseFilePath, identifyLicense } from "./project_license.js";
28
+ export { licensesFromReport, normalizeLicensesResponse, getLicenseDetails } from "./licenses_api.js";
@@ -0,0 +1,106 @@
1
+ /**
2
+ * License resolution and dependency license compatibility for component analysis.
3
+ */
4
+ import { getCompatibility } from './license_utils.js';
5
+ import { licensesFromReport, getLicenseDetails } from './licenses_api.js';
6
+ import { getProjectLicense, findLicenseFilePath, identifyLicense } from './project_license.js';
7
+ export { getProjectLicense, findLicenseFilePath, identifyLicense } from './project_license.js';
8
+ export { licensesFromReport, normalizeLicensesResponse, getLicenseDetails } from './licenses_api.js';
9
+ export { getCompatibility } from './license_utils.js';
10
+ /**
11
+ * Run full license check: resolve project license (with backend identification and details),
12
+ * get dependency licenses from analysis report, and compute incompatibilities.
13
+ *
14
+ * @param {string} sbomContent - CycloneDX SBOM JSON string (the one sent for component analysis)
15
+ * @param {string} manifestPath - path to manifest
16
+ * @param {string} url - the backend url to send the request to
17
+ * @param {import('../index.js').Options} [opts={}]
18
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport.ts').AnalysisReport} [analysisResult] - analysis result that includes licenses array from backend
19
+ * @returns {Promise<{ projectLicense: { manifest: Object|null, file: Object|null, mismatch: boolean }, incompatibleDependencies: Array<{ purl: string, licenses: string[], category?: string, reason: string }>, error?: string }>}
20
+ */
21
+ export async function runLicenseCheck(sbomContent, manifestPath, url, opts = {}, analysisResult = null) {
22
+ // Resolve project license from manifest and LICENSE file
23
+ const projectLicense = getProjectLicense(manifestPath);
24
+ // Try backend identification for LICENSE file (more accurate than local pattern matching)
25
+ const licenseFilePath = findLicenseFilePath(manifestPath);
26
+ let backendFileId = null;
27
+ if (licenseFilePath) {
28
+ try {
29
+ backendFileId = await identifyLicense(licenseFilePath, { ...opts, TRUSTIFY_DA_BACKEND_URL: url });
30
+ }
31
+ catch {
32
+ // Fall back to local detection
33
+ }
34
+ }
35
+ // Determine final license identifiers
36
+ const manifestSpdx = projectLicense.fromManifest;
37
+ const fileSpdx = backendFileId || projectLicense.fromFile;
38
+ const mismatch = Boolean(manifestSpdx && fileSpdx && manifestSpdx.toLowerCase() !== fileSpdx.toLowerCase());
39
+ // Fetch detailed license info from backend (avoid duplicate calls if same license)
40
+ const licenseDetailsCache = new Map();
41
+ async function getDetails(spdxId) {
42
+ if (!spdxId || !url) {
43
+ return null;
44
+ }
45
+ if (licenseDetailsCache.has(spdxId)) {
46
+ return licenseDetailsCache.get(spdxId);
47
+ }
48
+ try {
49
+ const details = await getLicenseDetails(spdxId, { ...opts, TRUSTIFY_DA_BACKEND_URL: url });
50
+ licenseDetailsCache.set(spdxId, details);
51
+ return details;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ const manifestLicenseInfo = await getDetails(manifestSpdx);
58
+ const fileLicenseInfo = await getDetails(fileSpdx);
59
+ // Extract dependency purls from SBOM (exclude root component)
60
+ const sbomObj = typeof sbomContent === 'string' ? JSON.parse(sbomContent) : sbomContent;
61
+ const rootRef = sbomObj?.metadata?.component?.["bom-ref"] || sbomObj?.metadata?.component?.purl;
62
+ const purls = (sbomObj?.components || [])
63
+ .map(c => c.purl || c["bom-ref"])
64
+ .filter(Boolean)
65
+ .filter(purl => !rootRef || purl !== rootRef);
66
+ if (purls.length === 0) {
67
+ return {
68
+ projectLicense: { manifest: manifestLicenseInfo, file: fileLicenseInfo, mismatch },
69
+ incompatibleDependencies: []
70
+ };
71
+ }
72
+ // Get dependency licenses from analysis report
73
+ const licenseByPurl = licensesFromReport(analysisResult, purls);
74
+ if (licenseByPurl.size === 0 && analysisResult) {
75
+ return {
76
+ projectLicense: { manifest: manifestLicenseInfo, file: fileLicenseInfo, mismatch },
77
+ incompatibleDependencies: [],
78
+ error: 'No license data available in analysis report'
79
+ };
80
+ }
81
+ // Check compatibility for each dependency
82
+ const projectCategory = manifestLicenseInfo?.category || fileLicenseInfo?.category;
83
+ const incompatibleDependencies = [];
84
+ for (const purl of purls) {
85
+ const entry = licenseByPurl.get(purl);
86
+ if (!entry) {
87
+ continue;
88
+ }
89
+ const status = getCompatibility(projectCategory, entry.category);
90
+ if (status === 'incompatible') {
91
+ const reason = entry.category?.toUpperCase() === 'UNKNOWN'
92
+ ? 'License not recognized as a standard SPDX identifier. Manual review recommended to verify compatibility.'
93
+ : 'Dependency license(s) are incompatible with the project license.';
94
+ incompatibleDependencies.push({
95
+ purl,
96
+ licenses: entry.licenses,
97
+ category: entry.category,
98
+ reason
99
+ });
100
+ }
101
+ }
102
+ return {
103
+ projectLicense: { manifest: manifestLicenseInfo, file: fileLicenseInfo, mismatch },
104
+ incompatibleDependencies
105
+ };
106
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Find LICENSE file path in the same directory as the manifest.
3
+ * @param {string} manifestPath
4
+ * @returns {string|null} - path to LICENSE file or null if not found
5
+ */
6
+ export function findLicenseFilePath(manifestPath: string): string | null;
7
+ /**
8
+ * Very simple SPDX detection from common license text (first ~500 chars).
9
+ * @param {string} text
10
+ * @returns {string|null}
11
+ */
12
+ export function detectSpdxFromText(text: string): string | null;
13
+ /**
14
+ * Read LICENSE file and detect SPDX identifier.
15
+ * @param {string} manifestPath - path to manifest
16
+ * @returns {string|null} - SPDX identifier from LICENSE file or null
17
+ */
18
+ export function readLicenseFile(manifestPath: string): string | null;
19
+ /**
20
+ * Get project license from manifest or LICENSE file.
21
+ * Returns manifestLicense if provided, otherwise tries LICENSE file.
22
+ * @param {string|null} manifestLicense - license from manifest (or null)
23
+ * @param {string} manifestPath - path to manifest
24
+ * @returns {string|null} - SPDX identifier or null
25
+ */
26
+ export function getLicense(manifestLicense: string | null, manifestPath: string): string | null;
27
+ /**
28
+ * Normalize SPDX identifier for comparison (lowercase, strip common suffixes).
29
+ * @param {string} spdxOrName
30
+ * @returns {string}
31
+ */
32
+ export function normalizeSpdx(spdxOrName: string): string;
33
+ /**
34
+ * Check if a dependency's license is compatible with the project license based on backend categories.
35
+ *
36
+ * @param {string} [projectCategory] - backend category for project license: PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
37
+ * @param {string} [dependencyCategory] - backend category for dependency license: PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
38
+ * @returns {'compatible'|'incompatible'|'unknown'}
39
+ */
40
+ export function getCompatibility(projectCategory?: string, dependencyCategory?: string): "compatible" | "incompatible" | "unknown";