@trustify-da/trustify-da-javascript-client 0.3.0-ea.1d590b2 → 0.3.0-ea.212178e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/package.json CHANGED
@@ -51,11 +51,11 @@
51
51
  "@cyclonedx/cyclonedx-library": "^6.13.0",
52
52
  "eslint-import-resolver-typescript": "^4.4.4",
53
53
  "fast-glob": "^3.3.3",
54
- "fast-toml": "^0.5.4",
55
54
  "fast-xml-parser": "^5.3.4",
56
55
  "help": "^3.0.2",
57
56
  "https-proxy-agent": "^7.0.6",
58
57
  "js-yaml": "^4.1.1",
58
+ "jsonc-parser": "^3.3.1",
59
59
  "micromatch": "^4.0.8",
60
60
  "node-fetch": "^3.3.2",
61
61
  "p-limit": "^4.0.0",
@@ -80,7 +80,7 @@ export type Options = {
80
80
  };
81
81
  export type BatchAnalysisMetadata = {
82
82
  workspaceRoot: string;
83
- ecosystem: "javascript" | "cargo" | "unknown";
83
+ ecosystem: "javascript" | "cargo" | "pyproject" | "unknown";
84
84
  total: number;
85
85
  successful: number;
86
86
  failed: number;
@@ -253,6 +253,8 @@ declare function imageAnalysis(imageRefs: Array<string>, html?: boolean | undefi
253
253
  declare function validateToken(opts?: Options): Promise<object>;
254
254
  import { discoverMavenModules } from './providers/java_maven.js';
255
255
  import { discoverGradleSubprojects } from './providers/java_gradle.js';
256
+ import { discoverGoWorkspaceModules } from './providers/golang_gomodules.js';
257
+ import { discoverUvWorkspaceMembers } from './providers/python_uv.js';
256
258
  import { discoverWorkspacePackages } from './workspace.js';
257
259
  import { discoverWorkspaceCrates } from './workspace.js';
258
260
  import { validatePackageJson } from './workspace.js';
@@ -260,5 +262,5 @@ import { resolveWorkspaceDiscoveryIgnore } from './workspace.js';
260
262
  import { filterManifestPathsByDiscoveryIgnore } from './workspace.js';
261
263
  import { resolveContinueOnError } from './batch_opts.js';
262
264
  import { resolveBatchMetadata } from './batch_opts.js';
263
- export { discoverMavenModules, discoverGradleSubprojects, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata };
265
+ export { discoverMavenModules, discoverGradleSubprojects, discoverGoWorkspaceModules, discoverUvWorkspaceMembers, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata };
264
266
  export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
package/dist/src/index.js CHANGED
@@ -8,6 +8,8 @@ import { getCustom } from "./tools.js";
8
8
  import { resolveBatchMetadata, resolveContinueOnError } from './batch_opts.js';
9
9
  import { discoverMavenModules } from './providers/java_maven.js';
10
10
  import { discoverGradleSubprojects } from './providers/java_gradle.js';
11
+ import { discoverGoWorkspaceModules } from './providers/golang_gomodules.js';
12
+ import { discoverUvWorkspaceMembers } from './providers/python_uv.js';
11
13
  import { discoverWorkspaceCrates, discoverWorkspacePackages, filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, validatePackageJson, } from './workspace.js';
12
14
  import.meta.dirname;
13
15
  import * as url from 'url';
@@ -15,7 +17,7 @@ export { parseImageRef } from "./oci_image/utils.js";
15
17
  export { ImageRef } from "./oci_image/images.js";
16
18
  export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
17
19
  export default { componentAnalysis, stackAnalysis, stackAnalysisBatch, imageAnalysis, validateToken, generateSbom };
18
- export { discoverMavenModules, discoverGradleSubprojects, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
20
+ export { discoverMavenModules, discoverGradleSubprojects, discoverGoWorkspaceModules, discoverUvWorkspaceMembers, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
19
21
  /**
20
22
  * @typedef {{
21
23
  * TRUSTIFY_DA_CARGO_PATH?: string | undefined,
@@ -66,7 +68,7 @@ export { discoverMavenModules, discoverGradleSubprojects, discoverWorkspacePacka
66
68
  /**
67
69
  * @typedef {{
68
70
  * workspaceRoot: string,
69
- * ecosystem: 'javascript' | 'cargo' | 'unknown',
71
+ * ecosystem: 'javascript' | 'cargo' | 'pyproject' | 'unknown',
70
72
  * total: number,
71
73
  * successful: number,
72
74
  * failed: number,
@@ -173,7 +175,9 @@ async function componentAnalysis(manifest, opts = {}) {
173
175
  fs.accessSync(manifest, fs.constants.R_OK);
174
176
  opts["manifest-type"] = path.basename(manifest);
175
177
  let provider = match(manifest, availableProviders, opts); // throws error if no matching provider
176
- return await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
178
+ const result = await analysis.requestComponent(provider, manifest, theUrl, opts); // throws error request sending failed
179
+ result.packageManager = provider.packageManagerName();
180
+ return result;
177
181
  }
178
182
  /**
179
183
  * @overload
@@ -281,7 +285,7 @@ async function generateOneSbom(manifestPath, workspaceOpts) {
281
285
  *
282
286
  * @param {string} root - Resolved workspace root
283
287
  * @param {Options} opts
284
- * @returns {Promise<{ ecosystem: 'javascript' | 'cargo' | 'maven' | 'gradle' | 'unknown', manifestPaths: string[] }>}
288
+ * @returns {Promise<{ ecosystem: 'javascript' | 'cargo' | 'maven' | 'gradle' | 'gomodules' | 'pyproject' | 'unknown', manifestPaths: string[] }>}
285
289
  * @private
286
290
  */
287
291
  async function detectWorkspaceManifests(root, opts) {
@@ -306,7 +310,20 @@ async function detectWorkspaceManifests(root, opts) {
306
310
  return { ecosystem: 'gradle', manifestPaths };
307
311
  }
308
312
  }
309
- const hasJsLock = fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
313
+ if (fs.existsSync(path.join(root, 'go.work'))) {
314
+ const manifestPaths = await discoverGoWorkspaceModules(root, opts);
315
+ if (manifestPaths.length > 0) {
316
+ return { ecosystem: 'gomodules', manifestPaths };
317
+ }
318
+ }
319
+ if (fs.existsSync(path.join(root, 'pyproject.toml')) && fs.existsSync(path.join(root, 'uv.lock'))) {
320
+ const manifestPaths = await discoverUvWorkspaceMembers(root, opts);
321
+ if (manifestPaths.length > 0) {
322
+ return { ecosystem: 'pyproject', manifestPaths };
323
+ }
324
+ }
325
+ const hasJsLock = fs.existsSync(path.join(root, 'bun.lock'))
326
+ || fs.existsSync(path.join(root, 'pnpm-lock.yaml'))
310
327
  || fs.existsSync(path.join(root, 'yarn.lock'))
311
328
  || fs.existsSync(path.join(root, 'package-lock.json'));
312
329
  if (fs.existsSync(packageJson) && hasJsLock) {
@@ -484,7 +501,7 @@ async function stackAnalysisBatch(workspaceRoot, html = false, opts = {}) {
484
501
  }
485
502
  }
486
503
  if (manifestPaths.length === 0) {
487
- throw new Error(`No workspace manifests found at ${root}. Ensure Cargo.toml+Cargo.lock or package.json+lock file exist.`);
504
+ 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).`);
488
505
  }
489
506
  const workspaceOpts = { ...opts, TRUSTIFY_DA_WORKSPACE_DIR: root };
490
507
  const concurrency = resolveBatchConcurrency(opts);
@@ -21,7 +21,7 @@ export function match(manifest: string, providers: [Provider], opts?: {
21
21
  TRUSTIFY_DA_WORKSPACE_DIR?: string;
22
22
  }): Provider;
23
23
  /** @typedef {{ecosystem: string, contentType: string, content: string}} Provided */
24
- /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string, Object): void, provideComponent: function(string, {}): Provided | Promise<Provided>, provideStack: function(string, {}): Provided | Promise<Provided>, readLicenseFromManifest: function(string): string | null}} Provider */
24
+ /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string, Object): void, provideComponent: function(string, {}): Provided | Promise<Provided>, provideStack: function(string, {}): Provided | Promise<Provided>, readLicenseFromManifest: function(string): string | null, packageManagerName: function(): string}} Provider */
25
25
  /**
26
26
  * MUST include all providers here.
27
27
  * @type {[Provider]}
@@ -38,4 +38,5 @@ export type Provider = {
38
38
  provideComponent: (arg0: string, arg1: {}) => Provided | Promise<Provided>;
39
39
  provideStack: (arg0: string, arg1: {}) => Provided | Promise<Provided>;
40
40
  readLicenseFromManifest: (arg0: string) => string | null;
41
+ packageManagerName: () => string;
41
42
  };
@@ -3,6 +3,7 @@ import golangGomodulesProvider from './providers/golang_gomodules.js';
3
3
  import Java_gradle_groovy from "./providers/java_gradle_groovy.js";
4
4
  import Java_gradle_kotlin from "./providers/java_gradle_kotlin.js";
5
5
  import Java_maven from "./providers/java_maven.js";
6
+ import Javascript_bun from './providers/javascript_bun.js';
6
7
  import Javascript_npm from './providers/javascript_npm.js';
7
8
  import Javascript_pnpm from './providers/javascript_pnpm.js';
8
9
  import Javascript_yarn from './providers/javascript_yarn.js';
@@ -12,7 +13,7 @@ import Python_poetry from './providers/python_poetry.js';
12
13
  import Python_uv from './providers/python_uv.js';
13
14
  import rustCargoProvider from './providers/rust_cargo.js';
14
15
  /** @typedef {{ecosystem: string, contentType: string, content: string}} Provided */
15
- /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string, Object): void, provideComponent: function(string, {}): Provided | Promise<Provided>, provideStack: function(string, {}): Provided | Promise<Provided>, readLicenseFromManifest: function(string): string | null}} Provider */
16
+ /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string, Object): void, provideComponent: function(string, {}): Provided | Promise<Provided>, provideStack: function(string, {}): Provided | Promise<Provided>, readLicenseFromManifest: function(string): string | null, packageManagerName: function(): string}} Provider */
16
17
  /**
17
18
  * MUST include all providers here.
18
19
  * @type {[Provider]}
@@ -21,6 +22,7 @@ export const availableProviders = [
21
22
  new Java_maven(),
22
23
  new Java_gradle_groovy(),
23
24
  new Java_gradle_kotlin(),
25
+ new Javascript_bun(),
24
26
  new Javascript_pnpm(),
25
27
  new Javascript_yarn(),
26
28
  new Javascript_npm(),
@@ -20,6 +20,11 @@ export default class Base_Java {
20
20
  CONFLICT_REGEX: RegExp;
21
21
  globalBinary: string;
22
22
  localWrapper: string;
23
+ /**
24
+ * Returns the package manager name (e.g. mvn, gradle)
25
+ * @returns {string}
26
+ */
27
+ packageManagerName(): string;
23
28
  /**
24
29
  * Recursively populates the SBOM instance with the parsed graph
25
30
  * @param {string} src - Source dependency to start the calculations from
@@ -25,6 +25,13 @@ export default class Base_Java {
25
25
  this.globalBinary = globalBinary;
26
26
  this.localWrapper = localWrapper;
27
27
  }
28
+ /**
29
+ * Returns the package manager name (e.g. mvn, gradle)
30
+ * @returns {string}
31
+ */
32
+ packageManagerName() {
33
+ return this.globalBinary;
34
+ }
28
35
  /**
29
36
  * Recursively populates the SBOM instance with the parsed graph
30
37
  * @param {string} src - Source dependency to start the calculations from
@@ -47,6 +47,11 @@ export default class Base_javascript {
47
47
  */
48
48
  protected _cmdName(): string;
49
49
  /**
50
+ * Returns the package manager name (e.g. npm, yarn, pnpm, bun)
51
+ * @returns {string} The package manager name
52
+ */
53
+ packageManagerName(): string;
54
+ /**
50
55
  * Returns the command arguments for listing dependencies
51
56
  * @returns {Array<string>} The command arguments
52
57
  * @abstract
@@ -136,6 +141,12 @@ export default class Base_javascript {
136
141
  */
137
142
  protected _version(): string;
138
143
  /**
144
+ * Creates or updates the lock file for the package manager
145
+ * @param {string} manifestDir - Directory containing the manifest file
146
+ * @protected
147
+ */
148
+ protected _createLockFile(manifestDir: string): void;
149
+ /**
139
150
  * Parses the dependency tree output
140
151
  * @param {string} output - The output to parse
141
152
  * @returns {string} The parsed output
@@ -71,6 +71,13 @@ export default class Base_javascript {
71
71
  throw new TypeError("_cmdName must be implemented");
72
72
  }
73
73
  /**
74
+ * Returns the package manager name (e.g. npm, yarn, pnpm, bun)
75
+ * @returns {string} The package manager name
76
+ */
77
+ packageManagerName() {
78
+ return this._cmdName();
79
+ }
80
+ /**
74
81
  * Returns the command arguments for listing dependencies
75
82
  * @returns {Array<string>} The command arguments
76
83
  * @abstract
@@ -217,7 +224,7 @@ export default class Base_javascript {
217
224
  this._version();
218
225
  const manifestDir = path.dirname(this.#manifest.manifestPath);
219
226
  const cmdDir = this._findLockFileDir(manifestDir, opts) || manifestDir;
220
- this.#createLockFile(cmdDir);
227
+ this._createLockFile(cmdDir);
221
228
  let output = this.#executeListCmd(includeTransitive, cmdDir);
222
229
  output = this._parseDepTreeOutput(output);
223
230
  return JSON.parse(output);
@@ -363,9 +370,9 @@ export default class Base_javascript {
363
370
  /**
364
371
  * Creates or updates the lock file for the package manager
365
372
  * @param {string} manifestDir - Directory containing the manifest file
366
- * @private
373
+ * @protected
367
374
  */
368
- #createLockFile(manifestDir) {
375
+ _createLockFile(manifestDir) {
369
376
  const originalDir = process.cwd();
370
377
  const isWindows = os.platform() === 'win32';
371
378
  if (isWindows) {
@@ -61,6 +61,11 @@ export default class Base_pyproject {
61
61
  * @protected
62
62
  */
63
63
  protected _cmdName(): string;
64
+ /**
65
+ * Returns the package manager name (e.g. pip, poetry, uv)
66
+ * @returns {string}
67
+ */
68
+ packageManagerName(): string;
64
69
  /**
65
70
  * Resolve dependencies using the tool-specific command and parser.
66
71
  *
@@ -145,6 +145,13 @@ export default class Base_pyproject {
145
145
  _cmdName() {
146
146
  throw new TypeError('_cmdName must be implemented');
147
147
  }
148
+ /**
149
+ * Returns the package manager name (e.g. pip, poetry, uv)
150
+ * @returns {string}
151
+ */
152
+ packageManagerName() {
153
+ return this._cmdName();
154
+ }
148
155
  /**
149
156
  * Resolve dependencies using the tool-specific command and parser.
150
157
  *
@@ -1,9 +1,19 @@
1
+ /**
2
+ * Discover all go.mod manifest paths in a Go workspace.
3
+ * Uses `go work edit -json` to get workspace members.
4
+ *
5
+ * @param {string} workspaceRoot - Absolute or relative path to workspace root (must contain go.work)
6
+ * @param {import('../index.js').Options} [opts={}]
7
+ * @returns {Promise<string[]>} Paths to go.mod files (absolute)
8
+ */
9
+ export function discoverGoWorkspaceModules(workspaceRoot: string, opts?: import("../index.js").Options): Promise<string[]>;
1
10
  declare namespace _default {
2
11
  export { isSupported };
3
12
  export { validateLockFile };
4
13
  export { provideComponent };
5
14
  export { provideStack };
6
15
  export { readLicenseFromManifest };
16
+ export function packageManagerName(): string;
7
17
  }
8
18
  export default _default;
9
19
  export type Provided = import("../provider").Provided;
@@ -4,8 +4,9 @@ import { PackageURL } from 'packageurl-js';
4
4
  import { readLicenseFile } from '../license/license_utils.js';
5
5
  import Sbom from '../sbom.js';
6
6
  import { getCustom, getCustomPath, invokeCommand } from "../tools.js";
7
+ import { filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore } from '../workspace.js';
7
8
  import { getParser, getRequireQuery } from './gomod_parser.js';
8
- export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest };
9
+ export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest, packageManagerName() { return 'go'; } };
9
10
  /** @typedef {import('../provider').Provider} */
10
11
  /** @typedef {import('../provider').Provided} Provided */
11
12
  /** @typedef {{name: string, version: string}} Package */
@@ -328,13 +329,7 @@ function getFinalPackagesVersionsForModule(rows, manifestPath, goBin) {
328
329
  catch (error) {
329
330
  throw new Error('failed to list all modules', { cause: error });
330
331
  }
331
- let finalVersionModules = new Map();
332
- finalVersionsForAllModules.split(getLineSeparatorGolang()).filter(string => string.trim() !== "")
333
- .filter(string => string.trim().split(" ").length === 2)
334
- .forEach((dependency) => {
335
- let dep = dependency.split(" ");
336
- finalVersionModules[dep[0]] = dep[1];
337
- });
332
+ let finalVersionModules = parseModuleVersions(finalVersionsForAllModules);
338
333
  let finalVersionModulesArray = new Array();
339
334
  rows.filter(string => string.trim() !== "").forEach(module => {
340
335
  let child = getChildVertexFromEdge(module);
@@ -395,7 +390,69 @@ function getVersionOfPackage(fullPackage) {
395
390
  let parts = fullPackage.split("@");
396
391
  return parts.length > 1 ? parts[1] : undefined;
397
392
  }
393
+ function parseModuleVersions(goListOutput) {
394
+ let modules = {};
395
+ goListOutput.split(getLineSeparatorGolang()).filter(string => string.trim() !== "")
396
+ .forEach((line) => {
397
+ let parts = line.trim().split(" ");
398
+ if (parts.length === 2) {
399
+ modules[parts[0]] = parts[1];
400
+ }
401
+ else if (parts.length >= 4 && parts[2] === "=>") {
402
+ modules[parts[0]] = parts[parts.length - 1];
403
+ }
404
+ });
405
+ return modules;
406
+ }
398
407
  function getLineSeparatorGolang() {
399
408
  let reg = /\n|\r\n/;
400
409
  return reg;
401
410
  }
411
+ /**
412
+ * Discover all go.mod manifest paths in a Go workspace.
413
+ * Uses `go work edit -json` to get workspace members.
414
+ *
415
+ * @param {string} workspaceRoot - Absolute or relative path to workspace root (must contain go.work)
416
+ * @param {import('../index.js').Options} [opts={}]
417
+ * @returns {Promise<string[]>} Paths to go.mod files (absolute)
418
+ */
419
+ export async function discoverGoWorkspaceModules(workspaceRoot, opts = {}) {
420
+ const root = path.resolve(workspaceRoot);
421
+ const goWork = path.join(root, 'go.work');
422
+ if (!fs.existsSync(goWork)) {
423
+ return [];
424
+ }
425
+ const goBin = getCustomPath('go', opts);
426
+ let output;
427
+ try {
428
+ output = invokeCommand(goBin, ['work', 'edit', '-json', goWork], { cwd: root });
429
+ }
430
+ catch {
431
+ return [];
432
+ }
433
+ let workspace;
434
+ try {
435
+ workspace = JSON.parse(output.toString().trim());
436
+ }
437
+ catch {
438
+ return [];
439
+ }
440
+ const useEntries = workspace.Use || [];
441
+ if (useEntries.length === 0) {
442
+ return [];
443
+ }
444
+ const manifestPaths = [];
445
+ for (const entry of useEntries) {
446
+ const diskPath = entry.DiskPath;
447
+ if (!diskPath) {
448
+ continue;
449
+ }
450
+ const moduleDir = path.resolve(root, diskPath);
451
+ const goMod = path.join(moduleDir, 'go.mod');
452
+ if (fs.existsSync(goMod)) {
453
+ manifestPaths.push(goMod);
454
+ }
455
+ }
456
+ const ignorePatterns = resolveWorkspaceDiscoveryIgnore(opts);
457
+ return filterManifestPathsByDiscoveryIgnore(manifestPaths, root, ignorePatterns);
458
+ }
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { EOL } from 'os';
6
- import TOML from 'fast-toml';
6
+ import { parse as parseToml } from 'smol-toml';
7
7
  import { readLicenseFile } from '../license/license_utils.js';
8
8
  import Sbom from '../sbom.js';
9
9
  import { invokeCommand } from '../tools.js';
@@ -366,7 +366,7 @@ export default class Java_gradle extends Base_java {
366
366
  // Read and parse the TOML file
367
367
  let pathOfToml = path.join(path.dirname(manifestPath), "gradle", "libs.versions.toml");
368
368
  const tomlString = fs.readFileSync(pathOfToml).toString();
369
- let tomlObject = TOML.parse(tomlString);
369
+ let tomlObject = parseToml(tomlString);
370
370
  let groupPlusArtifactObject = tomlObject.libraries[alias];
371
371
  let parts = groupPlusArtifactObject.module.split(":");
372
372
  let groupId = parts[0];
@@ -0,0 +1,10 @@
1
+ export default class Javascript_bun extends Base_javascript {
2
+ _listCmdArgs(): void;
3
+ _buildDependencyTree(includeTransitive: any, opts?: {}): {
4
+ name: any;
5
+ version: any;
6
+ dependencies: {};
7
+ };
8
+ #private;
9
+ }
10
+ import Base_javascript from './base_javascript.js';
@@ -0,0 +1,100 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse } from 'jsonc-parser';
4
+ import Base_javascript from './base_javascript.js';
5
+ export default class Javascript_bun extends Base_javascript {
6
+ _lockFileName() {
7
+ return "bun.lock";
8
+ }
9
+ _cmdName() {
10
+ return "bun";
11
+ }
12
+ _listCmdArgs() {
13
+ throw new Error("not supported by Bun");
14
+ }
15
+ _updateLockFileCmdArgs() {
16
+ return ['install', '--lockfile-only'];
17
+ }
18
+ _buildDependencyTree(includeTransitive, opts = {}) {
19
+ this._version();
20
+ const manifestDir = path.dirname(this._getManifest().manifestPath);
21
+ const lockDir = this._findLockFileDir(manifestDir, opts) || manifestDir;
22
+ this._createLockFile(lockDir);
23
+ const lockContent = fs.readFileSync(path.join(lockDir, 'bun.lock'), 'utf-8');
24
+ const lockData = parse(lockContent);
25
+ const packages = lockData.packages || {};
26
+ const memberName = this._getManifest().name;
27
+ const workspaceEntry = this.#findWorkspaceEntry(lockData, lockDir, manifestDir, memberName);
28
+ const directDeps = workspaceEntry?.dependencies || {};
29
+ const tree = { name: memberName, version: this._getManifest().version, dependencies: {} };
30
+ const visited = new Set();
31
+ for (const depName of Object.keys(directDeps)) {
32
+ const resolved = this.#resolvePackage(depName, '', packages);
33
+ if (resolved) {
34
+ tree.dependencies[depName] = this.#buildNode(depName, resolved, packages, includeTransitive, visited);
35
+ }
36
+ }
37
+ return tree;
38
+ }
39
+ #findWorkspaceEntry(lockData, lockDir, manifestDir, memberName) {
40
+ const workspaces = lockData.workspaces || {};
41
+ const relPath = path.relative(lockDir, path.resolve(manifestDir));
42
+ if (!relPath || relPath === '.') {
43
+ return workspaces[''] || {};
44
+ }
45
+ const normalised = relPath.split(path.sep).join('/');
46
+ if (workspaces[normalised]) {
47
+ return workspaces[normalised];
48
+ }
49
+ for (const [wsPath, entry] of Object.entries(workspaces)) {
50
+ if (entry.name === memberName && wsPath !== '') {
51
+ return entry;
52
+ }
53
+ }
54
+ return workspaces[''] || {};
55
+ }
56
+ #resolvePackage(depName, parentKey, packages) {
57
+ if (parentKey) {
58
+ const scopedKey = `${parentKey}/${depName}`;
59
+ if (packages[scopedKey]) {
60
+ return packages[scopedKey];
61
+ }
62
+ }
63
+ return packages[depName] || null;
64
+ }
65
+ #buildNode(depName, resolved, packages, includeTransitive, visited) {
66
+ const resolvedId = Array.isArray(resolved) ? resolved[0] : resolved;
67
+ const version = this.#extractVersion(resolvedId);
68
+ const node = { version };
69
+ if (!includeTransitive) {
70
+ return node;
71
+ }
72
+ const metadata = Array.isArray(resolved) ? (resolved[2] || {}) : {};
73
+ const subDeps = metadata.dependencies || {};
74
+ if (Object.keys(subDeps).length > 0) {
75
+ const visitKey = `${depName}@${version}`;
76
+ if (visited.has(visitKey)) {
77
+ return node;
78
+ }
79
+ visited.add(visitKey);
80
+ node.dependencies = {};
81
+ for (const subName of Object.keys(subDeps)) {
82
+ const subResolved = this.#resolvePackage(subName, depName, packages);
83
+ if (subResolved) {
84
+ node.dependencies[subName] = this.#buildNode(subName, subResolved, packages, true, visited);
85
+ }
86
+ }
87
+ }
88
+ return node;
89
+ }
90
+ #extractVersion(resolvedId) {
91
+ if (typeof resolvedId !== 'string') {
92
+ return '0.0.0';
93
+ }
94
+ const atIdx = resolvedId.lastIndexOf('@');
95
+ if (atIdx > 0) {
96
+ return resolvedId.substring(atIdx + 1);
97
+ }
98
+ return '0.0.0';
99
+ }
100
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Maps Node.js/OS values to PEP 508 marker variables.
3
+ * Example: on Linux, sys_platform='linux', platform_system='Linux', os_name='posix'
4
+ * @returns {Record<string, string>}
5
+ */
6
+ export function getEnvironmentMarkers(): Record<string, string>;
7
+ /**
8
+ * Evaluates a full PEP 508 marker expression against the current platform.
9
+ * Example: "sys_platform == 'win32' and python_version >= '3.8'" → false on Linux
10
+ * Empty/missing markers return true (unconditional dependency).
11
+ * @param {string} markerExpr
12
+ * @returns {boolean}
13
+ */
14
+ export function evaluateMarker(markerExpr: string): boolean;
@@ -0,0 +1,191 @@
1
+ // PEP 508 environment marker evaluator.
2
+ // Filters Python dependencies by platform/version markers so that e.g.
3
+ // "pywin32 ; sys_platform == 'win32'" is excluded on Linux/macOS.
4
+ // See https://peps.python.org/pep-0508/#environment-markers
5
+ import os from 'node:os';
6
+ import { getCustomPath, invokeCommand } from '../tools.js';
7
+ let cachedPythonVersions = undefined;
8
+ function getPythonVersions() {
9
+ if (cachedPythonVersions !== undefined) {
10
+ return cachedPythonVersions;
11
+ }
12
+ try {
13
+ let python = getCustomPath('python3');
14
+ let out = invokeCommand(python, ['-c', "import sys; v=sys.version_info; print(f'{v.major}.{v.minor} {v.major}.{v.minor}.{v.micro}')"], { timeout: 5000 }).toString().trim();
15
+ let [short, full] = out.split(' ');
16
+ cachedPythonVersions = { short, full };
17
+ }
18
+ catch {
19
+ cachedPythonVersions = null;
20
+ }
21
+ return cachedPythonVersions;
22
+ }
23
+ /**
24
+ * Maps Node.js/OS values to PEP 508 marker variables.
25
+ * Example: on Linux, sys_platform='linux', platform_system='Linux', os_name='posix'
26
+ * @returns {Record<string, string>}
27
+ */
28
+ export function getEnvironmentMarkers() {
29
+ let platform = process.platform;
30
+ let systemMap = { win32: 'Windows', linux: 'Linux', darwin: 'Darwin' };
31
+ let machine = typeof os.machine === 'function' ? os.machine() : process.arch;
32
+ let pyVer = getPythonVersions();
33
+ return {
34
+ sys_platform: platform,
35
+ platform_system: systemMap[platform] || platform,
36
+ os_name: platform === 'win32' ? 'nt' : 'posix',
37
+ platform_machine: machine,
38
+ platform_release: os.release(),
39
+ platform_version: os.version?.() || '',
40
+ python_version: pyVer?.short || '',
41
+ python_full_version: pyVer?.full || '',
42
+ implementation_name: 'cpython',
43
+ };
44
+ }
45
+ function compareVersions(left, right) {
46
+ let lParts = left.split('.').map(Number);
47
+ let rParts = right.split('.').map(Number);
48
+ let len = Math.max(lParts.length, rParts.length);
49
+ for (let i = 0; i < len; i++) {
50
+ let l = lParts[i] || 0;
51
+ let r = rParts[i] || 0;
52
+ if (l < r) {
53
+ return -1;
54
+ }
55
+ if (l > r) {
56
+ return 1;
57
+ }
58
+ }
59
+ return 0;
60
+ }
61
+ // Evaluates a single comparison like sys_platform == 'win32' or python_version >= '3.8'.
62
+ // Version-bearing variables (python_version, python_full_version) use numeric comparison;
63
+ // all others use string equality. Returns false when the env value is missing.
64
+ function evaluateComparison(variable, op, value, env) {
65
+ let envVal = env[variable];
66
+ if (envVal === undefined || envVal === '') {
67
+ return false;
68
+ }
69
+ let isVersion = variable.includes('version');
70
+ if (isVersion) {
71
+ let cmp = compareVersions(envVal, value);
72
+ switch (op) {
73
+ case '==': return cmp === 0;
74
+ case '!=': return cmp !== 0;
75
+ case '>=': return cmp >= 0;
76
+ case '<=': return cmp <= 0;
77
+ case '>': return cmp > 0;
78
+ case '<': return cmp < 0;
79
+ case '~=': {
80
+ let parts = value.split('.');
81
+ parts.pop();
82
+ let prefix = parts.join('.');
83
+ return envVal.startsWith(prefix) && cmp >= 0;
84
+ }
85
+ default: return true;
86
+ }
87
+ }
88
+ switch (op) {
89
+ case '==': return envVal === value;
90
+ case '!=': return envVal !== value;
91
+ case 'in': return value.includes(envVal);
92
+ case 'not in': return !value.includes(envVal);
93
+ default: return envVal === value;
94
+ }
95
+ }
96
+ // Parses a single marker comparison into {variable, op, value}.
97
+ // Handles both normal and reversed forms:
98
+ // "sys_platform == 'linux'" → { variable: 'sys_platform', op: '==', value: 'linux' }
99
+ // "'linux' == sys_platform" → { variable: 'sys_platform', op: '==', value: 'linux' }
100
+ function parseAtom(expr) {
101
+ // Normal form: variable op 'value'
102
+ let m = expr.match(/^\s*([\w.]+)\s*(~=|!=|==|>=|<=|>|<|not\s+in|in)\s*["']([^"']*)["']\s*$/);
103
+ if (m) {
104
+ return { variable: m[1], op: m[2].replace(/\s+/g, ' '), value: m[3] };
105
+ }
106
+ // Reversed form: 'value' op variable — reverse directional operators
107
+ let mReverse = expr.match(/^\s*["']([^"']*)['"]\s*(~=|!=|==|>=|<=|>|<|not\s+in|in)\s*([\w.]+)\s*$/);
108
+ if (mReverse) {
109
+ let reverseOp = { '<': '>', '>': '<', '<=': '>=', '>=': '<=' };
110
+ let op = mReverse[2].replace(/\s+/g, ' ');
111
+ return { variable: mReverse[3], op: reverseOp[op] || op, value: mReverse[1] };
112
+ }
113
+ return null;
114
+ }
115
+ /**
116
+ * Evaluates a full PEP 508 marker expression against the current platform.
117
+ * Example: "sys_platform == 'win32' and python_version >= '3.8'" → false on Linux
118
+ * Empty/missing markers return true (unconditional dependency).
119
+ * @param {string} markerExpr
120
+ * @returns {boolean}
121
+ */
122
+ export function evaluateMarker(markerExpr) {
123
+ if (!markerExpr || !markerExpr.trim()) {
124
+ return true;
125
+ }
126
+ let env = getEnvironmentMarkers();
127
+ return evaluateExpr(markerExpr.trim(), env);
128
+ }
129
+ function evaluateExpr(expr, env) {
130
+ let orParts = splitLogical(expr, ' or ');
131
+ if (orParts.length > 1) {
132
+ return orParts.some(part => evaluateExpr(part, env));
133
+ }
134
+ let andParts = splitLogical(expr, ' and ');
135
+ if (andParts.length > 1) {
136
+ return andParts.every(part => evaluateExpr(part, env));
137
+ }
138
+ let trimmed = expr.trim();
139
+ if (trimmed.startsWith('(') && trimmed.endsWith(')')) {
140
+ return evaluateExpr(trimmed.slice(1, -1), env);
141
+ }
142
+ let atom = parseAtom(trimmed);
143
+ if (!atom) {
144
+ return true;
145
+ }
146
+ return evaluateComparison(atom.variable, atom.op, atom.value, env);
147
+ }
148
+ // Splits an expression by " and " or " or " at the top level, skipping
149
+ // separators inside parentheses or quoted strings.
150
+ // Example: splitLogical("a == 'x' and (b == 'y' or c == 'z')", " and ")
151
+ // → ["a == 'x'", "(b == 'y' or c == 'z')"]
152
+ function splitLogical(expr, sep) {
153
+ let parts = [];
154
+ let depth = 0;
155
+ let current = '';
156
+ let i = 0;
157
+ let quoteChar = null;
158
+ while (i < expr.length) {
159
+ let ch = expr[i];
160
+ if (quoteChar) {
161
+ if (ch === quoteChar) {
162
+ quoteChar = null;
163
+ }
164
+ current += ch;
165
+ i++;
166
+ continue;
167
+ }
168
+ if (ch === '"' || ch === "'") {
169
+ quoteChar = ch;
170
+ current += ch;
171
+ i++;
172
+ continue;
173
+ }
174
+ if (ch === '(') {
175
+ depth++;
176
+ }
177
+ if (ch === ')') {
178
+ depth--;
179
+ }
180
+ if (depth === 0 && expr.substring(i, i + sep.length) === sep) {
181
+ parts.push(current);
182
+ current = '';
183
+ i += sep.length;
184
+ continue;
185
+ }
186
+ current += ch;
187
+ i++;
188
+ }
189
+ parts.push(current);
190
+ return parts.filter(p => p.trim());
191
+ }
@@ -19,6 +19,53 @@ function getPipShowOutput(depNames) {
19
19
  throw new Error('fail invoking \'pip show\' to fetch metadata for all installed packages in environment', { cause: error });
20
20
  }
21
21
  }
22
+ /**
23
+ * Get pip inspect output from env var override or by invoking pip inspect.
24
+ * Returns null if pip inspect is unavailable (pip < 22.2) or if freeze/show
25
+ * env vars are set without an inspect override (to avoid inconsistent data).
26
+ * @return {string|null} pip inspect JSON output, or null on failure
27
+ */
28
+ function getPipInspectOutput() {
29
+ if (environmentVariableIsPopulated("TRUSTIFY_DA_PIP_INSPECT")) {
30
+ return new Buffer.from(process.env["TRUSTIFY_DA_PIP_INSPECT"], 'base64').toString('ascii');
31
+ }
32
+ if (environmentVariableIsPopulated("TRUSTIFY_DA_PIP_FREEZE") || environmentVariableIsPopulated("TRUSTIFY_DA_PIP_SHOW")) {
33
+ return null;
34
+ }
35
+ try {
36
+ return invokeCommand(this.pathToPipBin, ['inspect']).toString();
37
+ }
38
+ catch (error) {
39
+ console.warn('pip inspect is not available (requires pip 22.2+), SBOM will be generated without hashes');
40
+ return null;
41
+ }
42
+ }
43
+ /**
44
+ * Parse pip inspect JSON output and build a hash lookup map.
45
+ * @param {string|null} inspectOutput - raw pip inspect JSON string
46
+ * @return {Map<string, Array<{alg: string, content: string}>>} map of lowercase package name to hashes
47
+ */
48
+ function parsePipInspectHashes(inspectOutput) {
49
+ if (!inspectOutput) {
50
+ return new Map();
51
+ }
52
+ try {
53
+ let inspectData = JSON.parse(inspectOutput);
54
+ let hashMap = new Map();
55
+ for (let pkg of (inspectData.installed || [])) {
56
+ let name = pkg.metadata?.name;
57
+ let sha256 = pkg.download_info?.archive_info?.hashes?.sha256;
58
+ if (name && sha256) {
59
+ hashMap.set(name.toLowerCase(), [{ alg: "SHA-256", content: sha256 }]);
60
+ }
61
+ }
62
+ return hashMap;
63
+ }
64
+ catch (error) {
65
+ console.warn('Failed to parse pip inspect output, SBOM will be generated without hashes');
66
+ return new Map();
67
+ }
68
+ }
22
69
  /** @typedef {{name: string, version: string, dependencies: DependencyEntry[], hashes?: Array<{alg: string, content: string}>}} DependencyEntry */
23
70
  export default class Python_controller {
24
71
  pythonEnvDir;
@@ -225,6 +272,8 @@ export default class Python_controller {
225
272
  CachedEnvironmentDeps[packageName.replace("_", "-")] = pipDepTreeEntryForCache;
226
273
  });
227
274
  }
275
+ const inspectOutput = getPipInspectOutput.call(this);
276
+ const hashMap = parsePipInspectHashes(inspectOutput);
228
277
  parsedRequirements.forEach(({ name: depName, version: manifestVersion, hasMarker }) => {
229
278
  if (hasMarker && CachedEnvironmentDeps[depName.toLowerCase()] === undefined) {
230
279
  return;
@@ -247,7 +296,7 @@ export default class Python_controller {
247
296
  }
248
297
  let path = [];
249
298
  path.push(depName.toLowerCase());
250
- bringAllDependencies(dependencies, depName, CachedEnvironmentDeps, includeTransitive, path, usePipDepTree);
299
+ bringAllDependencies(dependencies, depName, CachedEnvironmentDeps, includeTransitive, path, usePipDepTree, hashMap);
251
300
  });
252
301
  dependencies.sort((dep1, dep2) => {
253
302
  const DEP1 = dep1.name.toLowerCase();
@@ -327,8 +376,9 @@ function getDepsList(record) {
327
376
  * @param includeTransitive
328
377
  * @param usePipDepTree
329
378
  * @param {[string]}path array representing the path of the current branch in dependency tree, starting with a root dependency - that is - a given dependency in requirements.txt
379
+ * @param {Map<string, Array<{alg: string, content: string}>>} hashMap - map of lowercase package name to hashes
330
380
  */
331
- function bringAllDependencies(dependencies, dependencyName, cachedEnvironmentDeps, includeTransitive, path, usePipDepTree) {
381
+ function bringAllDependencies(dependencies, dependencyName, cachedEnvironmentDeps, includeTransitive, path, usePipDepTree, hashMap) {
332
382
  if (dependencyName?.trim() === "") {
333
383
  return;
334
384
  }
@@ -350,7 +400,11 @@ function bringAllDependencies(dependencies, dependencyName, cachedEnvironmentDep
350
400
  directDeps = record.dependencies;
351
401
  }
352
402
  let targetDeps = [];
403
+ let hashes = hashMap?.get(depName.toLowerCase());
353
404
  let entry = { "name": depName, "version": version, "dependencies": [] };
405
+ if (hashes) {
406
+ entry.hashes = hashes;
407
+ }
354
408
  dependencies.push(entry);
355
409
  directDeps.forEach((dep) => {
356
410
  let depArray = [];
@@ -360,7 +414,7 @@ function bringAllDependencies(dependencies, dependencyName, cachedEnvironmentDep
360
414
  depArray.push(dep.toLowerCase());
361
415
  if (includeTransitive) {
362
416
  // send to recurrsion the array of all deps in path + the current dependency name which is not on the path.
363
- bringAllDependencies(targetDeps, dep, cachedEnvironmentDeps, includeTransitive, path.concat(depArray), usePipDepTree);
417
+ bringAllDependencies(targetDeps, dep, cachedEnvironmentDeps, includeTransitive, path.concat(depArray), usePipDepTree, hashMap);
364
418
  }
365
419
  }
366
420
  // sort ra
@@ -4,6 +4,7 @@ declare namespace _default {
4
4
  export { provideComponent };
5
5
  export { provideStack };
6
6
  export { readLicenseFromManifest };
7
+ export function packageManagerName(): string;
7
8
  }
8
9
  export default _default;
9
10
  export type DependencyEntry = {
@@ -5,7 +5,7 @@ import Sbom from '../sbom.js';
5
5
  import { environmentVariableIsPopulated, getCustom, getCustomPath, invokeCommand } from "../tools.js";
6
6
  import Python_controller from './python_controller.js';
7
7
  import { getParser, getIgnoreQuery, getPinnedVersionQuery } from './requirements_parser.js';
8
- export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest };
8
+ export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest, packageManagerName() { return 'pip'; } };
9
9
  /** @typedef {{name: string, version: string, dependencies: DependencyEntry[], hashes?: Array<{alg: string, content: string}>}} DependencyEntry */
10
10
  /**
11
11
  * @type {string} ecosystem for python-pip is 'pip'
@@ -76,7 +76,9 @@ export default class Python_pip_pyproject extends Base_pyproject {
76
76
  let name = pkg.metadata.name;
77
77
  let version = pkg.metadata.version;
78
78
  let key = this._canonicalize(name);
79
- graph.set(key, { name, version, children: [] });
79
+ let sha256 = pkg.download_info?.archive_info?.hashes?.sha256;
80
+ let hashes = sha256 ? [{ alg: "SHA-256", content: sha256 }] : undefined;
81
+ graph.set(key, { name, version, children: [], hashes });
80
82
  }
81
83
  for (let pkg of nonRootPackages) {
82
84
  let key = this._canonicalize(pkg.metadata.name);
@@ -37,16 +37,33 @@ export default class Python_poetry extends Base_pyproject {
37
37
  * @returns {Map<string, string>} canonical name -> version
38
38
  */
39
39
  _parsePoetryShowAll(output: string): Map<string, string>;
40
+ /**
41
+ * Collects PEP 508 marker expressions for direct and transitive deps.
42
+ * Direct markers come from pyproject.toml dependency strings, e.g.:
43
+ * "pywin32>=311 ; sys_platform == 'win32'" → directMarkers['pywin32'] = "sys_platform == 'win32'"
44
+ * Transitive markers come from poetry.lock [package.dependencies] entries, e.g.:
45
+ * colorama = {version = "*", markers = "sys_platform == 'win32'"}
46
+ * → transitiveMarkers['click']['colorama'] = "sys_platform == 'win32'"
47
+ * @param {string|null} lockDir
48
+ * @param {object} parsed - parsed pyproject.toml
49
+ * @returns {{directMarkers: Map<string, string>, transitiveMarkers: Map<string, Map<string, string>>}}
50
+ */
51
+ _extractMarkerData(lockDir: string | null, parsed: object): {
52
+ directMarkers: Map<string, string>;
53
+ transitiveMarkers: Map<string, Map<string, string>>;
54
+ };
40
55
  /**
41
56
  * Parse poetry show --tree output into a dependency graph structure.
42
- * Top-level lines (no indentation/tree chars) are direct deps: "name version description"
43
- * Indented lines are transitive deps with tree chars: "├── name >=constraint"
44
57
  *
45
58
  * @param {string} treeOutput
46
59
  * @param {Map<string, string>} versionMap - canonical name -> resolved version
60
+ * @param {{directMarkers: Map<string, string>, transitiveMarkers: Map<string, Map<string, string>>}} markerData
47
61
  * @returns {{directDeps: string[], graph: Map<string, {name: string, version: string, children: string[]}>}}
48
62
  */
49
- _parsePoetryTree(treeOutput: string, versionMap: Map<string, string>): {
63
+ _parsePoetryTree(treeOutput: string, versionMap: Map<string, string>, markerData: {
64
+ directMarkers: Map<string, string>;
65
+ transitiveMarkers: Map<string, Map<string, string>>;
66
+ }): {
50
67
  directDeps: string[];
51
68
  graph: Map<string, {
52
69
  name: string;
@@ -1,7 +1,9 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { parse as parseToml } from 'smol-toml';
3
4
  import { environmentVariableIsPopulated, getCustom, getCustomPath, invokeCommand } from '../tools.js';
4
5
  import Base_pyproject from './base_pyproject.js';
6
+ import { evaluateMarker } from './marker_evaluator.js';
5
7
  export default class Python_poetry extends Base_pyproject {
6
8
  /**
7
9
  * Poetry has no native workspace/monorepo support (python-poetry/poetry#2270).
@@ -43,7 +45,9 @@ export default class Python_poetry extends Base_pyproject {
43
45
  let treeOutput = this._getPoetryShowTreeOutput(manifestDir, hasDevGroup, opts);
44
46
  let showAllOutput = this._getPoetryShowAllOutput(manifestDir, opts);
45
47
  let versionMap = this._parsePoetryShowAll(showAllOutput);
46
- return this._parsePoetryTree(treeOutput, versionMap);
48
+ let lockDir = this._findLockFileDir(manifestDir, opts);
49
+ let markerData = this._extractMarkerData(lockDir, parsed);
50
+ return this._parsePoetryTree(treeOutput, versionMap, markerData);
47
51
  }
48
52
  /**
49
53
  * Get poetry show --tree output.
@@ -98,16 +102,60 @@ export default class Python_poetry extends Base_pyproject {
98
102
  }
99
103
  return versions;
100
104
  }
105
+ /**
106
+ * Collects PEP 508 marker expressions for direct and transitive deps.
107
+ * Direct markers come from pyproject.toml dependency strings, e.g.:
108
+ * "pywin32>=311 ; sys_platform == 'win32'" → directMarkers['pywin32'] = "sys_platform == 'win32'"
109
+ * Transitive markers come from poetry.lock [package.dependencies] entries, e.g.:
110
+ * colorama = {version = "*", markers = "sys_platform == 'win32'"}
111
+ * → transitiveMarkers['click']['colorama'] = "sys_platform == 'win32'"
112
+ * @param {string|null} lockDir
113
+ * @param {object} parsed - parsed pyproject.toml
114
+ * @returns {{directMarkers: Map<string, string>, transitiveMarkers: Map<string, Map<string, string>>}}
115
+ */
116
+ _extractMarkerData(lockDir, parsed) {
117
+ let directMarkers = new Map();
118
+ let transitiveMarkers = new Map();
119
+ // Extract markers from PEP 621 dependency strings: "name[extras]>=ver ; marker"
120
+ let deps = parsed.project?.dependencies || [];
121
+ for (let dep of deps) {
122
+ let m = dep.match(/^([A-Za-z0-9][A-Za-z0-9._-]*)\s*[^;]*;\s*(.+)$/);
123
+ if (m) {
124
+ directMarkers.set(this._canonicalize(m[1]), m[2].trim());
125
+ }
126
+ }
127
+ if (lockDir) {
128
+ let lockPath = path.join(lockDir, this._lockFileName());
129
+ if (fs.existsSync(lockPath)) {
130
+ let lockContent = fs.readFileSync(lockPath, 'utf-8');
131
+ let lock = parseToml(lockContent);
132
+ let packages = lock.package || [];
133
+ for (let pkg of packages) {
134
+ let pkgKey = this._canonicalize(pkg.name);
135
+ let pkgDeps = pkg.dependencies || {};
136
+ for (let [depName, depSpec] of Object.entries(pkgDeps)) {
137
+ let markers = typeof depSpec === 'object' && depSpec != null ? depSpec.markers : null;
138
+ if (markers) {
139
+ if (!transitiveMarkers.has(pkgKey)) {
140
+ transitiveMarkers.set(pkgKey, new Map());
141
+ }
142
+ transitiveMarkers.get(pkgKey).set(this._canonicalize(depName), markers);
143
+ }
144
+ }
145
+ }
146
+ }
147
+ }
148
+ return { directMarkers, transitiveMarkers };
149
+ }
101
150
  /**
102
151
  * Parse poetry show --tree output into a dependency graph structure.
103
- * Top-level lines (no indentation/tree chars) are direct deps: "name version description"
104
- * Indented lines are transitive deps with tree chars: "├── name >=constraint"
105
152
  *
106
153
  * @param {string} treeOutput
107
154
  * @param {Map<string, string>} versionMap - canonical name -> resolved version
155
+ * @param {{directMarkers: Map<string, string>, transitiveMarkers: Map<string, Map<string, string>>}} markerData
108
156
  * @returns {{directDeps: string[], graph: Map<string, {name: string, version: string, children: string[]}>}}
109
157
  */
110
- _parsePoetryTree(treeOutput, versionMap) {
158
+ _parsePoetryTree(treeOutput, versionMap, markerData) {
111
159
  let lines = treeOutput.split(/\r?\n/);
112
160
  let graph = new Map();
113
161
  let directDeps = [];
@@ -123,6 +171,12 @@ export default class Python_poetry extends Base_pyproject {
123
171
  let name = topMatch[1];
124
172
  let version = topMatch[2];
125
173
  let key = this._canonicalize(name);
174
+ let marker = markerData.directMarkers.get(key);
175
+ if (marker && !evaluateMarker(marker)) {
176
+ currentDirectDep = null;
177
+ stack = [];
178
+ continue;
179
+ }
126
180
  directDeps.push(key);
127
181
  if (!graph.has(key)) {
128
182
  graph.set(key, { name, version, children: [] });
@@ -149,6 +203,20 @@ export default class Python_poetry extends Base_pyproject {
149
203
  // determine depth by counting tree-drawing groups in the prefix
150
204
  let prefix = line.substring(0, nameStart);
151
205
  let depth = (prefix.match(/(?:[├└│ ][\s─]{2} ?)/g) || []).length;
206
+ // pop stack back to find the parent at depth-1
207
+ while (stack.length > 0 && stack[stack.length - 1].depth >= depth) {
208
+ stack.pop();
209
+ }
210
+ let parentKey = stack.length > 0 ? stack[stack.length - 1].key : null;
211
+ if (parentKey) {
212
+ let parentMarkers = markerData.transitiveMarkers.get(parentKey);
213
+ if (parentMarkers) {
214
+ let marker = parentMarkers.get(depKey);
215
+ if (marker && !evaluateMarker(marker)) {
216
+ continue;
217
+ }
218
+ }
219
+ }
152
220
  // resolve version from the version map
153
221
  let version = versionMap.get(depKey) || null;
154
222
  if (!version) {
@@ -157,12 +225,7 @@ export default class Python_poetry extends Base_pyproject {
157
225
  if (!graph.has(depKey)) {
158
226
  graph.set(depKey, { name: depName, version, children: [] });
159
227
  }
160
- // pop stack back to find the parent at depth-1
161
- while (stack.length > 0 && stack[stack.length - 1].depth >= depth) {
162
- stack.pop();
163
- }
164
- if (stack.length > 0) {
165
- let parentKey = stack[stack.length - 1].key;
228
+ if (parentKey) {
166
229
  let parentEntry = graph.get(parentKey);
167
230
  if (parentEntry && !parentEntry.children.includes(depKey)) {
168
231
  parentEntry.children.push(depKey);
@@ -1,3 +1,16 @@
1
+ /**
2
+ * Discover all pyproject.toml manifest paths in a uv workspace.
3
+ * Parses `[tool.uv.workspace]` from root pyproject.toml and glob-expands member patterns.
4
+ *
5
+ * @param {string} workspaceRoot - Absolute or relative path to workspace root (must contain pyproject.toml and uv.lock)
6
+ * @param {{ workspaceDiscoveryIgnore?: string[], TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string, [key: string]: unknown }} [opts={}]
7
+ * @returns {Promise<string[]>} Paths to pyproject.toml files (absolute)
8
+ */
9
+ export function discoverUvWorkspaceMembers(workspaceRoot: string, opts?: {
10
+ workspaceDiscoveryIgnore?: string[];
11
+ TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string;
12
+ [key: string]: unknown;
13
+ }): Promise<string[]>;
1
14
  export default class Python_uv extends Base_pyproject {
2
15
  /**
3
16
  * @param {string} manifestDir - directory containing the target pyproject.toml
@@ -1,8 +1,11 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import fg from 'fast-glob';
3
4
  import { parse as parseToml } from 'smol-toml';
4
5
  import { environmentVariableIsPopulated, getCustomPath, invokeCommand } from '../tools.js';
6
+ import { filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, toManifestGlobPatterns } from '../workspace.js';
5
7
  import Base_pyproject from './base_pyproject.js';
8
+ import { evaluateMarker } from './marker_evaluator.js';
6
9
  import { getParser, getPinnedVersionQuery } from './requirements_parser.js';
7
10
  export default class Python_uv extends Base_pyproject {
8
11
  /** @returns {string} */
@@ -89,6 +92,16 @@ export default class Python_uv extends Base_pyproject {
89
92
  if (!nameNode) {
90
93
  continue;
91
94
  }
95
+ // Skip packages with non-matching PEP 508 markers, e.g. "pywin32==311 ; sys_platform == 'win32'"
96
+ let markerNode = child.children.find(c => c.type === 'marker_spec');
97
+ if (markerNode) {
98
+ let markerText = markerNode.text.replace(/^\s*;\s*/, '');
99
+ if (!evaluateMarker(markerText)) {
100
+ currentPkg = null;
101
+ collectingVia = false;
102
+ continue;
103
+ }
104
+ }
92
105
  let name = nameNode.text;
93
106
  let version = null;
94
107
  let versionMatches = pinnedVersionQuery.matches(child);
@@ -147,3 +160,68 @@ export default class Python_uv extends Base_pyproject {
147
160
  return { directDeps, graph };
148
161
  }
149
162
  }
163
+ const DEFAULT_UV_DISCOVERY_IGNORE = [
164
+ '**/__pycache__/**',
165
+ '**/.venv/**',
166
+ ];
167
+ /**
168
+ * Discover all pyproject.toml manifest paths in a uv workspace.
169
+ * Parses `[tool.uv.workspace]` from root pyproject.toml and glob-expands member patterns.
170
+ *
171
+ * @param {string} workspaceRoot - Absolute or relative path to workspace root (must contain pyproject.toml and uv.lock)
172
+ * @param {{ workspaceDiscoveryIgnore?: string[], TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string, [key: string]: unknown }} [opts={}]
173
+ * @returns {Promise<string[]>} Paths to pyproject.toml files (absolute)
174
+ */
175
+ export async function discoverUvWorkspaceMembers(workspaceRoot, opts = {}) {
176
+ const root = path.resolve(workspaceRoot);
177
+ const rootPyproject = path.join(root, 'pyproject.toml');
178
+ const uvLock = path.join(root, 'uv.lock');
179
+ if (!fs.existsSync(rootPyproject) || !fs.existsSync(uvLock)) {
180
+ return [];
181
+ }
182
+ let parsed;
183
+ try {
184
+ parsed = parseToml(fs.readFileSync(rootPyproject, 'utf-8'));
185
+ }
186
+ catch {
187
+ return [];
188
+ }
189
+ const workspaceConfig = parsed?.tool?.uv?.workspace;
190
+ if (!workspaceConfig) {
191
+ return [];
192
+ }
193
+ const memberPatterns = workspaceConfig.members;
194
+ if (!Array.isArray(memberPatterns) || memberPatterns.length === 0) {
195
+ return [];
196
+ }
197
+ const excludePatterns = Array.isArray(workspaceConfig.exclude) ? workspaceConfig.exclude : [];
198
+ const excludeGlobs = excludePatterns
199
+ .filter(p => typeof p === 'string' && p.trim())
200
+ .map(p => `${p.trim()}/pyproject.toml`);
201
+ const ignorePatterns = [...resolveWorkspaceDiscoveryIgnore(opts), ...DEFAULT_UV_DISCOVERY_IGNORE];
202
+ const globOpts = {
203
+ cwd: root,
204
+ absolute: true,
205
+ onlyFiles: true,
206
+ ignore: [...ignorePatterns, ...excludeGlobs],
207
+ followSymbolicLinks: false,
208
+ };
209
+ const patterns = toManifestGlobPatterns(memberPatterns.filter(p => typeof p === 'string'), 'pyproject.toml');
210
+ const manifestPaths = await fg(patterns, globOpts);
211
+ if (!manifestPaths.includes(rootPyproject) && hasProjectMetadata(parsed)) {
212
+ manifestPaths.unshift(rootPyproject);
213
+ }
214
+ return filterManifestPathsByDiscoveryIgnore(manifestPaths, root, ignorePatterns);
215
+ }
216
+ /**
217
+ * @param {import('smol-toml').TomlTable} parsedPyProject
218
+ * @returns {boolean}
219
+ */
220
+ function hasProjectMetadata(parsedPyProject) {
221
+ try {
222
+ return typeof parsedPyProject?.project?.name === 'string' && parsedPyProject.project.name.trim() !== '';
223
+ }
224
+ catch {
225
+ return false;
226
+ }
227
+ }
@@ -4,6 +4,7 @@ declare namespace _default {
4
4
  export { provideComponent };
5
5
  export { provideStack };
6
6
  export { readLicenseFromManifest };
7
+ export function packageManagerName(): string;
7
8
  }
8
9
  export default _default;
9
10
  export type Provided = import("../provider").Provided;
@@ -5,7 +5,7 @@ import { parse as parseToml } from 'smol-toml';
5
5
  import { getLicense } from '../license/license_utils.js';
6
6
  import Sbom from '../sbom.js';
7
7
  import { getCustom, getCustomPath, invokeCommand } from '../tools.js';
8
- export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest };
8
+ export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest, packageManagerName() { return 'cargo'; } };
9
9
  /** @typedef {import('../provider').Provider} */
10
10
  /** @typedef {import('../provider').Provided} Provided */
11
11
  /**
@@ -42,6 +42,15 @@ export function discoverWorkspacePackages(workspaceRoot: string, opts?: {
42
42
  TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE?: string;
43
43
  [key: string]: unknown;
44
44
  }): Promise<string[]>;
45
+ /**
46
+ * Convert workspace glob patterns to manifest-file glob patterns,
47
+ * correctly handling negation prefixes.
48
+ *
49
+ * @param {string[]} patterns - Workspace glob patterns (may include negations)
50
+ * @param {string} manifestFileName - e.g. 'package.json' or 'Cargo.toml'
51
+ * @returns {string[]}
52
+ */
53
+ export function toManifestGlobPatterns(patterns: string[], manifestFileName: string): string[];
45
54
  /**
46
55
  * Discover all Cargo.toml manifest paths in a Cargo workspace.
47
56
  * Uses `cargo metadata` to get workspace members.
@@ -172,7 +172,7 @@ function parsePnpmPackages(content) {
172
172
  * @param {string} manifestFileName - e.g. 'package.json' or 'Cargo.toml'
173
173
  * @returns {string[]}
174
174
  */
175
- function toManifestGlobPatterns(patterns, manifestFileName) {
175
+ export function toManifestGlobPatterns(patterns, manifestFileName) {
176
176
  return patterns.map(p => {
177
177
  if (p.startsWith('!')) {
178
178
  return `!${p.slice(1)}/${manifestFileName}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trustify-da/trustify-da-javascript-client",
3
- "version": "0.3.0-ea.1d590b2",
3
+ "version": "0.3.0-ea.212178e",
4
4
  "description": "Code-Ready Dependency Analytics JavaScript API.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/guacsec/trustify-da-javascript-client#README.md",
@@ -51,11 +51,11 @@
51
51
  "@cyclonedx/cyclonedx-library": "^6.13.0",
52
52
  "eslint-import-resolver-typescript": "^4.4.4",
53
53
  "fast-glob": "^3.3.3",
54
- "fast-toml": "^0.5.4",
55
54
  "fast-xml-parser": "^5.3.4",
56
55
  "help": "^3.0.2",
57
56
  "https-proxy-agent": "^7.0.6",
58
57
  "js-yaml": "^4.1.1",
58
+ "jsonc-parser": "^3.3.1",
59
59
  "micromatch": "^4.0.8",
60
60
  "node-fetch": "^3.3.2",
61
61
  "p-limit": "^4.0.0",