@trustify-da/trustify-da-javascript-client 0.3.0-ea.b68592e → 0.3.0-ea.b77d624

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 (57) hide show
  1. package/README.md +189 -3
  2. package/dist/package.json +16 -7
  3. package/dist/src/analysis.d.ts +7 -0
  4. package/dist/src/analysis.js +29 -13
  5. package/dist/src/cli.js +106 -2
  6. package/dist/src/cyclone_dx_sbom.d.ts +13 -0
  7. package/dist/src/cyclone_dx_sbom.js +39 -1
  8. package/dist/src/index.d.ts +5 -1
  9. package/dist/src/index.js +12 -25
  10. package/dist/src/oci_image/images.js +15 -1
  11. package/dist/src/package_version.d.ts +8 -0
  12. package/dist/src/package_version.js +31 -0
  13. package/dist/src/provider.js +3 -1
  14. package/dist/src/providers/base_java.d.ts +53 -0
  15. package/dist/src/providers/base_java.js +64 -17
  16. package/dist/src/providers/base_javascript.d.ts +54 -0
  17. package/dist/src/providers/base_javascript.js +105 -3
  18. package/dist/src/providers/containerfile_parser.d.ts +5 -0
  19. package/dist/src/providers/containerfile_parser.js +20 -0
  20. package/dist/src/providers/golang_gomodules.js +49 -7
  21. package/dist/src/providers/java_gradle.d.ts +48 -0
  22. package/dist/src/providers/java_gradle.js +196 -18
  23. package/dist/src/providers/java_maven.d.ts +28 -8
  24. package/dist/src/providers/java_maven.js +104 -10
  25. package/dist/src/providers/javascript_bun.d.ts +12 -0
  26. package/dist/src/providers/javascript_bun.js +42 -1
  27. package/dist/src/providers/javascript_npm.d.ts +13 -0
  28. package/dist/src/providers/javascript_npm.js +40 -1
  29. package/dist/src/providers/javascript_pnpm.d.ts +13 -0
  30. package/dist/src/providers/javascript_pnpm.js +47 -1
  31. package/dist/src/providers/javascript_yarn.d.ts +12 -0
  32. package/dist/src/providers/javascript_yarn.js +75 -2
  33. package/dist/src/providers/manifest.js +6 -3
  34. package/dist/src/providers/oci_dockerfile.d.ts +51 -0
  35. package/dist/src/providers/oci_dockerfile.js +177 -0
  36. package/dist/src/providers/processors/yarn_berry_processor.d.ts +5 -1
  37. package/dist/src/providers/processors/yarn_berry_processor.js +3 -2
  38. package/dist/src/providers/processors/yarn_classic_processor.d.ts +5 -1
  39. package/dist/src/providers/processors/yarn_classic_processor.js +8 -6
  40. package/dist/src/providers/python_controller.js +4 -1
  41. package/dist/src/providers/requirements_parser.js +1 -1
  42. package/dist/src/providers/rust_cargo.js +70 -29
  43. package/dist/src/providers/tree-sitter-containerfile.wasm +0 -0
  44. package/dist/src/remediate.d.ts +21 -0
  45. package/dist/src/remediate.js +149 -0
  46. package/dist/src/remediation.d.ts +57 -0
  47. package/dist/src/remediation.js +436 -0
  48. package/dist/src/remediation_report.d.ts +40 -0
  49. package/dist/src/remediation_report.js +159 -0
  50. package/dist/src/sbom.d.ts +11 -0
  51. package/dist/src/sbom.js +10 -0
  52. package/dist/src/tools.js +24 -1
  53. package/dist/src/updaters/maven_updater.d.ts +26 -0
  54. package/dist/src/updaters/maven_updater.js +322 -0
  55. package/dist/src/updaters/toml_updater.d.ts +33 -0
  56. package/dist/src/updaters/toml_updater.js +244 -0
  57. package/package.json +17 -8
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Report generator that transforms remediation extractor output into structured
3
+ * markdown for PR bodies, CLI dry-run output, and JSON.
4
+ */
5
+ import { SEVERITY_ORDER } from './remediation.js';
6
+ /**
7
+ * Generates a formatted report from an array of remediation entries.
8
+ *
9
+ * @param {Array<{purl: string, groupId: string, artifactId: string, currentVersion: string,
10
+ * fixedInVersion: string, fixedInPurl: string, provider: string, source: string,
11
+ * advisories: Array<{id: string, url: string}>, severity: string, cves: string[]}>} remediations
12
+ * @param {object} [options]
13
+ * @param {'dependency'|'bundle'} [options.groupBy='dependency'] - grouping strategy
14
+ * @param {'markdown'|'json'} [options.format='markdown'] - output format
15
+ * @param {boolean} [options.dryRun=false] - when true, produces tabular summary
16
+ * @returns {string}
17
+ */
18
+ export function generateReport(remediations, options = {}) {
19
+ const { groupBy = 'dependency', format = 'markdown', dryRun = false } = options;
20
+ if (!remediations || remediations.length === 0) {
21
+ return format === 'json' ? '[]' : 'No remediations found.';
22
+ }
23
+ if (format === 'json') {
24
+ return JSON.stringify(remediations, null, '\t');
25
+ }
26
+ if (dryRun) {
27
+ return generateDryRunReport(remediations);
28
+ }
29
+ if (groupBy === 'bundle') {
30
+ return generateBundledReport(remediations);
31
+ }
32
+ return generatePerDependencyReport(remediations);
33
+ }
34
+ /**
35
+ * Generates a per-dependency markdown report with one section per remediation entry.
36
+ * @param {Array<object>} remediations
37
+ * @returns {string}
38
+ */
39
+ function generatePerDependencyReport(remediations) {
40
+ const sections = remediations.map(rem => {
41
+ const depName = rem.groupId
42
+ ? `${rem.groupId}:${rem.artifactId}`
43
+ : rem.artifactId;
44
+ const lines = [
45
+ `## Security Update: ${depName} ${rem.currentVersion} → ${rem.fixedInVersion}`,
46
+ '',
47
+ `**Provider:** ${rem.provider} | **Source:** ${rem.source}`,
48
+ '',
49
+ ];
50
+ if (rem.cves && rem.cves.length > 0) {
51
+ lines.push('### Vulnerabilities resolved');
52
+ lines.push('');
53
+ lines.push('| CVE | Severity | Advisory |');
54
+ lines.push('| --- | --- | --- |');
55
+ const advisoryLinks = formatAdvisoryLinks(rem.advisories);
56
+ for (const cve of rem.cves) {
57
+ lines.push(`| ${cve} | ${rem.severity} | ${advisoryLinks} |`);
58
+ }
59
+ }
60
+ return lines.join('\n');
61
+ });
62
+ return sections.join('\n\n');
63
+ }
64
+ /**
65
+ * Generates a bundled markdown report grouping all remediations by severity.
66
+ * @param {Array<object>} remediations
67
+ * @returns {string}
68
+ */
69
+ function generateBundledReport(remediations) {
70
+ const lines = ['# Security Update Summary', ''];
71
+ const bySeverity = groupBySeverity(remediations);
72
+ for (const severity of [...SEVERITY_ORDER].reverse()) {
73
+ const group = bySeverity.get(severity);
74
+ if (!group || group.length === 0) {
75
+ continue;
76
+ }
77
+ lines.push(`## ${severity}`);
78
+ lines.push('');
79
+ lines.push('| Dependency | Current | Fixed | Provider | CVEs | Advisory |');
80
+ lines.push('| --- | --- | --- | --- | --- | --- |');
81
+ for (const rem of group) {
82
+ const depName = rem.groupId
83
+ ? `${rem.groupId}:${rem.artifactId}`
84
+ : rem.artifactId;
85
+ const cves = (rem.cves || []).join(', ');
86
+ const advisoryLinks = formatAdvisoryLinks(rem.advisories);
87
+ lines.push(`| ${depName} | ${rem.currentVersion} | ${rem.fixedInVersion}`
88
+ + ` | ${rem.provider} | ${cves} | ${advisoryLinks} |`);
89
+ }
90
+ lines.push('');
91
+ }
92
+ return lines.join('\n').trimEnd();
93
+ }
94
+ /**
95
+ * Generates a tabular dry-run summary of proposed changes.
96
+ * @param {Array<object>} remediations
97
+ * @returns {string}
98
+ */
99
+ function generateDryRunReport(remediations) {
100
+ const lines = [
101
+ 'Proposed dependency updates:',
102
+ '',
103
+ '| Dependency | Current | Fixed | Severity | Provider |',
104
+ '| --- | --- | --- | --- | --- |',
105
+ ];
106
+ for (const rem of remediations) {
107
+ const depName = rem.groupId
108
+ ? `${rem.groupId}:${rem.artifactId}`
109
+ : rem.artifactId;
110
+ lines.push(`| ${depName} | ${rem.currentVersion} | ${rem.fixedInVersion}`
111
+ + ` | ${rem.severity} | ${rem.provider} |`);
112
+ }
113
+ return lines.join('\n');
114
+ }
115
+ /**
116
+ * Groups remediations by their severity.
117
+ * @param {Array<object>} remediations
118
+ * @returns {Map<string, Array<object>>}
119
+ */
120
+ function groupBySeverity(remediations) {
121
+ const map = new Map();
122
+ for (const severity of SEVERITY_ORDER) {
123
+ map.set(severity, []);
124
+ }
125
+ for (const rem of remediations) {
126
+ const sev = rem.severity || 'UNKNOWN';
127
+ if (!map.has(sev)) {
128
+ map.set(sev, []);
129
+ }
130
+ map.get(sev).push(rem);
131
+ }
132
+ return map;
133
+ }
134
+ /**
135
+ * Formats advisory entries into markdown links or plain text.
136
+ * @param {Array<{id: string, url: string}>} advisories
137
+ * @returns {string}
138
+ */
139
+ function formatAdvisoryLinks(advisories) {
140
+ if (!advisories || advisories.length === 0) {
141
+ return '-';
142
+ }
143
+ return advisories
144
+ .map(adv => adv.url ? `[${adv.id}](${adv.url})` : adv.id)
145
+ .join(', ');
146
+ }
147
+ /**
148
+ * Generates a deterministic deduplication key for a remediation entry.
149
+ * Suitable for checking existing PR titles or branch names.
150
+ *
151
+ * @param {object} remediation - a single remediation entry
152
+ * @returns {string} stable key in the form `groupId:artifactId:newVersion`
153
+ */
154
+ export function generateDeduplicationKey(remediation) {
155
+ const group = remediation.groupId || '';
156
+ const artifact = remediation.artifactId || '';
157
+ const version = remediation.fixedInVersion || '';
158
+ return `${group}:${artifact}:${version}`;
159
+ }
@@ -33,6 +33,17 @@ export default class Sbom {
33
33
  alg: string;
34
34
  content: string;
35
35
  }>): CycloneDxSbom;
36
+ /**
37
+ * Attach hashes to existing components by matching their PURL. Post-processing
38
+ * step used by ecosystem-specific providers (e.g. Maven) to enrich the SBOM
39
+ * with artifact hashes without leaking their concern into the shared parser.
40
+ * @param {Map<string, Array<{alg: string, content: string}>>} hashMap - PURL→hashes map
41
+ * @return {Sbom}
42
+ */
43
+ attachHashes(hashMap: Map<string, Array<{
44
+ alg: string;
45
+ content: string;
46
+ }>>): Sbom;
36
47
  /**
37
48
  * @return String sbom json in a string format
38
49
  */
package/dist/src/sbom.js CHANGED
@@ -50,6 +50,16 @@ export default class Sbom {
50
50
  addDependency(sourceRef, targetRef, scope, targetHashes) {
51
51
  return this.sbomModel.addDependency(sourceRef, targetRef, scope, targetHashes);
52
52
  }
53
+ /**
54
+ * Attach hashes to existing components by matching their PURL. Post-processing
55
+ * step used by ecosystem-specific providers (e.g. Maven) to enrich the SBOM
56
+ * with artifact hashes without leaking their concern into the shared parser.
57
+ * @param {Map<string, Array<{alg: string, content: string}>>} hashMap - PURL→hashes map
58
+ * @return {Sbom}
59
+ */
60
+ attachHashes(hashMap) {
61
+ return this.sbomModel.attachHashes(hashMap);
62
+ }
53
63
  /**
54
64
  * @return String sbom json in a string format
55
65
  */
package/dist/src/tools.js CHANGED
@@ -42,6 +42,28 @@ export function getCustom(key, def = null, opts = {}) {
42
42
  }
43
43
  return key in process.env ? process.env[key] : key in opts && typeof opts[key] === 'string' ? opts[key] : def;
44
44
  }
45
+ /**
46
+ * Validates that an executable path does not use directory traversal or relative segments.
47
+ * @param {string} binPath - The executable path to validate.
48
+ * @returns {string} The validated path.
49
+ * @throws {Error} If the path contains '..' segments or is a relative path with separators.
50
+ */
51
+ function validateExecutablePath(binPath) {
52
+ if (typeof binPath !== 'string' || binPath.length === 0) {
53
+ throw new Error('Executable path rejected: expected a non-empty string');
54
+ }
55
+ if (binPath.startsWith('./') || binPath.startsWith('.\\')) {
56
+ throw new Error(`Executable path rejected: relative paths starting with './' are not allowed: ${binPath}`);
57
+ }
58
+ const segments = binPath.split(/[/\\]/);
59
+ if (segments.includes('..')) {
60
+ throw new Error(`Executable path rejected: path contains directory traversal segment (..): ${binPath}`);
61
+ }
62
+ if ((binPath.includes('/') || binPath.includes('\\')) && !path.isAbsolute(binPath)) {
63
+ throw new Error(`Executable path rejected: relative paths are not allowed, use an absolute path or a bare command name: ${binPath}`);
64
+ }
65
+ return binPath;
66
+ }
45
67
  /**
46
68
  * Utility function for looking up custom variable for a binary path.
47
69
  * Will look in the environment variables (1) or in opts (2) for a key with TRUSTIFY_DA_x_PATH, x is an
@@ -53,7 +75,8 @@ export function getCustom(key, def = null, opts = {}) {
53
75
  * original name supplied
54
76
  */
55
77
  export function getCustomPath(name, opts = {}) {
56
- return getCustom(`TRUSTIFY_DA_${name.toUpperCase()}_PATH`, name, opts);
78
+ const resolvedPath = getCustom(`TRUSTIFY_DA_${name.toUpperCase()}_PATH`, name, opts);
79
+ return validateExecutablePath(resolvedPath);
57
80
  }
58
81
  /**
59
82
  * Utility function for determining whether wrappers for build tools such as gradlew/mvnw should be
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Updates dependency versions in a Maven pom.xml while preserving file formatting.
3
+ *
4
+ * Uses `fast-xml-parser` to understand the XML structure (dependencies and properties),
5
+ * then performs position-based string splice to replace version strings without altering
6
+ * any other formatting, comments, whitespace, or indentation.
7
+ *
8
+ * Supports `${property}` indirection: when a dependency's `<version>` is a property
9
+ * reference, the updater resolves the property chain (including recursive references)
10
+ * and updates the terminal property value in `<properties>` instead.
11
+ *
12
+ * @param {string} pomContent - the raw pom.xml file content
13
+ * @param {Array<{groupId: string, artifactId: string, newVersion: string}>} versionChanges -
14
+ * list of version changes to apply
15
+ * @returns {{content: string, applied: Array, skipped: Array}} the updated content and
16
+ * lists of applied and skipped changes
17
+ */
18
+ export function updateMavenVersions(pomContent: string, versionChanges: Array<{
19
+ groupId: string;
20
+ artifactId: string;
21
+ newVersion: string;
22
+ }>): {
23
+ content: string;
24
+ applied: any[];
25
+ skipped: any[];
26
+ };
@@ -0,0 +1,322 @@
1
+ import { XMLParser } from 'fast-xml-parser';
2
+ /**
3
+ * Extracts the trimmed text content of a simple XML element from a string block.
4
+ * @param {string} block - the XML text to search within
5
+ * @param {string} tagName - the element name whose content to extract
6
+ * @returns {string|null} the trimmed text content, or null if not found
7
+ */
8
+ function extractTagContent(block, tagName) {
9
+ const openTag = `<${tagName}>`;
10
+ const closeTag = `</${tagName}>`;
11
+ const start = block.indexOf(openTag);
12
+ if (start === -1) {
13
+ return null;
14
+ }
15
+ const contentStart = start + openTag.length;
16
+ const end = block.indexOf(closeTag, contentStart);
17
+ if (end === -1) {
18
+ return null;
19
+ }
20
+ return block.substring(contentStart, end).trim();
21
+ }
22
+ /**
23
+ * Finds the character positions of an XML element's text content within the raw file.
24
+ * Returns the start (inclusive) and end (exclusive) offsets of the text between the
25
+ * opening and closing tags.
26
+ * @param {string} content - full raw XML content
27
+ * @param {number} searchStart - start offset to search from
28
+ * @param {number} searchEnd - end offset to search within
29
+ * @param {string} tagName - the element name whose content position to locate
30
+ * @returns {{start: number, end: number}|null} character offsets, or null if not found
31
+ */
32
+ function findTagContentPosition(content, searchStart, searchEnd, tagName) {
33
+ const openTag = `<${tagName}>`;
34
+ const closeTag = `</${tagName}>`;
35
+ const tagStart = content.indexOf(openTag, searchStart);
36
+ if (tagStart === -1 || tagStart >= searchEnd) {
37
+ return null;
38
+ }
39
+ const contentStart = tagStart + openTag.length;
40
+ const tagEnd = content.indexOf(closeTag, contentStart);
41
+ if (tagEnd === -1 || tagEnd > searchEnd) {
42
+ return null;
43
+ }
44
+ return { start: contentStart, end: tagEnd };
45
+ }
46
+ /**
47
+ * Checks whether the character immediately following a tag prefix indicates
48
+ * that the prefix is the complete tag name (e.g. `<dependency>` vs `<dependencyManagement>`).
49
+ * @param {string} char - the character after the tag prefix
50
+ * @returns {boolean} true if the character terminates the tag name
51
+ */
52
+ function isTagBoundary(char) {
53
+ return char === '>' || char === ' ' || char === '\t'
54
+ || char === '\n' || char === '\r' || char === '/';
55
+ }
56
+ /**
57
+ * Finds the text content position of a `<version>` element within the first
58
+ * `<dependency>` block matching the given groupId and artifactId.
59
+ * Searches through all `<dependency>` elements in the file, covering both
60
+ * `<dependencies>` and `<dependencyManagement>` sections.
61
+ * @param {string} content - full raw pom.xml content
62
+ * @param {string} groupId - the dependency's groupId to match
63
+ * @param {string} artifactId - the dependency's artifactId to match
64
+ * @returns {{start: number, end: number}|null} version content offsets, or null
65
+ */
66
+ function findDependencyVersionPosition(content, groupId, artifactId) {
67
+ let searchStart = 0;
68
+ const TAG_PREFIX = '<dependency';
69
+ const CLOSE_TAG = '</dependency>';
70
+ while (searchStart < content.length) {
71
+ const start = content.indexOf(TAG_PREFIX, searchStart);
72
+ if (start === -1) {
73
+ break;
74
+ }
75
+ // Verify this is exactly <dependency> and not <dependencyManagement> etc.
76
+ const charAfterTag = content.charAt(start + TAG_PREFIX.length);
77
+ if (!isTagBoundary(charAfterTag)) {
78
+ searchStart = start + 1;
79
+ continue;
80
+ }
81
+ // Find closing </dependency>
82
+ const end = content.indexOf(CLOSE_TAG, start + TAG_PREFIX.length);
83
+ if (end === -1) {
84
+ break;
85
+ }
86
+ const blockEnd = end + CLOSE_TAG.length;
87
+ const block = content.substring(start, blockEnd);
88
+ const gid = extractTagContent(block, 'groupId');
89
+ const aid = extractTagContent(block, 'artifactId');
90
+ if (gid === groupId && aid === artifactId) {
91
+ const pos = findTagContentPosition(content, start, blockEnd, 'version');
92
+ if (pos) {
93
+ return pos;
94
+ }
95
+ // Matching dependency but no <version> element; continue searching
96
+ // (the version may be in <dependencyManagement>)
97
+ }
98
+ searchStart = blockEnd;
99
+ }
100
+ return null;
101
+ }
102
+ /**
103
+ * Finds the text content position of a property element inside a `<properties>` block.
104
+ * Searches through all `<properties>` blocks in the file.
105
+ * @param {string} content - full raw pom.xml content
106
+ * @param {string} propName - the property element name to locate
107
+ * @returns {{start: number, end: number}|null} property value offsets, or null
108
+ */
109
+ function findPropertyPosition(content, propName) {
110
+ let searchStart = 0;
111
+ const TAG_PREFIX = '<properties';
112
+ const CLOSE_TAG = '</properties>';
113
+ while (searchStart < content.length) {
114
+ const propsStart = content.indexOf(TAG_PREFIX, searchStart);
115
+ if (propsStart === -1) {
116
+ break;
117
+ }
118
+ // Verify this is exactly <properties> and not some other tag
119
+ const charAfter = content.charAt(propsStart + TAG_PREFIX.length);
120
+ if (!isTagBoundary(charAfter)) {
121
+ searchStart = propsStart + 1;
122
+ continue;
123
+ }
124
+ const propsCloseStart = content.indexOf(CLOSE_TAG, propsStart);
125
+ if (propsCloseStart === -1) {
126
+ break;
127
+ }
128
+ const propsBlockEnd = propsCloseStart + CLOSE_TAG.length;
129
+ const result = findTagContentPosition(content, propsStart, propsBlockEnd, propName);
130
+ if (result) {
131
+ return result;
132
+ }
133
+ searchStart = propsBlockEnd;
134
+ }
135
+ return null;
136
+ }
137
+ /**
138
+ * Resolves a Maven property chain, following `${propName}` references through
139
+ * the properties map until a concrete (non-reference) value is reached.
140
+ * Detects circular references via a visited set.
141
+ * @param {string} propName - the initial property name to resolve
142
+ * @param {Object} properties - properties map from the parsed XML
143
+ * @param {Set<string>} [visited] - visited property names (for cycle detection)
144
+ * @returns {{terminalPropName: string, resolvedValue: string}|{error: string}}
145
+ */
146
+ function resolvePropertyChain(propName, properties, visited = new Set()) {
147
+ if (visited.has(propName)) {
148
+ const chain = [...visited, propName].join(' -> ');
149
+ return { error: `Circular property reference detected: ${chain}` };
150
+ }
151
+ visited.add(propName);
152
+ const value = properties[propName];
153
+ if (value == null) {
154
+ return { error: `Property '${propName}' not found in <properties>` };
155
+ }
156
+ const valueStr = String(value);
157
+ const propMatch = valueStr.match(/^\$\{(.+)\}$/);
158
+ if (propMatch) {
159
+ return resolvePropertyChain(propMatch[1], properties, visited);
160
+ }
161
+ return { terminalPropName: propName, resolvedValue: valueStr };
162
+ }
163
+ /**
164
+ * Updates dependency versions in a Maven pom.xml while preserving file formatting.
165
+ *
166
+ * Uses `fast-xml-parser` to understand the XML structure (dependencies and properties),
167
+ * then performs position-based string splice to replace version strings without altering
168
+ * any other formatting, comments, whitespace, or indentation.
169
+ *
170
+ * Supports `${property}` indirection: when a dependency's `<version>` is a property
171
+ * reference, the updater resolves the property chain (including recursive references)
172
+ * and updates the terminal property value in `<properties>` instead.
173
+ *
174
+ * @param {string} pomContent - the raw pom.xml file content
175
+ * @param {Array<{groupId: string, artifactId: string, newVersion: string}>} versionChanges -
176
+ * list of version changes to apply
177
+ * @returns {{content: string, applied: Array, skipped: Array}} the updated content and
178
+ * lists of applied and skipped changes
179
+ */
180
+ export function updateMavenVersions(pomContent, versionChanges) {
181
+ if (!versionChanges || versionChanges.length === 0) {
182
+ return { content: pomContent, applied: [], skipped: [] };
183
+ }
184
+ const parser = new XMLParser({
185
+ parseTagValue: false,
186
+ commentPropName: '#comment',
187
+ });
188
+ let parsed;
189
+ try {
190
+ parsed = parser.parse(pomContent);
191
+ }
192
+ catch (e) {
193
+ return {
194
+ content: pomContent,
195
+ applied: [],
196
+ skipped: versionChanges.map(vc => ({
197
+ groupId: vc.groupId,
198
+ artifactId: vc.artifactId,
199
+ newVersion: vc.newVersion,
200
+ reason: `Failed to parse pom.xml: ${e.message}`,
201
+ })),
202
+ };
203
+ }
204
+ const project = parsed?.project;
205
+ if (!project) {
206
+ return {
207
+ content: pomContent,
208
+ applied: [],
209
+ skipped: versionChanges.map(vc => ({
210
+ groupId: vc.groupId,
211
+ artifactId: vc.artifactId,
212
+ newVersion: vc.newVersion,
213
+ reason: 'No <project> element found in pom.xml',
214
+ })),
215
+ };
216
+ }
217
+ const properties = project.properties || {};
218
+ const applied = [];
219
+ const skipped = [];
220
+ /** @type {Map<number, {start: number, end: number, newValue: string}>} */
221
+ const replacementsByPosition = new Map();
222
+ for (const change of versionChanges) {
223
+ const versionPos = findDependencyVersionPosition(pomContent, change.groupId, change.artifactId);
224
+ if (!versionPos) {
225
+ skipped.push({
226
+ groupId: change.groupId,
227
+ artifactId: change.artifactId,
228
+ newVersion: change.newVersion,
229
+ reason: 'Dependency not found in pom.xml or has no <version> element',
230
+ });
231
+ continue;
232
+ }
233
+ const currentVersion = pomContent.substring(versionPos.start, versionPos.end);
234
+ const propMatch = currentVersion.match(/^\$\{(.+)\}$/);
235
+ if (propMatch) {
236
+ const resolved = resolvePropertyChain(propMatch[1], properties);
237
+ if (resolved.error) {
238
+ skipped.push({
239
+ groupId: change.groupId,
240
+ artifactId: change.artifactId,
241
+ newVersion: change.newVersion,
242
+ reason: resolved.error,
243
+ });
244
+ continue;
245
+ }
246
+ const propPos = findPropertyPosition(pomContent, resolved.terminalPropName);
247
+ if (!propPos) {
248
+ skipped.push({
249
+ groupId: change.groupId,
250
+ artifactId: change.artifactId,
251
+ newVersion: change.newVersion,
252
+ reason: `Could not locate property '${resolved.terminalPropName}' in pom.xml`,
253
+ });
254
+ continue;
255
+ }
256
+ // Deduplicate: multiple deps may share the same property
257
+ const existing = replacementsByPosition.get(propPos.start);
258
+ if (existing) {
259
+ if (existing.newValue !== change.newVersion) {
260
+ skipped.push({
261
+ groupId: change.groupId,
262
+ artifactId: change.artifactId,
263
+ newVersion: change.newVersion,
264
+ reason: `Property '${resolved.terminalPropName}' already targeted `
265
+ + `with a different version '${existing.newValue}'`,
266
+ });
267
+ continue;
268
+ }
269
+ // Same replacement already queued; record as applied without duplicating
270
+ }
271
+ else {
272
+ replacementsByPosition.set(propPos.start, {
273
+ start: propPos.start,
274
+ end: propPos.end,
275
+ newValue: change.newVersion,
276
+ });
277
+ }
278
+ applied.push({
279
+ groupId: change.groupId,
280
+ artifactId: change.artifactId,
281
+ newVersion: change.newVersion,
282
+ type: 'property',
283
+ property: resolved.terminalPropName,
284
+ });
285
+ }
286
+ else {
287
+ const existing = replacementsByPosition.get(versionPos.start);
288
+ if (existing) {
289
+ if (existing.newValue !== change.newVersion) {
290
+ skipped.push({
291
+ groupId: change.groupId,
292
+ artifactId: change.artifactId,
293
+ newVersion: change.newVersion,
294
+ reason: `Version already targeted with a different version '${existing.newValue}'`,
295
+ });
296
+ continue;
297
+ }
298
+ }
299
+ else {
300
+ replacementsByPosition.set(versionPos.start, {
301
+ start: versionPos.start,
302
+ end: versionPos.end,
303
+ newValue: change.newVersion,
304
+ });
305
+ }
306
+ applied.push({
307
+ groupId: change.groupId,
308
+ artifactId: change.artifactId,
309
+ newVersion: change.newVersion,
310
+ type: 'direct',
311
+ });
312
+ }
313
+ }
314
+ // Sort replacements by position descending to preserve offsets during splice
315
+ const sortedReplacements = [...replacementsByPosition.values()]
316
+ .sort((a, b) => b.start - a.start);
317
+ let result = pomContent;
318
+ for (const r of sortedReplacements) {
319
+ result = result.substring(0, r.start) + r.newValue + result.substring(r.end);
320
+ }
321
+ return { content: result, applied, skipped };
322
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Updates dependency versions in a Gradle version catalog (libs.versions.toml) file.
3
+ *
4
+ * Supports two version declaration patterns:
5
+ * - Centralized: [versions] section defines version aliases, [libraries] references via version.ref
6
+ * - Inline: [libraries] entries include version = "x.y.z" directly
7
+ *
8
+ * Uses smol-toml parse() to locate keys, then performs position-based string replacement
9
+ * on the raw content to preserve formatting and comments.
10
+ *
11
+ * @param {string} tomlContent - raw TOML file content
12
+ * @param {Array<{groupId: string, artifactId: string, newVersion: string}>} versionChanges
13
+ * @returns {{content: string, applied: Array<{groupId: string, artifactId: string, newVersion: string, oldVersion: string}>, skipped: Array<{groupId: string, artifactId: string, newVersion: string, reason: string}>}}
14
+ */
15
+ export function updateTomlVersions(tomlContent: string, versionChanges: Array<{
16
+ groupId: string;
17
+ artifactId: string;
18
+ newVersion: string;
19
+ }>): {
20
+ content: string;
21
+ applied: Array<{
22
+ groupId: string;
23
+ artifactId: string;
24
+ newVersion: string;
25
+ oldVersion: string;
26
+ }>;
27
+ skipped: Array<{
28
+ groupId: string;
29
+ artifactId: string;
30
+ newVersion: string;
31
+ reason: string;
32
+ }>;
33
+ };