1. /**
  2. * Sorts HTTP request records for backward compatibility with default values.
  3. *
  4. * @param {Array<Object>} requests An array of HTTP request records.
  5. * @returns {Array<Object>} The sorted array of HTTP request records.
  6. */
  7. function sortRequestsForCompatibility(requests) {
  8. if (!Array.isArray(requests)) {
  9. return []; // Handle invalid input
  10. }
  11. // Sort by method, then by URL, then by headers (for consistency).
  12. requests.sort((a, b) => {
  13. const methodComparison = a.method.localeCompare(b.method); // Case-sensitive comparison
  14. if (methodComparison !== 0) {
  15. return methodComparison;
  16. }
  17. const urlComparison = a.url.localeCompare(b.url); // Case-sensitive comparison
  18. if (urlComparison !== 0) {
  19. return urlComparison;
  20. }
  21. // If method and URL are the same, compare headers.
  22. // This ensures consistent ordering when default values are applied.
  23. const headerComparison = Object.keys(a.headers)
  24. .sort() // Sort keys alphabetically
  25. .reduce((diff, headerName) => {
  26. const headerA = a.headers[headerName] || '';
  27. const headerB = b.headers[headerName] || '';
  28. if (headerA.localeCompare(headerB) !== 0) {
  29. return headerA.localeCompare(headerB);
  30. }
  31. return diff;
  32. }, 0);
  33. return headerComparison;
  34. });
  35. return requests;
  36. }

Add your comment