(
xmlContent: string,
searchReplacePairs: Array<{ search: string; replace: string }>,
)
| 272 | * @returns The updated XML string with replacements applied |
| 273 | */ |
| 274 | export function replaceXMLParts( |
| 275 | xmlContent: string, |
| 276 | searchReplacePairs: Array<{ search: string; replace: string }>, |
| 277 | ): string { |
| 278 | // Format the XML first to ensure consistent line breaks |
| 279 | let result = formatXML(xmlContent) |
| 280 | |
| 281 | for (const { search, replace } of searchReplacePairs) { |
| 282 | // Also format the search content for consistency |
| 283 | const formattedSearch = formatXML(search) |
| 284 | const searchLines = formattedSearch.split("\n") |
| 285 | |
| 286 | // Split into lines for exact line matching |
| 287 | const resultLines = result.split("\n") |
| 288 | |
| 289 | // Remove trailing empty line if exists (from the trailing \n in search content) |
| 290 | if (searchLines[searchLines.length - 1] === "") { |
| 291 | searchLines.pop() |
| 292 | } |
| 293 | |
| 294 | // Always search from the beginning - pairs may not be in document order |
| 295 | const startLineNum = 0 |
| 296 | |
| 297 | // Try to find match using multiple strategies |
| 298 | let matchFound = false |
| 299 | let matchStartLine = -1 |
| 300 | let matchEndLine = -1 |
| 301 | |
| 302 | // First try: exact match |
| 303 | for ( |
| 304 | let i = startLineNum; |
| 305 | i <= resultLines.length - searchLines.length; |
| 306 | i++ |
| 307 | ) { |
| 308 | let matches = true |
| 309 | |
| 310 | for (let j = 0; j < searchLines.length; j++) { |
| 311 | if (resultLines[i + j] !== searchLines[j]) { |
| 312 | matches = false |
| 313 | break |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | if (matches) { |
| 318 | matchStartLine = i |
| 319 | matchEndLine = i + searchLines.length |
| 320 | matchFound = true |
| 321 | break |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | // Second try: line-trimmed match (fallback) |
| 326 | if (!matchFound) { |
| 327 | for ( |
| 328 | let i = startLineNum; |
| 329 | i <= resultLines.length - searchLines.length; |
| 330 | i++ |
| 331 | ) { |
no test coverage detected