@trustify-da/trustify-da-javascript-client 0.3.0-ea.d71f957 → 0.3.0-ea.d8ec262

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 (50) hide show
  1. package/README.md +56 -2
  2. package/dist/package.json +2 -2
  3. package/dist/src/analysis.js +3 -2
  4. package/dist/src/cli.js +51 -2
  5. package/dist/src/cyclone_dx_sbom.d.ts +7 -1
  6. package/dist/src/cyclone_dx_sbom.js +29 -8
  7. package/dist/src/index.d.ts +74 -3
  8. package/dist/src/index.js +92 -7
  9. package/dist/src/oci_image/utils.js +11 -2
  10. package/dist/src/provider.d.ts +3 -2
  11. package/dist/src/provider.js +9 -1
  12. package/dist/src/providers/base_java.d.ts +12 -10
  13. package/dist/src/providers/base_java.js +18 -44
  14. package/dist/src/providers/base_javascript.d.ts +11 -0
  15. package/dist/src/providers/base_javascript.js +10 -3
  16. package/dist/src/providers/base_pyproject.d.ts +158 -0
  17. package/dist/src/providers/base_pyproject.js +322 -0
  18. package/dist/src/providers/golang_gomodules.d.ts +10 -0
  19. package/dist/src/providers/golang_gomodules.js +65 -8
  20. package/dist/src/providers/java_gradle.d.ts +19 -0
  21. package/dist/src/providers/java_gradle.js +116 -2
  22. package/dist/src/providers/java_maven.d.ts +8 -0
  23. package/dist/src/providers/java_maven.js +165 -1
  24. package/dist/src/providers/javascript_bun.d.ts +10 -0
  25. package/dist/src/providers/javascript_bun.js +100 -0
  26. package/dist/src/providers/javascript_npm.d.ts +1 -0
  27. package/dist/src/providers/javascript_npm.js +21 -0
  28. package/dist/src/providers/javascript_pnpm.js +6 -2
  29. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  30. package/dist/src/providers/marker_evaluator.js +191 -0
  31. package/dist/src/providers/processors/yarn_berry_processor.js +6 -2
  32. package/dist/src/providers/python_controller.d.ts +5 -1
  33. package/dist/src/providers/python_controller.js +65 -7
  34. package/dist/src/providers/python_pip.d.ts +5 -0
  35. package/dist/src/providers/python_pip.js +5 -5
  36. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  37. package/dist/src/providers/python_pip_pyproject.js +146 -0
  38. package/dist/src/providers/python_poetry.d.ts +97 -0
  39. package/dist/src/providers/python_poetry.js +271 -0
  40. package/dist/src/providers/python_uv.d.ts +55 -0
  41. package/dist/src/providers/python_uv.js +227 -0
  42. package/dist/src/providers/rust_cargo.d.ts +5 -1
  43. package/dist/src/providers/rust_cargo.js +31 -4
  44. package/dist/src/sbom.d.ts +7 -1
  45. package/dist/src/sbom.js +4 -2
  46. package/dist/src/tools.d.ts +26 -0
  47. package/dist/src/tools.js +58 -0
  48. package/dist/src/workspace.d.ts +9 -0
  49. package/dist/src/workspace.js +1 -1
  50. package/package.json +3 -3
@@ -0,0 +1,271 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse as parseToml } from 'smol-toml';
4
+ import { environmentVariableIsPopulated, getCustom, getCustomPath, invokeCommand } from '../tools.js';
5
+ import Base_pyproject from './base_pyproject.js';
6
+ import { evaluateMarker } from './marker_evaluator.js';
7
+ export default class Python_poetry extends Base_pyproject {
8
+ /**
9
+ * Poetry has no native workspace/monorepo support (python-poetry/poetry#2270).
10
+ * Each poetry project is treated independently — no lock file walk-up.
11
+ * Running `poetry show` from a parent directory returns the parent's deps, not
12
+ * the sub-package's, so walk-up would produce incorrect SBOMs.
13
+ * @param {string} manifestDir
14
+ * @param {Object} [opts={}]
15
+ * @returns {string|null}
16
+ * @protected
17
+ */
18
+ _findLockFileDir(manifestDir, opts = {}) {
19
+ const workspaceDir = getCustom('TRUSTIFY_DA_WORKSPACE_DIR', null, opts);
20
+ if (workspaceDir) {
21
+ const dir = path.resolve(workspaceDir);
22
+ return fs.existsSync(path.join(dir, this._lockFileName())) ? dir : null;
23
+ }
24
+ const dir = path.resolve(manifestDir);
25
+ return fs.existsSync(path.join(dir, this._lockFileName())) ? dir : null;
26
+ }
27
+ /** @returns {string} */
28
+ _lockFileName() {
29
+ return 'poetry.lock';
30
+ }
31
+ /** @returns {string} */
32
+ _cmdName() {
33
+ return 'poetry';
34
+ }
35
+ /**
36
+ * @param {string} manifestDir
37
+ * @param {string} _workspaceDir - unused (poetry has no workspace support)
38
+ * @param {object} parsed - parsed pyproject.toml
39
+ * @param {Object} opts
40
+ * @returns {Promise<{directDeps: string[], graph: Map<string, {name: string, version: string, children: string[]}>}>}
41
+ */
42
+ // eslint-disable-next-line no-unused-vars
43
+ async _getDependencyData(manifestDir, _workspaceDir, parsed, opts) {
44
+ let hasDevGroup = !!(parsed.tool?.poetry?.group?.dev || parsed.tool?.poetry?.['dev-dependencies']);
45
+ let treeOutput = this._getPoetryShowTreeOutput(manifestDir, hasDevGroup, opts);
46
+ let showAllOutput = this._getPoetryShowAllOutput(manifestDir, opts);
47
+ let versionMap = this._parsePoetryShowAll(showAllOutput);
48
+ let lockDir = this._findLockFileDir(manifestDir, opts);
49
+ let markerData = this._extractMarkerData(lockDir, parsed);
50
+ return this._parsePoetryTree(treeOutput, versionMap, markerData);
51
+ }
52
+ /**
53
+ * Get poetry show --tree output.
54
+ * @param {string} manifestDir
55
+ * @param {boolean} hasDevGroup
56
+ * @param {Object} opts
57
+ * @returns {string}
58
+ */
59
+ _getPoetryShowTreeOutput(manifestDir, hasDevGroup, opts) {
60
+ if (environmentVariableIsPopulated('TRUSTIFY_DA_POETRY_SHOW_TREE')) {
61
+ return Buffer.from(process.env['TRUSTIFY_DA_POETRY_SHOW_TREE'], 'base64').toString('utf-8');
62
+ }
63
+ let poetryBin = getCustomPath('poetry', opts);
64
+ let args = ['show', '--tree', '--no-ansi'];
65
+ if (hasDevGroup) {
66
+ args.push('--without', 'dev');
67
+ }
68
+ return invokeCommand(poetryBin, args, { cwd: manifestDir }).toString();
69
+ }
70
+ /**
71
+ * Get poetry show --all output (flat list with resolved versions).
72
+ * @param {string} manifestDir
73
+ * @param {Object} opts
74
+ * @returns {string}
75
+ */
76
+ _getPoetryShowAllOutput(manifestDir, opts) {
77
+ if (environmentVariableIsPopulated('TRUSTIFY_DA_POETRY_SHOW_ALL')) {
78
+ return Buffer.from(process.env['TRUSTIFY_DA_POETRY_SHOW_ALL'], 'base64').toString('utf-8');
79
+ }
80
+ let poetryBin = getCustomPath('poetry', opts);
81
+ return invokeCommand(poetryBin, ['show', '--no-ansi', '--all'], { cwd: manifestDir }).toString();
82
+ }
83
+ /**
84
+ * Parse poetry show --all output into a version map.
85
+ * Lines look like: "name (!) 1.2.3 Description text..."
86
+ * or: "name 1.2.3 Description text..."
87
+ * @param {string} output
88
+ * @returns {Map<string, string>} canonical name -> version
89
+ */
90
+ _parsePoetryShowAll(output) {
91
+ let versions = new Map();
92
+ let lines = output.split(/\r?\n/);
93
+ for (let line of lines) {
94
+ let trimmed = line.trim();
95
+ if (!trimmed) {
96
+ continue;
97
+ }
98
+ let match = trimmed.match(/^([A-Za-z0-9][A-Za-z0-9._-]*)\s+(?:\(!\)\s+)?(\S+)/);
99
+ if (match) {
100
+ versions.set(this._canonicalize(match[1]), match[2]);
101
+ }
102
+ }
103
+ return versions;
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>>, hashMap: Map<string, Array<{alg: string, content: string}>>}}
115
+ */
116
+ _extractMarkerData(lockDir, parsed) {
117
+ let directMarkers = new Map();
118
+ let transitiveMarkers = new Map();
119
+ let hashMap = new Map();
120
+ // Extract markers from PEP 621 dependency strings: "name[extras]>=ver ; marker"
121
+ let deps = parsed.project?.dependencies || [];
122
+ for (let dep of deps) {
123
+ let m = dep.match(/^([A-Za-z0-9][A-Za-z0-9._-]*)\s*[^;]*;\s*(.+)$/);
124
+ if (m) {
125
+ directMarkers.set(this._canonicalize(m[1]), m[2].trim());
126
+ }
127
+ }
128
+ if (lockDir) {
129
+ let lockPath = path.join(lockDir, this._lockFileName());
130
+ if (fs.existsSync(lockPath)) {
131
+ let lockContent = fs.readFileSync(lockPath, 'utf-8');
132
+ let lock = parseToml(lockContent);
133
+ let packages = lock.package || [];
134
+ for (let pkg of packages) {
135
+ let pkgKey = this._canonicalize(pkg.name);
136
+ let pkgDeps = pkg.dependencies || {};
137
+ for (let [depName, depSpec] of Object.entries(pkgDeps)) {
138
+ let markers = typeof depSpec === 'object' && depSpec != null ? depSpec.markers : null;
139
+ if (markers) {
140
+ if (!transitiveMarkers.has(pkgKey)) {
141
+ transitiveMarkers.set(pkgKey, new Map());
142
+ }
143
+ transitiveMarkers.get(pkgKey).set(this._canonicalize(depName), markers);
144
+ }
145
+ }
146
+ let sha256Hex = this._extractSha256FromFiles(pkg.files);
147
+ if (sha256Hex) {
148
+ hashMap.set(pkgKey, [{ alg: "SHA-256", content: sha256Hex }]);
149
+ }
150
+ }
151
+ }
152
+ }
153
+ return { directMarkers, transitiveMarkers, hashMap };
154
+ }
155
+ /**
156
+ * Extract a SHA-256 hex digest from poetry.lock files array.
157
+ * Prefers the sdist (.tar.gz) hash; falls back to the first wheel hash.
158
+ * @param {Array<{file: string, hash: string}>} [files]
159
+ * @returns {string|null}
160
+ */
161
+ _extractSha256FromFiles(files) {
162
+ if (!Array.isArray(files) || files.length === 0) {
163
+ return null;
164
+ }
165
+ let sdist = files.find(f => f.file.endsWith('.tar.gz'));
166
+ let entry = sdist || files[0];
167
+ let hash = entry.hash;
168
+ if (hash && hash.startsWith('sha256:')) {
169
+ return hash.slice(7);
170
+ }
171
+ return null;
172
+ }
173
+ /**
174
+ * Parse poetry show --tree output into a dependency graph structure.
175
+ *
176
+ * @param {string} treeOutput
177
+ * @param {Map<string, string>} versionMap - canonical name -> resolved version
178
+ * @param {{directMarkers: Map<string, string>, transitiveMarkers: Map<string, Map<string, string>>, hashMap: Map<string, Array<{alg: string, content: string}>>}} markerData
179
+ * @returns {{directDeps: string[], graph: Map<string, {name: string, version: string, children: string[], hashes?: Array<{alg: string, content: string}>}>}}
180
+ */
181
+ _parsePoetryTree(treeOutput, versionMap, markerData) {
182
+ let lines = treeOutput.split(/\r?\n/);
183
+ let graph = new Map();
184
+ let directDeps = [];
185
+ let stack = []; // [{key, depth}]
186
+ let currentDirectDep = null;
187
+ for (let line of lines) {
188
+ if (!line.trim()) {
189
+ continue;
190
+ }
191
+ // top-level line: "name version description..."
192
+ let topMatch = line.match(/^([A-Za-z0-9][A-Za-z0-9._-]*)\s+(\S+)(?:\s|$)/);
193
+ if (topMatch) {
194
+ let name = topMatch[1];
195
+ let version = topMatch[2];
196
+ let key = this._canonicalize(name);
197
+ let marker = markerData.directMarkers.get(key);
198
+ if (marker && !evaluateMarker(marker)) {
199
+ currentDirectDep = null;
200
+ stack = [];
201
+ continue;
202
+ }
203
+ directDeps.push(key);
204
+ if (!graph.has(key)) {
205
+ let entry = { name, version, children: [] };
206
+ let hashes = markerData.hashMap.get(key);
207
+ if (hashes) {
208
+ entry.hashes = hashes;
209
+ }
210
+ graph.set(key, entry);
211
+ }
212
+ currentDirectDep = key;
213
+ stack = [{ key, depth: -1 }];
214
+ continue;
215
+ }
216
+ if (!currentDirectDep) {
217
+ continue;
218
+ }
219
+ // indented line with tree chars (UTF-8 box-drawing: ├── └── │)
220
+ let nameStart = line.search(/[A-Za-z0-9]/);
221
+ if (nameStart < 0) {
222
+ continue;
223
+ }
224
+ let rest = line.substring(nameStart);
225
+ let depMatch = rest.match(/^([A-Za-z0-9][A-Za-z0-9._-]*)/);
226
+ if (!depMatch) {
227
+ continue;
228
+ }
229
+ let depName = depMatch[1];
230
+ let depKey = this._canonicalize(depName);
231
+ // determine depth by counting tree-drawing groups in the prefix
232
+ let prefix = line.substring(0, nameStart);
233
+ let depth = (prefix.match(/(?:[├└│ ][\s─]{2} ?)/g) || []).length;
234
+ // pop stack back to find the parent at depth-1
235
+ while (stack.length > 0 && stack[stack.length - 1].depth >= depth) {
236
+ stack.pop();
237
+ }
238
+ let parentKey = stack.length > 0 ? stack[stack.length - 1].key : null;
239
+ if (parentKey) {
240
+ let parentMarkers = markerData.transitiveMarkers.get(parentKey);
241
+ if (parentMarkers) {
242
+ let marker = parentMarkers.get(depKey);
243
+ if (marker && !evaluateMarker(marker)) {
244
+ continue;
245
+ }
246
+ }
247
+ }
248
+ // resolve version from the version map
249
+ let version = versionMap.get(depKey) || null;
250
+ if (!version) {
251
+ throw new Error(`poetry: package '${depName}' has no resolved version`);
252
+ }
253
+ if (!graph.has(depKey)) {
254
+ let entry = { name: depName, version, children: [] };
255
+ let hashes = markerData.hashMap.get(depKey);
256
+ if (hashes) {
257
+ entry.hashes = hashes;
258
+ }
259
+ graph.set(depKey, entry);
260
+ }
261
+ if (parentKey) {
262
+ let parentEntry = graph.get(parentKey);
263
+ if (parentEntry && !parentEntry.children.includes(depKey)) {
264
+ parentEntry.children.push(depKey);
265
+ }
266
+ }
267
+ stack.push({ key: depKey, depth });
268
+ }
269
+ return { directDeps, graph };
270
+ }
271
+ }
@@ -0,0 +1,55 @@
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[]>;
14
+ export default class Python_uv extends Base_pyproject {
15
+ /**
16
+ * @param {string} manifestDir - directory containing the target pyproject.toml
17
+ * @param {string} workspaceDir - workspace root (for resolving editable install paths)
18
+ * @param {object} parsed - parsed pyproject.toml
19
+ * @param {Object} opts
20
+ * @returns {Promise<{directDeps: string[], graph: Map<string, {name: string, version: string, children: string[]}>}>}
21
+ */
22
+ _getDependencyData(manifestDir: string, workspaceDir: string, parsed: object, opts: any): Promise<{
23
+ directDeps: string[];
24
+ graph: Map<string, {
25
+ name: string;
26
+ version: string;
27
+ children: string[];
28
+ }>;
29
+ }>;
30
+ /**
31
+ * Get the uv export output, either from env var or by running the command.
32
+ * @param {string} manifestDir
33
+ * @param {Object} opts
34
+ * @returns {string}
35
+ */
36
+ _getUvExportOutput(manifestDir: string, opts: any): string;
37
+ /**
38
+ * Parse uv export output into a dependency graph using tree-sitter-requirements
39
+ * for package/version extraction and string parsing for "# via" comments.
40
+ *
41
+ * @param {string} output
42
+ * @param {string} projectName - canonical project name to identify direct deps
43
+ * @param {string} workspaceDir - workspace root (for resolving editable install paths)
44
+ * @returns {Promise<{directDeps: string[], graph: Map<string, {name: string, version: string, children: string[]}>}>}
45
+ */
46
+ _parseUvExport(output: string, projectName: string, workspaceDir: string): Promise<{
47
+ directDeps: string[];
48
+ graph: Map<string, {
49
+ name: string;
50
+ version: string;
51
+ children: string[];
52
+ }>;
53
+ }>;
54
+ }
55
+ import Base_pyproject from './base_pyproject.js';
@@ -0,0 +1,227 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import fg from 'fast-glob';
4
+ import { parse as parseToml } from 'smol-toml';
5
+ import { environmentVariableIsPopulated, getCustomPath, invokeCommand } from '../tools.js';
6
+ import { filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore, toManifestGlobPatterns } from '../workspace.js';
7
+ import Base_pyproject from './base_pyproject.js';
8
+ import { evaluateMarker } from './marker_evaluator.js';
9
+ import { getParser, getPinnedVersionQuery } from './requirements_parser.js';
10
+ export default class Python_uv extends Base_pyproject {
11
+ /** @returns {string} */
12
+ _lockFileName() {
13
+ return 'uv.lock';
14
+ }
15
+ /** @returns {string} */
16
+ _cmdName() {
17
+ return 'uv';
18
+ }
19
+ /**
20
+ * @param {string} manifestDir - directory containing the target pyproject.toml
21
+ * @param {string} workspaceDir - workspace root (for resolving editable install paths)
22
+ * @param {object} parsed - parsed pyproject.toml
23
+ * @param {Object} opts
24
+ * @returns {Promise<{directDeps: string[], graph: Map<string, {name: string, version: string, children: string[]}>}>}
25
+ */
26
+ async _getDependencyData(manifestDir, workspaceDir, parsed, opts) {
27
+ let projectName = this._getProjectName(parsed);
28
+ let uvOutput = this._getUvExportOutput(manifestDir, opts);
29
+ return this._parseUvExport(uvOutput, projectName, workspaceDir);
30
+ }
31
+ /**
32
+ * Get the uv export output, either from env var or by running the command.
33
+ * @param {string} manifestDir
34
+ * @param {Object} opts
35
+ * @returns {string}
36
+ */
37
+ _getUvExportOutput(manifestDir, opts) {
38
+ if (environmentVariableIsPopulated('TRUSTIFY_DA_UV_EXPORT')) {
39
+ return Buffer.from(process.env['TRUSTIFY_DA_UV_EXPORT'], 'base64').toString('ascii');
40
+ }
41
+ let uvBin = getCustomPath('uv', opts);
42
+ return invokeCommand(uvBin, ['export', '--format', 'requirements.txt', '--frozen', '--no-hashes', '--no-dev', '--no-emit-project'], { cwd: manifestDir }).toString();
43
+ }
44
+ /**
45
+ * Parse uv export output into a dependency graph using tree-sitter-requirements
46
+ * for package/version extraction and string parsing for "# via" comments.
47
+ *
48
+ * @param {string} output
49
+ * @param {string} projectName - canonical project name to identify direct deps
50
+ * @param {string} workspaceDir - workspace root (for resolving editable install paths)
51
+ * @returns {Promise<{directDeps: string[], graph: Map<string, {name: string, version: string, children: string[]}>}>}
52
+ */
53
+ async _parseUvExport(output, projectName, workspaceDir) {
54
+ let [parser, pinnedVersionQuery] = await Promise.all([
55
+ getParser(), getPinnedVersionQuery()
56
+ ]);
57
+ let tree = parser.parse(output);
58
+ let root = tree.rootNode;
59
+ let canonProjectName = this._canonicalize(projectName);
60
+ let packages = new Map(); // canonical name -> {name, version, parents: Set}
61
+ let currentPkg = null;
62
+ let collectingVia = false;
63
+ for (let child of root.children) {
64
+ if (child.type === 'global_opt') {
65
+ let optNode = child.children.find(c => c.type === 'option');
66
+ let pathNode = child.children.find(c => c.type === 'path');
67
+ if (optNode?.text === '-e' && pathNode && workspaceDir) {
68
+ let memberDir = path.resolve(workspaceDir, pathNode.text);
69
+ let memberManifest = path.join(memberDir, 'pyproject.toml');
70
+ if (fs.existsSync(memberManifest)) {
71
+ let memberParsed = parseToml(fs.readFileSync(memberManifest, 'utf-8'));
72
+ let name = memberParsed.project?.name || memberParsed.tool?.poetry?.name;
73
+ let version = memberParsed.project?.version || memberParsed.tool?.poetry?.version;
74
+ if (name && version) {
75
+ let key = this._canonicalize(name);
76
+ if (key === canonProjectName) {
77
+ continue;
78
+ }
79
+ currentPkg = { name, version, parents: new Set() };
80
+ packages.set(key, currentPkg);
81
+ collectingVia = false;
82
+ continue;
83
+ }
84
+ }
85
+ }
86
+ currentPkg = null;
87
+ collectingVia = false;
88
+ continue;
89
+ }
90
+ if (child.type === 'requirement') {
91
+ let nameNode = child.children.find(c => c.type === 'package');
92
+ if (!nameNode) {
93
+ continue;
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
+ }
105
+ let name = nameNode.text;
106
+ let version = null;
107
+ let versionMatches = pinnedVersionQuery.matches(child);
108
+ if (versionMatches.length > 0) {
109
+ version = versionMatches[0].captures.find(c => c.name === 'version').node.text;
110
+ }
111
+ if (!version) {
112
+ throw new Error(`uv export: package '${name}' has no pinned version`);
113
+ }
114
+ let key = this._canonicalize(name);
115
+ currentPkg = { name, version, parents: new Set() };
116
+ packages.set(key, currentPkg);
117
+ collectingVia = false;
118
+ continue;
119
+ }
120
+ if (child.type === 'comment' && currentPkg) {
121
+ let text = child.text.trim();
122
+ let viaSingle = text.match(/^# via ([A-Za-z0-9][A-Za-z0-9._-]*)$/);
123
+ if (viaSingle) {
124
+ currentPkg.parents.add(this._canonicalize(viaSingle[1]));
125
+ collectingVia = false;
126
+ continue;
127
+ }
128
+ if (text === '# via') {
129
+ collectingVia = true;
130
+ continue;
131
+ }
132
+ if (collectingVia) {
133
+ let parentMatch = text.match(/^#\s+([A-Za-z0-9][A-Za-z0-9._-]*)$/);
134
+ if (parentMatch) {
135
+ currentPkg.parents.add(this._canonicalize(parentMatch[1]));
136
+ continue;
137
+ }
138
+ collectingVia = false;
139
+ }
140
+ }
141
+ }
142
+ // Build forward dependency map and extract direct deps in one pass
143
+ let graph = new Map();
144
+ let directDeps = [];
145
+ for (let [key, pkg] of packages) {
146
+ graph.set(key, { name: pkg.name, version: pkg.version, children: [] });
147
+ }
148
+ for (let [childKey, pkg] of packages) {
149
+ for (let parentKey of pkg.parents) {
150
+ if (parentKey === canonProjectName) {
151
+ directDeps.push(childKey);
152
+ continue;
153
+ }
154
+ let parentEntry = graph.get(parentKey);
155
+ if (parentEntry) {
156
+ parentEntry.children.push(childKey);
157
+ }
158
+ }
159
+ }
160
+ return { directDeps, graph };
161
+ }
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;
@@ -46,7 +47,10 @@ declare function provideStack(manifest: string, opts?: {}): Provided;
46
47
  * Read project license from Cargo.toml, with fallback to LICENSE file.
47
48
  * Supports the `license` field under `[package]` (single crate / workspace
48
49
  * with root) and under `[workspace.package]` (virtual workspaces).
50
+ * When a member crate uses `license = { workspace = true }`, the actual
51
+ * license is resolved from the workspace root Cargo.toml.
49
52
  * @param {string} manifestPath - path to Cargo.toml
53
+ * @param {object} [metadata] - cargo metadata output (needed for workspace license resolution)
50
54
  * @returns {string|null} SPDX identifier or null
51
55
  */
52
- declare function readLicenseFromManifest(manifestPath: string): string | null;
56
+ declare function readLicenseFromManifest(manifestPath: string, metadata?: object): string | null;
@@ -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
  /**
@@ -71,15 +71,22 @@ function isSupported(manifestName) {
71
71
  * Read project license from Cargo.toml, with fallback to LICENSE file.
72
72
  * Supports the `license` field under `[package]` (single crate / workspace
73
73
  * with root) and under `[workspace.package]` (virtual workspaces).
74
+ * When a member crate uses `license = { workspace = true }`, the actual
75
+ * license is resolved from the workspace root Cargo.toml.
74
76
  * @param {string} manifestPath - path to Cargo.toml
77
+ * @param {object} [metadata] - cargo metadata output (needed for workspace license resolution)
75
78
  * @returns {string|null} SPDX identifier or null
76
79
  */
77
- function readLicenseFromManifest(manifestPath) {
80
+ function readLicenseFromManifest(manifestPath, metadata) {
78
81
  let fromManifest = null;
79
82
  try {
80
83
  let content = fs.readFileSync(manifestPath, 'utf-8');
81
84
  let parsed = parseToml(content);
82
- fromManifest = parsed.package?.license
85
+ let packageLicense = parsed.package?.license;
86
+ if (typeof packageLicense === 'object' && packageLicense?.workspace === true) {
87
+ packageLicense = resolveWorkspaceLicense(parsed, metadata);
88
+ }
89
+ fromManifest = packageLicense
83
90
  || parsed.workspace?.package?.license
84
91
  || null;
85
92
  }
@@ -88,6 +95,26 @@ function readLicenseFromManifest(manifestPath) {
88
95
  }
89
96
  return getLicense(fromManifest, manifestPath);
90
97
  }
98
+ /**
99
+ * Resolve a workspace-inherited license from the workspace root Cargo.toml.
100
+ * @param {object} parsed - the parsed member crate Cargo.toml
101
+ * @param {object} [metadata] - cargo metadata output with workspace_root
102
+ * @returns {string|null} resolved license string or null
103
+ */
104
+ function resolveWorkspaceLicense(parsed, metadata) {
105
+ if (metadata?.workspace_root) {
106
+ let cargoTomlPath = path.join(metadata.workspace_root, 'Cargo.toml');
107
+ try {
108
+ let content = fs.readFileSync(cargoTomlPath, 'utf-8');
109
+ let workspaceParsed = parseToml(content);
110
+ return workspaceParsed.workspace?.package?.license || null;
111
+ }
112
+ catch (_) {
113
+ // fall through
114
+ }
115
+ }
116
+ return parsed.workspace?.package?.license || null;
117
+ }
91
118
  /**
92
119
  * Validates that Cargo.lock exists in the manifest directory or in a parent
93
120
  * workspace root directory. In Cargo workspaces the lock file always lives at
@@ -173,7 +200,7 @@ function getSBOM(manifest, opts = {}, includeTransitive) {
173
200
  let metadata = executeCargoMetadata(cargoBin, manifestDir);
174
201
  let ignoredDeps = getIgnoredDeps(manifest, metadata);
175
202
  let crateType = detectCrateType(metadata);
176
- let license = readLicenseFromManifest(manifest);
203
+ let license = readLicenseFromManifest(manifest, metadata);
177
204
  let sbom;
178
205
  if (crateType === CrateType.WORKSPACE_VIRTUAL) {
179
206
  sbom = handleVirtualWorkspace(manifest, metadata, ignoredDeps, includeTransitive, opts, license);
@@ -25,9 +25,14 @@ export default class Sbom {
25
25
  /**
26
26
  * @param {component} sourceRef current source Component ( Starting from root component by clients)
27
27
  * @param {PackageURL} targetRef current dependency to add to Dependencies list of component sourceRef
28
+ * @param {string} [scope] - Scope of the dependency
29
+ * @param {Array<{alg: string, content: string}>} [targetHashes] - Optional hashes for the target component
28
30
  * @return Sbom
29
31
  */
30
- addDependency(sourceRef: component, targetRef: PackageURL, scope: any): CycloneDxSbom;
32
+ addDependency(sourceRef: component, targetRef: PackageURL, scope?: string, targetHashes?: Array<{
33
+ alg: string;
34
+ content: string;
35
+ }>): CycloneDxSbom;
31
36
  /**
32
37
  * @return String sbom json in a string format
33
38
  */
@@ -45,6 +50,7 @@ export default class Sbom {
45
50
  version: any;
46
51
  scope: any;
47
52
  licenses?: any;
53
+ hashes?: any;
48
54
  };
49
55
  /** This method gets a component object, and a string name, and checks if the name is a substring of the component' purl.
50
56
  * @param {} component to search in its dependencies