@trustify-da/trustify-da-javascript-client 0.3.0-ea.e12bc82 → 0.3.0-ea.f2d5d72

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 (64) hide show
  1. package/README.md +191 -11
  2. package/dist/package.json +22 -9
  3. package/dist/src/analysis.d.ts +21 -5
  4. package/dist/src/analysis.js +71 -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 +192 -8
  8. package/dist/src/cyclone_dx_sbom.d.ts +10 -2
  9. package/dist/src/cyclone_dx_sbom.js +32 -5
  10. package/dist/src/index.d.ts +128 -11
  11. package/dist/src/index.js +272 -7
  12. package/dist/src/license/index.d.ts +28 -0
  13. package/dist/src/license/index.js +100 -0
  14. package/dist/src/license/license_utils.d.ts +40 -0
  15. package/dist/src/license/license_utils.js +134 -0
  16. package/dist/src/license/licenses_api.d.ts +34 -0
  17. package/dist/src/license/licenses_api.js +98 -0
  18. package/dist/src/license/project_license.d.ts +20 -0
  19. package/dist/src/license/project_license.js +62 -0
  20. package/dist/src/oci_image/images.d.ts +4 -5
  21. package/dist/src/oci_image/utils.d.ts +4 -4
  22. package/dist/src/provider.d.ts +17 -5
  23. package/dist/src/provider.js +27 -5
  24. package/dist/src/providers/base_java.d.ts +3 -5
  25. package/dist/src/providers/base_javascript.d.ts +29 -7
  26. package/dist/src/providers/base_javascript.js +129 -22
  27. package/dist/src/providers/base_pyproject.d.ts +147 -0
  28. package/dist/src/providers/base_pyproject.js +279 -0
  29. package/dist/src/providers/golang_gomodules.d.ts +20 -13
  30. package/dist/src/providers/golang_gomodules.js +112 -114
  31. package/dist/src/providers/gomod_parser.d.ts +4 -0
  32. package/dist/src/providers/gomod_parser.js +16 -0
  33. package/dist/src/providers/java_gradle.d.ts +9 -3
  34. package/dist/src/providers/java_gradle.js +12 -2
  35. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  36. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  37. package/dist/src/providers/java_maven.d.ts +12 -5
  38. package/dist/src/providers/java_maven.js +33 -5
  39. package/dist/src/providers/javascript_pnpm.d.ts +1 -1
  40. package/dist/src/providers/javascript_pnpm.js +2 -2
  41. package/dist/src/providers/manifest.d.ts +2 -0
  42. package/dist/src/providers/manifest.js +22 -4
  43. package/dist/src/providers/processors/yarn_berry_processor.js +82 -3
  44. package/dist/src/providers/python_controller.d.ts +5 -2
  45. package/dist/src/providers/python_controller.js +56 -58
  46. package/dist/src/providers/python_pip.d.ts +11 -4
  47. package/dist/src/providers/python_pip.js +47 -54
  48. package/dist/src/providers/python_poetry.d.ts +42 -0
  49. package/dist/src/providers/python_poetry.js +146 -0
  50. package/dist/src/providers/python_uv.d.ts +26 -0
  51. package/dist/src/providers/python_uv.js +118 -0
  52. package/dist/src/providers/requirements_parser.d.ts +6 -0
  53. package/dist/src/providers/requirements_parser.js +24 -0
  54. package/dist/src/providers/rust_cargo.d.ts +52 -0
  55. package/dist/src/providers/rust_cargo.js +614 -0
  56. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  57. package/dist/src/providers/tree-sitter-requirements.wasm +0 -0
  58. package/dist/src/sbom.d.ts +10 -1
  59. package/dist/src/sbom.js +12 -2
  60. package/dist/src/tools.d.ts +22 -6
  61. package/dist/src/tools.js +56 -1
  62. package/dist/src/workspace.d.ts +61 -0
  63. package/dist/src/workspace.js +256 -0
  64. package/package.json +23 -10
@@ -12,18 +12,19 @@
12
12
  export function selectTrustifyDABackend(opts?: {
13
13
  TRUSTIFY_DA_DEBUG?: string | undefined;
14
14
  TRUSTIFY_DA_BACKEND_URL?: string | undefined;
15
- } | undefined): string;
15
+ }): string;
16
16
  export { parseImageRef } from "./oci_image/utils.js";
17
17
  export { ImageRef } from "./oci_image/images.js";
18
18
  declare namespace _default {
19
19
  export { componentAnalysis };
20
20
  export { stackAnalysis };
21
+ export { stackAnalysisBatch };
21
22
  export { imageAnalysis };
22
23
  export { validateToken };
23
24
  }
24
25
  export default _default;
25
26
  export type Options = {
26
- [key: string]: string | undefined;
27
+ TRUSTIFY_DA_CARGO_PATH?: string | undefined;
27
28
  TRUSTIFY_DA_DOCKER_PATH?: string | undefined;
28
29
  TRUSTIFY_DA_GO_MVS_LOGIC_ENABLED?: string | undefined;
29
30
  TRUSTIFY_DA_GO_PATH?: string | undefined;
@@ -48,10 +49,45 @@ export type Options = {
48
49
  TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined;
49
50
  TRUSTIFY_DA_SYFT_PATH?: string | undefined;
50
51
  TRUSTIFY_DA_YARN_PATH?: string | undefined;
52
+ TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined;
53
+ TRUSTIFY_DA_LICENSE_CHECK?: string | undefined;
51
54
  MATCH_MANIFEST_VERSIONS?: string | undefined;
52
- RHDA_SOURCE?: string | undefined;
53
- RHDA_TOKEN?: string | undefined;
54
- RHDA_TELEMETRY_ID?: string | undefined;
55
+ TRUSTIFY_DA_SOURCE?: string | undefined;
56
+ TRUSTIFY_DA_TOKEN?: string | undefined;
57
+ TRUSTIFY_DA_TELEMETRY_ID?: string | undefined;
58
+ TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined;
59
+ batchConcurrency?: number | undefined;
60
+ TRUSTIFY_DA_BATCH_CONCURRENCY?: string | undefined;
61
+ workspaceDiscoveryIgnore?: string[] | undefined;
62
+ TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string | undefined;
63
+ continueOnError?: boolean | undefined;
64
+ TRUSTIFY_DA_CONTINUE_ON_ERROR?: string | undefined;
65
+ batchMetadata?: boolean | undefined;
66
+ TRUSTIFY_DA_BATCH_METADATA?: string | undefined;
67
+ TRUSTIFY_DA_UV_PATH?: string | undefined;
68
+ TRUSTIFY_DA_POETRY_PATH?: string | undefined;
69
+ [key: string]: string | number | boolean | string[] | undefined;
70
+ };
71
+ export type BatchAnalysisMetadata = {
72
+ workspaceRoot: string;
73
+ ecosystem: "javascript" | "cargo" | "unknown";
74
+ total: number;
75
+ successful: number;
76
+ failed: number;
77
+ errors: Array<{
78
+ manifestPath: string;
79
+ phase: "validation" | "sbom";
80
+ reason: string;
81
+ }>;
82
+ };
83
+ export type SbomResult = {
84
+ ok: true;
85
+ purl: string;
86
+ sbom: object;
87
+ } | {
88
+ ok: false;
89
+ manifestPath: string;
90
+ reason: string;
55
91
  };
56
92
  /**
57
93
  * Get component analysis report for a manifest content.
@@ -60,16 +96,88 @@ export type Options = {
60
96
  * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
61
97
  * @throws {Error} if no matching provider, failed to get create content, or backend request failed
62
98
  */
63
- declare function componentAnalysis(manifest: string, opts?: Options | undefined): Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>;
99
+ declare function componentAnalysis(manifest: string, opts?: Options): Promise<import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport>;
100
+ /**
101
+ * @overload
102
+ * @param {string} manifest
103
+ * @param {true} html
104
+ * @param {Options} [opts={}]
105
+ * @returns {Promise<string>}
106
+ * @throws {Error}
107
+ */
64
108
  declare function stackAnalysis(manifest: string, html: true, opts?: Options | undefined): Promise<string>;
65
- declare function stackAnalysis(manifest: string, html: false, opts?: Options | undefined): Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>;
66
- declare function stackAnalysis(manifest: string, html?: boolean | undefined, opts?: Options | undefined): Promise<string | import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>;
109
+ /**
110
+ * @overload
111
+ * @param {string} manifest
112
+ * @param {false} html
113
+ * @param {Options} [opts={}]
114
+ * @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
115
+ * @throws {Error}
116
+ */
117
+ declare function stackAnalysis(manifest: string, html: false, opts?: Options | undefined): Promise<import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport>;
118
+ /**
119
+ * Get stack analysis report for a manifest file.
120
+ * @overload
121
+ * @param {string} manifest - path for the manifest
122
+ * @param {boolean} [html=false] - true will return a html string, false will return AnalysisReport object.
123
+ * @param {Options} [opts={}] - optional various options to pass along the application
124
+ * @returns {Promise<string|import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
125
+ * @throws {Error} if manifest inaccessible, no matching provider, failed to get create content,
126
+ * or backend request failed
127
+ */
128
+ declare function stackAnalysis(manifest: string, html?: boolean | undefined, opts?: Options | undefined): Promise<string | import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport>;
129
+ /**
130
+ * Get stack analysis for all workspace packages/crates (batch).
131
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
132
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
133
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
134
+ *
135
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
136
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
137
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
138
+ * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>|{ analysis: string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
139
+ * @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.
140
+ */
141
+ declare function stackAnalysisBatch(workspaceRoot: string, html?: boolean, opts?: Options): Promise<string | {
142
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
143
+ } | {
144
+ analysis: string | {
145
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
146
+ };
147
+ metadata: BatchAnalysisMetadata;
148
+ }>;
149
+ /**
150
+ * @overload
151
+ * @param {Array<string>} imageRefs
152
+ * @param {true} html
153
+ * @param {Options} [opts={}]
154
+ * @returns {Promise<string>}
155
+ * @throws {Error}
156
+ */
67
157
  declare function imageAnalysis(imageRefs: Array<string>, html: true, opts?: Options | undefined): Promise<string>;
158
+ /**
159
+ * @overload
160
+ * @param {Array<string>} imageRefs
161
+ * @param {false} html
162
+ * @param {Options} [opts={}]
163
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
164
+ * @throws {Error}
165
+ */
68
166
  declare function imageAnalysis(imageRefs: Array<string>, html: false, opts?: Options | undefined): Promise<{
69
- [x: string]: import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport;
167
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
70
168
  }>;
169
+ /**
170
+ * Get image analysis report for a set of OCI image references.
171
+ * @overload
172
+ * @param {Array<string>} imageRefs - OCI image references
173
+ * @param {boolean} [html=false] - true will return a html string, false will return AnalysisReport
174
+ * @param {Options} [opts={}] - optional various options to pass along the application
175
+ * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
176
+ * @throws {Error} if manifest inaccessible, no matching provider, failed to get create content,
177
+ * or backend request failed
178
+ */
71
179
  declare function imageAnalysis(imageRefs: Array<string>, html?: boolean | undefined, opts?: Options | undefined): Promise<string | {
72
- [x: string]: import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport;
180
+ [x: string]: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport;
73
181
  }>;
74
182
  /**
75
183
  * Validates the Exhort token.
@@ -77,4 +185,13 @@ declare function imageAnalysis(imageRefs: Array<string>, html?: boolean | undefi
77
185
  * @returns {Promise<object>} A promise that resolves with the validation result from the backend.
78
186
  * @throws {Error} if the backend request failed.
79
187
  */
80
- declare function validateToken(opts?: Options | undefined): Promise<object>;
188
+ declare function validateToken(opts?: Options): Promise<object>;
189
+ import { discoverWorkspacePackages } from './workspace.js';
190
+ import { discoverWorkspaceCrates } from './workspace.js';
191
+ import { validatePackageJson } from './workspace.js';
192
+ import { resolveWorkspaceDiscoveryIgnore } from './workspace.js';
193
+ import { filterManifestPathsByDiscoveryIgnore } from './workspace.js';
194
+ import { resolveContinueOnError } from './batch_opts.js';
195
+ import { resolveBatchMetadata } from './batch_opts.js';
196
+ export { discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata };
197
+ export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
package/dist/src/index.js CHANGED
@@ -1,16 +1,22 @@
1
1
  import path from "node:path";
2
2
  import { EOL } from "os";
3
+ import pLimit from 'p-limit';
3
4
  import { availableProviders, match } from './provider.js';
4
5
  import analysis from './analysis.js';
5
6
  import fs from 'node:fs';
6
7
  import { getCustom } from "./tools.js";
8
+ import { resolveBatchMetadata, resolveContinueOnError } from './batch_opts.js';
9
+ import { discoverWorkspaceCrates, discoverWorkspacePackages, filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, validatePackageJson, } from './workspace.js';
7
10
  import.meta.dirname;
8
11
  import * as url from 'url';
9
12
  export { parseImageRef } from "./oci_image/utils.js";
10
13
  export { ImageRef } from "./oci_image/images.js";
11
- export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken };
14
+ export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
15
+ export default { componentAnalysis, stackAnalysis, stackAnalysisBatch, imageAnalysis, validateToken };
16
+ export { discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
12
17
  /**
13
18
  * @typedef {{
19
+ * TRUSTIFY_DA_CARGO_PATH?: string | undefined,
14
20
  * TRUSTIFY_DA_DOCKER_PATH?: string | undefined,
15
21
  * TRUSTIFY_DA_GO_MVS_LOGIC_ENABLED?: string | undefined,
16
22
  * TRUSTIFY_DA_GO_PATH?: string | undefined,
@@ -35,13 +41,36 @@ export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken
35
41
  * TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined,
36
42
  * TRUSTIFY_DA_SYFT_PATH?: string | undefined,
37
43
  * TRUSTIFY_DA_YARN_PATH?: string | undefined,
44
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
45
+ * TRUSTIFY_DA_LICENSE_CHECK?: string | undefined,
38
46
  * MATCH_MANIFEST_VERSIONS?: string | undefined,
39
- * RHDA_SOURCE?: string | undefined,
40
- * RHDA_TOKEN?: string | undefined,
41
- * RHDA_TELEMETRY_ID?: string | undefined,
42
- * [key: string]: string | undefined,
47
+ * TRUSTIFY_DA_SOURCE?: string | undefined,
48
+ * TRUSTIFY_DA_TOKEN?: string | undefined,
49
+ * TRUSTIFY_DA_TELEMETRY_ID?: string | undefined,
50
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
51
+ * batchConcurrency?: number | undefined,
52
+ * TRUSTIFY_DA_BATCH_CONCURRENCY?: string | undefined,
53
+ * workspaceDiscoveryIgnore?: string[] | undefined,
54
+ * TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string | undefined,
55
+ * continueOnError?: boolean | undefined,
56
+ * TRUSTIFY_DA_CONTINUE_ON_ERROR?: string | undefined,
57
+ * batchMetadata?: boolean | undefined,
58
+ * TRUSTIFY_DA_BATCH_METADATA?: string | undefined,
59
+ * TRUSTIFY_DA_UV_PATH?: string | undefined,
60
+ * TRUSTIFY_DA_POETRY_PATH?: string | undefined,
61
+ * [key: string]: string | number | boolean | string[] | undefined,
43
62
  * }} Options
44
63
  */
64
+ /**
65
+ * @typedef {{
66
+ * workspaceRoot: string,
67
+ * ecosystem: 'javascript' | 'cargo' | 'unknown',
68
+ * total: number,
69
+ * successful: number,
70
+ * failed: number,
71
+ * errors: Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>
72
+ * }} BatchAnalysisMetadata
73
+ */
45
74
  /**
46
75
  * Logs messages to the console if the TRUSTIFY_DA_DEBUG environment variable is set to "true".
47
76
  * @param {string} alongsideText - The text to prepend to the log message.
@@ -127,7 +156,7 @@ export function selectTrustifyDABackend(opts = {}) {
127
156
  async function stackAnalysis(manifest, html = false, opts = {}) {
128
157
  const theUrl = selectTrustifyDABackend(opts);
129
158
  fs.accessSync(manifest, fs.constants.R_OK); // throws error if file unreadable
130
- let provider = match(manifest, availableProviders); // throws error if no matching provider
159
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
131
160
  return await analysis.requestStack(provider, manifest, theUrl, html, opts); // throws error request sending failed
132
161
  }
133
162
  /**
@@ -141,7 +170,7 @@ async function componentAnalysis(manifest, opts = {}) {
141
170
  const theUrl = selectTrustifyDABackend(opts);
142
171
  fs.accessSync(manifest, fs.constants.R_OK);
143
172
  opts["manifest-type"] = path.basename(manifest);
144
- let provider = match(manifest, availableProviders); // throws error if no matching provider
173
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
145
174
  return await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
146
175
  }
147
176
  /**
@@ -174,6 +203,242 @@ async function imageAnalysis(imageRefs, html = false, opts = {}) {
174
203
  const theUrl = selectTrustifyDABackend(opts);
175
204
  return await analysis.requestImages(imageRefs, theUrl, html, opts);
176
205
  }
206
+ /**
207
+ * Max concurrent SBOM generations for batch workspace analysis. Env/opts override default 10.
208
+ * @param {Options} opts
209
+ * @returns {number}
210
+ * @private
211
+ */
212
+ function resolveBatchConcurrency(opts) {
213
+ const fromEnv = getCustom('TRUSTIFY_DA_BATCH_CONCURRENCY', null, opts);
214
+ const raw = opts.batchConcurrency ?? fromEnv ?? '10';
215
+ const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10);
216
+ if (!Number.isFinite(n) || n < 1) {
217
+ return 10;
218
+ }
219
+ return Math.min(256, n);
220
+ }
221
+ /**
222
+ * @param {string} root
223
+ * @param {'javascript' | 'cargo' | 'unknown'} ecosystem
224
+ * @param {number} totalSbomAttempts
225
+ * @param {number} successfulSbomCount
226
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} errors
227
+ * @returns {BatchAnalysisMetadata}
228
+ * @private
229
+ */
230
+ function buildBatchAnalysisMetadata(root, ecosystem, totalSbomAttempts, successfulSbomCount, errors) {
231
+ return {
232
+ workspaceRoot: root,
233
+ ecosystem,
234
+ total: totalSbomAttempts,
235
+ successful: successfulSbomCount,
236
+ failed: errors.length,
237
+ errors: [...errors],
238
+ };
239
+ }
240
+ /**
241
+ * @typedef {{ ok: true, purl: string, sbom: object } | { ok: false, manifestPath: string, reason: string }} SbomResult
242
+ */
243
+ /**
244
+ * Generate an SBOM for a single manifest, returning a normalized result.
245
+ *
246
+ * @param {string} manifestPath
247
+ * @param {Options} workspaceOpts - opts with `TRUSTIFY_DA_WORKSPACE_DIR` set
248
+ * @returns {Promise<SbomResult>}
249
+ * @private
250
+ */
251
+ async function generateOneSbom(manifestPath, workspaceOpts) {
252
+ const provider = match(manifestPath, availableProviders, workspaceOpts);
253
+ const provided = await provider.provideStack(manifestPath, workspaceOpts);
254
+ const sbom = JSON.parse(provided.content);
255
+ const purl = sbom?.metadata?.component?.purl || sbom?.metadata?.component?.['bom-ref'];
256
+ if (!purl) {
257
+ return { ok: false, manifestPath, reason: 'missing purl in SBOM' };
258
+ }
259
+ return { ok: true, purl, sbom };
260
+ }
261
+ /**
262
+ * Detect the workspace ecosystem and discover manifest paths.
263
+ *
264
+ * @param {string} root - Resolved workspace root
265
+ * @param {Options} opts
266
+ * @returns {Promise<{ ecosystem: 'javascript' | 'cargo' | 'unknown', manifestPaths: string[] }>}
267
+ * @private
268
+ */
269
+ async function detectWorkspaceManifests(root, opts) {
270
+ const cargoToml = path.join(root, 'Cargo.toml');
271
+ const cargoLock = path.join(root, 'Cargo.lock');
272
+ const packageJson = path.join(root, 'package.json');
273
+ if (fs.existsSync(cargoToml) && fs.existsSync(cargoLock)) {
274
+ return { ecosystem: 'cargo', manifestPaths: await discoverWorkspaceCrates(root, opts) };
275
+ }
276
+ const hasJsLock = fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
277
+ || fs.existsSync(path.join(root, 'yarn.lock'))
278
+ || fs.existsSync(path.join(root, 'package-lock.json'));
279
+ if (fs.existsSync(packageJson) && hasJsLock) {
280
+ let manifestPaths = await discoverWorkspacePackages(root, opts);
281
+ if (manifestPaths.length === 0) {
282
+ manifestPaths = [packageJson];
283
+ }
284
+ return { ecosystem: 'javascript', manifestPaths };
285
+ }
286
+ return { ecosystem: 'unknown', manifestPaths: [] };
287
+ }
288
+ /**
289
+ * Validate discovered JS package.json manifests, collecting errors.
290
+ *
291
+ * @param {string[]} manifestPaths
292
+ * @param {boolean} continueOnError
293
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
294
+ * @returns {{ validPaths: string[] }}
295
+ * @throws {Error} on first invalid manifest when `continueOnError` is false
296
+ * @private
297
+ */
298
+ function validateJsManifests(manifestPaths, continueOnError, collectedErrors) {
299
+ const validPaths = [];
300
+ for (const p of manifestPaths) {
301
+ const v = validatePackageJson(p);
302
+ if (v.valid) {
303
+ validPaths.push(p);
304
+ }
305
+ else {
306
+ collectedErrors.push({ manifestPath: p, phase: 'validation', reason: v.error });
307
+ console.warn(`Skipping invalid package.json (${v.error}): ${p}`);
308
+ if (!continueOnError) {
309
+ throw new Error(`Invalid package.json (${v.error}): ${p}`);
310
+ }
311
+ }
312
+ }
313
+ return { validPaths };
314
+ }
315
+ /**
316
+ * Generate SBOMs for all manifests. In fail-fast mode, stops on first error.
317
+ * In continue-on-error mode, runs concurrently and collects failures.
318
+ *
319
+ * @param {string[]} manifestPaths
320
+ * @param {Options} workspaceOpts
321
+ * @param {boolean} continueOnError
322
+ * @param {number} concurrency
323
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
324
+ * @returns {Promise<Object.<string, object>>} sbomByPurl map
325
+ * @throws {Error} on first SBOM failure when `continueOnError` is false
326
+ * @private
327
+ */
328
+ async function generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors) {
329
+ /** @type {SbomResult[]} */
330
+ const results = [];
331
+ if (!continueOnError) {
332
+ for (const manifestPath of manifestPaths) {
333
+ const result = await generateOneSbom(manifestPath, workspaceOpts);
334
+ if (!result.ok) {
335
+ collectedErrors.push({ manifestPath: result.manifestPath, phase: 'sbom', reason: result.reason });
336
+ throw new Error(`${result.manifestPath}: ${result.reason}`);
337
+ }
338
+ results.push(result);
339
+ }
340
+ }
341
+ else {
342
+ const limit = pLimit(concurrency);
343
+ const settled = await Promise.all(manifestPaths.map(manifestPath => limit(async () => {
344
+ try {
345
+ return await generateOneSbom(manifestPath, workspaceOpts);
346
+ }
347
+ catch (err) {
348
+ const msg = err instanceof Error ? err.message : String(err);
349
+ if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
350
+ console.log(`Skipping ${manifestPath}: ${msg}`);
351
+ }
352
+ return { ok: false, manifestPath, reason: msg };
353
+ }
354
+ })));
355
+ for (const r of settled) {
356
+ results.push(r);
357
+ if (!r.ok) {
358
+ collectedErrors.push({ manifestPath: r.manifestPath, phase: 'sbom', reason: r.reason });
359
+ }
360
+ }
361
+ }
362
+ const sbomByPurl = {};
363
+ for (const r of results) {
364
+ if (r.ok) {
365
+ sbomByPurl[r.purl] = r.sbom;
366
+ }
367
+ }
368
+ return sbomByPurl;
369
+ }
370
+ /**
371
+ * Create an Error with optional `batchMetadata` attached.
372
+ * @param {string} message
373
+ * @param {boolean} wantMetadata
374
+ * @param {BatchAnalysisMetadata} [metadata]
375
+ * @returns {Error}
376
+ * @private
377
+ */
378
+ function batchError(message, wantMetadata, metadata) {
379
+ const err = new Error(message);
380
+ if (wantMetadata && metadata) {
381
+ err.batchMetadata = metadata;
382
+ }
383
+ return err;
384
+ }
385
+ /**
386
+ * Get stack analysis for all workspace packages/crates (batch).
387
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
388
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
389
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
390
+ *
391
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
392
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
393
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
394
+ * @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>|{ analysis: string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
395
+ * @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.
396
+ */
397
+ async function stackAnalysisBatch(workspaceRoot, html = false, opts = {}) {
398
+ const theUrl = selectTrustifyDABackend(opts);
399
+ const root = path.resolve(workspaceRoot);
400
+ fs.accessSync(root, fs.constants.R_OK);
401
+ const continueOnError = resolveContinueOnError(opts);
402
+ const wantMetadata = resolveBatchMetadata(opts);
403
+ /** @type {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} */
404
+ const collectedErrors = [];
405
+ const { ecosystem, manifestPaths: discovered } = await detectWorkspaceManifests(root, opts);
406
+ let manifestPaths = discovered;
407
+ if (ecosystem === 'javascript') {
408
+ try {
409
+ const { validPaths } = validateJsManifests(manifestPaths, continueOnError, collectedErrors);
410
+ manifestPaths = validPaths;
411
+ }
412
+ catch (err) {
413
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
414
+ }
415
+ if (manifestPaths.length === 0 && discovered.length > 0) {
416
+ const detail = collectedErrors.map(e => `${e.manifestPath}: ${e.reason}`).join('; ');
417
+ throw batchError(`No valid packages after validation at ${root}. ${detail}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
418
+ }
419
+ }
420
+ if (manifestPaths.length === 0) {
421
+ throw new Error(`No workspace manifests found at ${root}. Ensure Cargo.toml+Cargo.lock or package.json+lock file exist.`);
422
+ }
423
+ const workspaceOpts = { ...opts, TRUSTIFY_DA_WORKSPACE_DIR: root };
424
+ const concurrency = resolveBatchConcurrency(opts);
425
+ let sbomByPurl;
426
+ try {
427
+ sbomByPurl = await generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors);
428
+ }
429
+ catch (err) {
430
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
431
+ }
432
+ if (Object.keys(sbomByPurl).length === 0) {
433
+ throw batchError(`No valid SBOMs produced from ${manifestPaths.length} manifest(s) at ${root}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
434
+ }
435
+ const analysisResult = await analysis.requestStackBatch(sbomByPurl, theUrl, html, opts);
436
+ const meta = buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, Object.keys(sbomByPurl).length, collectedErrors);
437
+ if (wantMetadata) {
438
+ return { analysis: analysisResult, metadata: meta };
439
+ }
440
+ return analysisResult;
441
+ }
177
442
  /**
178
443
  * Validates the Exhort token.
179
444
  * @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').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").AnalysisReport): Promise<{
13
+ projectLicense: {
14
+ manifest: any | null;
15
+ file: any | 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,100 @@
1
+ /**
2
+ * License resolution and dependency license compatibility for component analysis.
3
+ */
4
+ import { getProjectLicense, findLicenseFilePath, identifyLicense } from './project_license.js';
5
+ import { licensesFromReport, getLicenseDetails } from './licenses_api.js';
6
+ import { getCompatibility } from './license_utils.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').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
+ if (licenseDetailsCache.has(spdxId))
45
+ return licenseDetailsCache.get(spdxId);
46
+ try {
47
+ const details = await getLicenseDetails(spdxId, { ...opts, TRUSTIFY_DA_BACKEND_URL: url });
48
+ licenseDetailsCache.set(spdxId, details);
49
+ return details;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ const manifestLicenseInfo = await getDetails(manifestSpdx);
56
+ const fileLicenseInfo = await getDetails(fileSpdx);
57
+ // Extract dependency purls from SBOM (exclude root component)
58
+ const sbomObj = typeof sbomContent === 'string' ? JSON.parse(sbomContent) : sbomContent;
59
+ const rootRef = sbomObj?.metadata?.component?.["bom-ref"] || sbomObj?.metadata?.component?.purl;
60
+ const purls = (sbomObj?.components || [])
61
+ .map(c => c.purl || c["bom-ref"])
62
+ .filter(Boolean)
63
+ .filter(purl => !rootRef || purl !== rootRef);
64
+ if (purls.length === 0) {
65
+ return {
66
+ projectLicense: { manifest: manifestLicenseInfo, file: fileLicenseInfo, mismatch },
67
+ incompatibleDependencies: []
68
+ };
69
+ }
70
+ // Get dependency licenses from analysis report
71
+ const licenseByPurl = licensesFromReport(analysisResult, purls);
72
+ if (licenseByPurl.size === 0 && analysisResult) {
73
+ return {
74
+ projectLicense: { manifest: manifestLicenseInfo, file: fileLicenseInfo, mismatch },
75
+ incompatibleDependencies: [],
76
+ error: 'No license data available in analysis report'
77
+ };
78
+ }
79
+ // Check compatibility for each dependency
80
+ const projectCategory = manifestLicenseInfo?.category || fileLicenseInfo?.category;
81
+ const incompatibleDependencies = [];
82
+ for (const purl of purls) {
83
+ const entry = licenseByPurl.get(purl);
84
+ if (!entry)
85
+ continue;
86
+ const status = getCompatibility(projectCategory, entry.category);
87
+ if (status === 'incompatible') {
88
+ incompatibleDependencies.push({
89
+ purl,
90
+ licenses: entry.licenses,
91
+ category: entry.category,
92
+ reason: 'Dependency license(s) are incompatible with the project license.'
93
+ });
94
+ }
95
+ }
96
+ return {
97
+ projectLicense: { manifest: manifestLicenseInfo, file: fileLicenseInfo, mismatch },
98
+ incompatibleDependencies
99
+ };
100
+ }
@@ -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";