@trustify-da/trustify-da-javascript-client 0.3.0-ea.b40d888 → 0.3.0-ea.bbe2094

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 (74) hide show
  1. package/README.md +191 -11
  2. package/dist/package.json +24 -11
  3. package/dist/src/analysis.d.ts +21 -5
  4. package/dist/src/analysis.js +74 -80
  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 +241 -8
  8. package/dist/src/cyclone_dx_sbom.d.ts +17 -3
  9. package/dist/src/cyclone_dx_sbom.js +48 -8
  10. package/dist/src/index.d.ts +197 -11
  11. package/dist/src/index.js +353 -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/oci_image/utils.js +11 -2
  23. package/dist/src/provider.d.ts +17 -5
  24. package/dist/src/provider.js +31 -5
  25. package/dist/src/providers/base_java.d.ts +3 -14
  26. package/dist/src/providers/base_java.js +2 -38
  27. package/dist/src/providers/base_javascript.d.ts +35 -7
  28. package/dist/src/providers/base_javascript.js +131 -24
  29. package/dist/src/providers/base_pyproject.d.ts +153 -0
  30. package/dist/src/providers/base_pyproject.js +315 -0
  31. package/dist/src/providers/golang_gomodules.d.ts +29 -13
  32. package/dist/src/providers/golang_gomodules.js +176 -121
  33. package/dist/src/providers/gomod_parser.d.ts +4 -0
  34. package/dist/src/providers/gomod_parser.js +16 -0
  35. package/dist/src/providers/java_gradle.d.ts +28 -3
  36. package/dist/src/providers/java_gradle.js +128 -4
  37. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  38. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  39. package/dist/src/providers/java_maven.d.ts +20 -5
  40. package/dist/src/providers/java_maven.js +126 -6
  41. package/dist/src/providers/javascript_bun.d.ts +10 -0
  42. package/dist/src/providers/javascript_bun.js +100 -0
  43. package/dist/src/providers/javascript_npm.d.ts +1 -0
  44. package/dist/src/providers/javascript_npm.js +21 -0
  45. package/dist/src/providers/javascript_pnpm.d.ts +1 -1
  46. package/dist/src/providers/javascript_pnpm.js +8 -4
  47. package/dist/src/providers/manifest.d.ts +2 -0
  48. package/dist/src/providers/manifest.js +22 -4
  49. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  50. package/dist/src/providers/marker_evaluator.js +191 -0
  51. package/dist/src/providers/processors/yarn_berry_processor.js +88 -5
  52. package/dist/src/providers/python_controller.d.ts +10 -3
  53. package/dist/src/providers/python_controller.js +61 -59
  54. package/dist/src/providers/python_pip.d.ts +15 -4
  55. package/dist/src/providers/python_pip.js +51 -58
  56. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  57. package/dist/src/providers/python_pip_pyproject.js +146 -0
  58. package/dist/src/providers/python_poetry.d.ts +75 -0
  59. package/dist/src/providers/python_poetry.js +238 -0
  60. package/dist/src/providers/python_uv.d.ts +55 -0
  61. package/dist/src/providers/python_uv.js +227 -0
  62. package/dist/src/providers/requirements_parser.d.ts +6 -0
  63. package/dist/src/providers/requirements_parser.js +24 -0
  64. package/dist/src/providers/rust_cargo.d.ts +52 -0
  65. package/dist/src/providers/rust_cargo.js +614 -0
  66. package/dist/src/providers/tree-sitter-gomod.wasm +0 -0
  67. package/dist/src/providers/tree-sitter-requirements.wasm +0 -0
  68. package/dist/src/sbom.d.ts +17 -2
  69. package/dist/src/sbom.js +16 -4
  70. package/dist/src/tools.d.ts +48 -6
  71. package/dist/src/tools.js +114 -1
  72. package/dist/src/workspace.d.ts +70 -0
  73. package/dist/src/workspace.js +256 -0
  74. package/package.json +25 -12
package/dist/src/index.js CHANGED
@@ -1,16 +1,26 @@
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 { discoverMavenModules } from './providers/java_maven.js';
10
+ import { discoverGradleSubprojects } from './providers/java_gradle.js';
11
+ import { discoverGoWorkspaceModules } from './providers/golang_gomodules.js';
12
+ import { discoverUvWorkspaceMembers } from './providers/python_uv.js';
13
+ import { discoverWorkspaceCrates, discoverWorkspacePackages, filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, validatePackageJson, } from './workspace.js';
7
14
  import.meta.dirname;
8
15
  import * as url from 'url';
9
16
  export { parseImageRef } from "./oci_image/utils.js";
10
17
  export { ImageRef } from "./oci_image/images.js";
11
- export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken };
18
+ export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
19
+ export default { componentAnalysis, stackAnalysis, stackAnalysisBatch, imageAnalysis, validateToken, generateSbom };
20
+ export { discoverMavenModules, discoverGradleSubprojects, discoverGoWorkspaceModules, discoverUvWorkspaceMembers, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
12
21
  /**
13
22
  * @typedef {{
23
+ * TRUSTIFY_DA_CARGO_PATH?: string | undefined,
14
24
  * TRUSTIFY_DA_DOCKER_PATH?: string | undefined,
15
25
  * TRUSTIFY_DA_GO_MVS_LOGIC_ENABLED?: string | undefined,
16
26
  * TRUSTIFY_DA_GO_PATH?: string | undefined,
@@ -35,13 +45,36 @@ export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken
35
45
  * TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined,
36
46
  * TRUSTIFY_DA_SYFT_PATH?: string | undefined,
37
47
  * TRUSTIFY_DA_YARN_PATH?: string | undefined,
48
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
49
+ * TRUSTIFY_DA_LICENSE_CHECK?: string | undefined,
38
50
  * 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,
51
+ * TRUSTIFY_DA_SOURCE?: string | undefined,
52
+ * TRUSTIFY_DA_TOKEN?: string | undefined,
53
+ * TRUSTIFY_DA_TELEMETRY_ID?: string | undefined,
54
+ * TRUSTIFY_DA_WORKSPACE_DIR?: string | undefined,
55
+ * batchConcurrency?: number | undefined,
56
+ * TRUSTIFY_DA_BATCH_CONCURRENCY?: string | undefined,
57
+ * workspaceDiscoveryIgnore?: string[] | undefined,
58
+ * TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string | undefined,
59
+ * continueOnError?: boolean | undefined,
60
+ * TRUSTIFY_DA_CONTINUE_ON_ERROR?: string | undefined,
61
+ * batchMetadata?: boolean | undefined,
62
+ * TRUSTIFY_DA_BATCH_METADATA?: string | undefined,
63
+ * TRUSTIFY_DA_UV_PATH?: string | undefined,
64
+ * TRUSTIFY_DA_POETRY_PATH?: string | undefined,
65
+ * [key: string]: string | number | boolean | string[] | undefined,
43
66
  * }} Options
44
67
  */
68
+ /**
69
+ * @typedef {{
70
+ * workspaceRoot: string,
71
+ * ecosystem: 'javascript' | 'cargo' | 'pyproject' | 'unknown',
72
+ * total: number,
73
+ * successful: number,
74
+ * failed: number,
75
+ * errors: Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>
76
+ * }} BatchAnalysisMetadata
77
+ */
45
78
  /**
46
79
  * Logs messages to the console if the TRUSTIFY_DA_DEBUG environment variable is set to "true".
47
80
  * @param {string} alongsideText - The text to prepend to the log message.
@@ -127,7 +160,7 @@ export function selectTrustifyDABackend(opts = {}) {
127
160
  async function stackAnalysis(manifest, html = false, opts = {}) {
128
161
  const theUrl = selectTrustifyDABackend(opts);
129
162
  fs.accessSync(manifest, fs.constants.R_OK); // throws error if file unreadable
130
- let provider = match(manifest, availableProviders); // throws error if no matching provider
163
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
131
164
  return await analysis.requestStack(provider, manifest, theUrl, html, opts); // throws error request sending failed
132
165
  }
133
166
  /**
@@ -141,7 +174,7 @@ async function componentAnalysis(manifest, opts = {}) {
141
174
  const theUrl = selectTrustifyDABackend(opts);
142
175
  fs.accessSync(manifest, fs.constants.R_OK);
143
176
  opts["manifest-type"] = path.basename(manifest);
144
- let provider = match(manifest, availableProviders); // throws error if no matching provider
177
+ let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
145
178
  return await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
146
179
  }
147
180
  /**
@@ -174,6 +207,319 @@ async function imageAnalysis(imageRefs, html = false, opts = {}) {
174
207
  const theUrl = selectTrustifyDABackend(opts);
175
208
  return await analysis.requestImages(imageRefs, theUrl, html, opts);
176
209
  }
210
+ /**
211
+ * Max concurrent SBOM generations for batch workspace analysis. Env/opts override default 10.
212
+ * @param {Options} opts
213
+ * @returns {number}
214
+ * @private
215
+ */
216
+ function resolveBatchConcurrency(opts) {
217
+ const fromEnv = getCustom('TRUSTIFY_DA_BATCH_CONCURRENCY', null, opts);
218
+ const raw = opts.batchConcurrency ?? fromEnv ?? '10';
219
+ const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10);
220
+ if (!Number.isFinite(n) || n < 1) {
221
+ return 10;
222
+ }
223
+ return Math.min(256, n);
224
+ }
225
+ /**
226
+ * @param {string} root
227
+ * @param {'javascript' | 'cargo' | 'unknown'} ecosystem
228
+ * @param {number} totalSbomAttempts
229
+ * @param {number} successfulSbomCount
230
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} errors
231
+ * @returns {BatchAnalysisMetadata}
232
+ * @private
233
+ */
234
+ function buildBatchAnalysisMetadata(root, ecosystem, totalSbomAttempts, successfulSbomCount, errors) {
235
+ return {
236
+ workspaceRoot: root,
237
+ ecosystem,
238
+ total: totalSbomAttempts,
239
+ successful: successfulSbomCount,
240
+ failed: errors.length,
241
+ errors: [...errors],
242
+ };
243
+ }
244
+ /**
245
+ * Generate a CycloneDX SBOM from a manifest file. No backend HTTP request is made.
246
+ *
247
+ * @param {string} manifestPath - path to the manifest file (e.g. pom.xml, package.json)
248
+ * @param {Options} [opts={}] - optional options (e.g. workspace dir, tool paths)
249
+ * @returns {Promise<object>} parsed CycloneDX SBOM JSON object
250
+ * @throws {Error} if the manifest is unsupported or SBOM generation fails
251
+ */
252
+ export async function generateSbom(manifestPath, opts = {}) {
253
+ fs.accessSync(manifestPath, fs.constants.R_OK);
254
+ const result = await generateOneSbom(manifestPath, opts);
255
+ if (!result.ok) {
256
+ throw new Error(`Failed to generate SBOM for ${result.manifestPath}: ${result.reason}`);
257
+ }
258
+ return result.sbom;
259
+ }
260
+ /**
261
+ * @typedef {{ ok: true, purl: string, sbom: object } | { ok: false, manifestPath: string, reason: string }} SbomResult
262
+ */
263
+ /**
264
+ * Generate an SBOM for a single manifest, returning a normalized result.
265
+ *
266
+ * @param {string} manifestPath
267
+ * @param {Options} workspaceOpts - opts with `TRUSTIFY_DA_WORKSPACE_DIR` set
268
+ * @returns {Promise<SbomResult>}
269
+ * @private
270
+ */
271
+ async function generateOneSbom(manifestPath, workspaceOpts) {
272
+ const provider = match(manifestPath, availableProviders, workspaceOpts);
273
+ const provided = await provider.provideStack(manifestPath, workspaceOpts);
274
+ const sbom = JSON.parse(provided.content);
275
+ const purl = sbom?.metadata?.component?.purl || sbom?.metadata?.component?.['bom-ref'];
276
+ if (!purl) {
277
+ return { ok: false, manifestPath, reason: 'missing purl in SBOM' };
278
+ }
279
+ return { ok: true, purl, sbom };
280
+ }
281
+ /**
282
+ * Detect the workspace ecosystem and discover manifest paths.
283
+ *
284
+ * @param {string} root - Resolved workspace root
285
+ * @param {Options} opts
286
+ * @returns {Promise<{ ecosystem: 'javascript' | 'cargo' | 'maven' | 'gradle' | 'gomodules' | 'pyproject' | 'unknown', manifestPaths: string[] }>}
287
+ * @private
288
+ */
289
+ async function detectWorkspaceManifests(root, opts) {
290
+ const cargoToml = path.join(root, 'Cargo.toml');
291
+ const cargoLock = path.join(root, 'Cargo.lock');
292
+ const packageJson = path.join(root, 'package.json');
293
+ const pomXml = path.join(root, 'pom.xml');
294
+ if (fs.existsSync(cargoToml) && fs.existsSync(cargoLock)) {
295
+ return { ecosystem: 'cargo', manifestPaths: await discoverWorkspaceCrates(root, opts) };
296
+ }
297
+ if (fs.existsSync(pomXml)) {
298
+ const manifestPaths = await discoverMavenModules(root, opts);
299
+ if (manifestPaths.length > 0) {
300
+ return { ecosystem: 'maven', manifestPaths };
301
+ }
302
+ }
303
+ const hasGradleSettings = fs.existsSync(path.join(root, 'settings.gradle'))
304
+ || fs.existsSync(path.join(root, 'settings.gradle.kts'));
305
+ if (hasGradleSettings) {
306
+ const manifestPaths = await discoverGradleSubprojects(root, opts);
307
+ if (manifestPaths.length > 0) {
308
+ return { ecosystem: 'gradle', manifestPaths };
309
+ }
310
+ }
311
+ if (fs.existsSync(path.join(root, 'go.work'))) {
312
+ const manifestPaths = await discoverGoWorkspaceModules(root, opts);
313
+ if (manifestPaths.length > 0) {
314
+ return { ecosystem: 'gomodules', manifestPaths };
315
+ }
316
+ }
317
+ if (fs.existsSync(path.join(root, 'pyproject.toml')) && fs.existsSync(path.join(root, 'uv.lock'))) {
318
+ const manifestPaths = await discoverUvWorkspaceMembers(root, opts);
319
+ if (manifestPaths.length > 0) {
320
+ return { ecosystem: 'pyproject', manifestPaths };
321
+ }
322
+ }
323
+ const hasJsLock = fs.existsSync(path.join(root, 'bun.lock'))
324
+ || fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
325
+ || fs.existsSync(path.join(root, 'yarn.lock'))
326
+ || fs.existsSync(path.join(root, 'package-lock.json'));
327
+ if (fs.existsSync(packageJson) && hasJsLock) {
328
+ let manifestPaths = await discoverWorkspacePackages(root, opts);
329
+ if (manifestPaths.length === 0) {
330
+ manifestPaths = [packageJson];
331
+ }
332
+ return { ecosystem: 'javascript', manifestPaths };
333
+ }
334
+ return { ecosystem: 'unknown', manifestPaths: [] };
335
+ }
336
+ /**
337
+ * Validate discovered JS package.json manifests, collecting errors.
338
+ *
339
+ * @param {string[]} manifestPaths
340
+ * @param {boolean} continueOnError
341
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
342
+ * @returns {{ validPaths: string[] }}
343
+ * @throws {Error} on first invalid manifest when `continueOnError` is false
344
+ * @private
345
+ */
346
+ function validateJsManifests(manifestPaths, continueOnError, collectedErrors) {
347
+ const validPaths = [];
348
+ for (const p of manifestPaths) {
349
+ const v = validatePackageJson(p);
350
+ if (v.valid) {
351
+ validPaths.push(p);
352
+ }
353
+ else {
354
+ collectedErrors.push({ manifestPath: p, phase: 'validation', reason: v.error });
355
+ console.warn(`Skipping invalid package.json (${v.error}): ${p}`);
356
+ if (!continueOnError) {
357
+ throw new Error(`Invalid package.json (${v.error}): ${p}`);
358
+ }
359
+ }
360
+ }
361
+ return { validPaths };
362
+ }
363
+ /**
364
+ * Generate SBOMs for all manifests. In fail-fast mode, stops on first error.
365
+ * In continue-on-error mode, runs concurrently and collects failures.
366
+ *
367
+ * @param {string[]} manifestPaths
368
+ * @param {Options} workspaceOpts
369
+ * @param {boolean} continueOnError
370
+ * @param {number} concurrency
371
+ * @param {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} collectedErrors - mutated in place
372
+ * @returns {Promise<Object.<string, object>>} sbomByPurl map
373
+ * @throws {Error} on first SBOM failure when `continueOnError` is false
374
+ * @private
375
+ */
376
+ async function generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors) {
377
+ /** @type {SbomResult[]} */
378
+ const results = [];
379
+ if (!continueOnError) {
380
+ for (const manifestPath of manifestPaths) {
381
+ const result = await generateOneSbom(manifestPath, workspaceOpts);
382
+ if (!result.ok) {
383
+ collectedErrors.push({ manifestPath: result.manifestPath, phase: 'sbom', reason: result.reason });
384
+ throw new Error(`${result.manifestPath}: ${result.reason}`);
385
+ }
386
+ results.push(result);
387
+ }
388
+ }
389
+ else {
390
+ const limit = pLimit(concurrency);
391
+ const settled = await Promise.all(manifestPaths.map(manifestPath => limit(async () => {
392
+ try {
393
+ return await generateOneSbom(manifestPath, workspaceOpts);
394
+ }
395
+ catch (err) {
396
+ const msg = err instanceof Error ? err.message : String(err);
397
+ if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
398
+ console.log(`Skipping ${manifestPath}: ${msg}`);
399
+ }
400
+ return { ok: false, manifestPath, reason: msg };
401
+ }
402
+ })));
403
+ for (const r of settled) {
404
+ results.push(r);
405
+ if (!r.ok) {
406
+ collectedErrors.push({ manifestPath: r.manifestPath, phase: 'sbom', reason: r.reason });
407
+ }
408
+ }
409
+ }
410
+ const sbomByPurl = {};
411
+ for (const r of results) {
412
+ if (r.ok) {
413
+ sbomByPurl[r.purl] = r.sbom;
414
+ }
415
+ }
416
+ return sbomByPurl;
417
+ }
418
+ /**
419
+ * Create an Error with optional `batchMetadata` attached.
420
+ * @param {string} message
421
+ * @param {boolean} wantMetadata
422
+ * @param {BatchAnalysisMetadata} [metadata]
423
+ * @returns {Error}
424
+ * @private
425
+ */
426
+ function batchError(message, wantMetadata, metadata) {
427
+ const err = new Error(message);
428
+ if (wantMetadata && metadata) {
429
+ err.batchMetadata = metadata;
430
+ }
431
+ return err;
432
+ }
433
+ /**
434
+ * @overload
435
+ * @param {string} workspaceRoot
436
+ * @param {true} html
437
+ * @param {Options & { batchMetadata: true }} opts
438
+ * @returns {Promise<{ analysis: string, metadata: BatchAnalysisMetadata }>}
439
+ * @throws {Error}
440
+ */
441
+ /**
442
+ * @overload
443
+ * @param {string} workspaceRoot
444
+ * @param {true} html
445
+ * @param {Options & { batchMetadata?: false }} [opts={}]
446
+ * @returns {Promise<string>}
447
+ * @throws {Error}
448
+ */
449
+ /**
450
+ * @overload
451
+ * @param {string} workspaceRoot
452
+ * @param {false} html
453
+ * @param {Options & { batchMetadata: true }} opts
454
+ * @returns {Promise<{ analysis: Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>, metadata: BatchAnalysisMetadata }>}
455
+ * @throws {Error}
456
+ */
457
+ /**
458
+ * @overload
459
+ * @param {string} workspaceRoot
460
+ * @param {false} html
461
+ * @param {Options & { batchMetadata?: false }} [opts={}]
462
+ * @returns {Promise<Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
463
+ * @throws {Error}
464
+ */
465
+ /**
466
+ * Get stack analysis for all workspace packages/crates (batch).
467
+ * Detects ecosystem from workspace root: Cargo (Cargo.toml + Cargo.lock) or JS/TS (package.json + lock file).
468
+ * SBOMs are generated in parallel (see `batchConcurrency`) unless `continueOnError: false` (fail-fast sequential).
469
+ * With `opts.batchMetadata` / `TRUSTIFY_DA_BATCH_METADATA`, returns `{ analysis, metadata }` including validation and SBOM errors.
470
+ *
471
+ * @overload
472
+ * @param {string} workspaceRoot - Path to workspace root (containing lock file and workspace config)
473
+ * @param {boolean} [html=false] - true returns HTML, false returns JSON report
474
+ * @param {Options} [opts={}] - `batchConcurrency`, discovery ignores, `continueOnError` (default true), `batchMetadata` (default false)
475
+ * @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 }>}
476
+ * @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.
477
+ */
478
+ async function stackAnalysisBatch(workspaceRoot, html = false, opts = {}) {
479
+ const theUrl = selectTrustifyDABackend(opts);
480
+ const root = path.resolve(workspaceRoot);
481
+ fs.accessSync(root, fs.constants.R_OK);
482
+ const continueOnError = resolveContinueOnError(opts);
483
+ const wantMetadata = resolveBatchMetadata(opts);
484
+ /** @type {Array<{ manifestPath: string, phase: 'validation' | 'sbom', reason: string }>} */
485
+ const collectedErrors = [];
486
+ const { ecosystem, manifestPaths: discovered } = await detectWorkspaceManifests(root, opts);
487
+ let manifestPaths = discovered;
488
+ if (ecosystem === 'javascript') {
489
+ try {
490
+ const { validPaths } = validateJsManifests(manifestPaths, continueOnError, collectedErrors);
491
+ manifestPaths = validPaths;
492
+ }
493
+ catch (err) {
494
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
495
+ }
496
+ if (manifestPaths.length === 0 && discovered.length > 0) {
497
+ const detail = collectedErrors.map(e => `${e.manifestPath}: ${e.reason}`).join('; ');
498
+ throw batchError(`No valid packages after validation at ${root}. ${detail}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, 0, 0, collectedErrors));
499
+ }
500
+ }
501
+ if (manifestPaths.length === 0) {
502
+ 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).`);
503
+ }
504
+ const workspaceOpts = { ...opts, TRUSTIFY_DA_WORKSPACE_DIR: root };
505
+ const concurrency = resolveBatchConcurrency(opts);
506
+ let sbomByPurl;
507
+ try {
508
+ sbomByPurl = await generateSboms(manifestPaths, workspaceOpts, continueOnError, concurrency, collectedErrors);
509
+ }
510
+ catch (err) {
511
+ throw batchError(err.message, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
512
+ }
513
+ if (Object.keys(sbomByPurl).length === 0) {
514
+ throw batchError(`No valid SBOMs produced from ${manifestPaths.length} manifest(s) at ${root}`, wantMetadata, buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, 0, collectedErrors));
515
+ }
516
+ const analysisResult = await analysis.requestStackBatch(sbomByPurl, theUrl, html, opts);
517
+ const meta = buildBatchAnalysisMetadata(root, ecosystem, manifestPaths.length, Object.keys(sbomByPurl).length, collectedErrors);
518
+ if (wantMetadata) {
519
+ return { analysis: analysisResult, metadata: meta };
520
+ }
521
+ return analysisResult;
522
+ }
177
523
  /**
178
524
  * Validates the Exhort token.
179
525
  * @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";