~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/hydraulophone

An unofficial YouTube Music app for iPhone, iPad, and Mac.

0
0
main
1026 lines · 31.6 KB Raw History
import Foundation
import Testing

@testable import HydraulophoneCore

// Request fixtures share one URLProtocol recorder; serialize their lifetimes.
@Suite(.serialized)
struct CatalogResponseParserTests {
  // Synthetic equivalents of structural-only simulator observations on
  // 2026-09-23. No response values or account payloads were retained.
  @Test
  func searchAcceptsItemSectionAndCardShelfLayouts() throws {
    let data = try fixtureData([
      "contents": [
        "tabbedSearchResultsRenderer": [
          "tabs": [
            [
              "tabRenderer": [
                "content": [
                  "sectionListRenderer": [
                    "contents": [
                      ["musicCardShelfRenderer": ["contents": [song(id: "card", title: "Card")]]],
                      [
                        "itemSectionRenderer": ["contents": [song(id: "section", title: "Section")]]
                      ],
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ])
    let page = try CatalogResponseParser.searchPage(from: data)
    #expect(page.items.map(\.id) == ["song-card", "song-section"])
  }

  @Test
  func initialTrackPageFallsBackToItsEnclosingSecondarySectionToken() throws {
    let data = try fixtureData([
      "contents": [
        "twoColumnBrowseResultsRenderer": [
          "secondaryContents": [
            "sectionListRenderer": [
              "contents": [
                ["musicPlaylistShelfRenderer": ["contents": [song(id: "one", title: "One")]]]
              ],
              "continuations": [
                ["nextContinuationData": ["continuation": "secondary-next"]]
              ],
            ]
          ]
        ]
      ]
    ])
    let page = try CatalogResponseParser.playlistTrackPage(from: data)
    #expect(page.items.map(\.id) == ["one"])
    #expect(page.next?.rawValue == "secondary-next")
  }

  @Test
  func continuationQueryOptionsAreBothOpaqueAndAllowlisted() throws {
    let builder = InnerTubeRequestBuilder(configuration: .auraWebRemix)
    let request = try builder.makeRequest(
      endpoint: "search",
      body: Data(),
      queryItems: [
        URLQueryItem(name: "continuation", value: "opaque/next?="),
        URLQueryItem(name: "ctoken", value: "opaque/next?="),
      ]
    )
    let requestURL = try #require(request.url)
    let queryItems = try #require(
      URLComponents(url: requestURL, resolvingAgainstBaseURL: false)?.queryItems
    )
    #expect(queryItems.first(where: { $0.name == "continuation" })?.value == "opaque/next?=")
    #expect(queryItems.first(where: { $0.name == "ctoken" })?.value == "opaque/next?=")
    #expect(
      throws: InnerTubeError.self,
      performing: {
        try builder.makeRequest(
          endpoint: "search",
          body: Data(),
          queryItems: [URLQueryItem(name: "key", value: "not-allowed")]
        )
      }
    )
  }

  @Test
  func homeParsesSupportedItemsFiltersAndScopedContinuation() throws {
    let data = try fixtureData([
      "contents": [
        "singleColumnBrowseResultsRenderer": [
          "tabs": [
            [
              "tabRenderer": [
                "content": [
                  "sectionListRenderer": [
                    "header": [
                      "chipCloudRenderer": [
                        "chips": [
                          [
                            "chipCloudChipRenderer": [
                              "text": ["simpleText": "For you"],
                              "navigationEndpoint": [
                                "browseEndpoint": ["params": "filter-params"]
                              ],
                            ]
                          ]
                        ]
                      ]
                    ],
                    "contents": [
                      carousel(
                        title: "Made for you",
                        items: [
                          song(id: "song-1", title: "One"),
                          playlist(id: "PLfixture", title: "A playlist"),
                          album(id: "MPREfixture", title: "An album"),
                          artist(id: "UCunsupported", title: "Not a catalog item"),
                        ]
                      ),
                      carousel(
                        title: "Made for you",
                        items: [song(id: "song-2", title: "Two")]
                      ),
                    ],
                    "continuations": [
                      ["nextContinuationData": ["continuation": "home-next-token"]]
                    ],
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ])

    let page = try CatalogResponseParser.homePage(
      from: data,
      sectionIDPrefix: "home-anonymous"
    )
    #expect(page.filters == [HomeFilter(title: "For you", params: "filter-params")])
    #expect(page.sections.count == 2)
    #expect(page.sections[0].title == page.sections[1].title)
    #expect(page.sections[0].id != page.sections[1].id)
    #expect(page.sections[0].items.count == 3)
    #expect(
      page.sections[0].items.contains { item in
        if case .album = item { return true }
        return false
      })
    #expect(
      page.sections[0].items.contains { item in
        if case .playlist = item { return true }
        return false
      })
    #expect(page.next == PaginationToken(rawValue: "home-next-token"))
  }

  @Test
  func playlistTracksUseInlineContinuationInsteadOfSectionContinuation() throws {
    let data = try fixtureData([
      "contents": [
        "twoColumnBrowseResultsRenderer": [
          "secondaryContents": [
            "sectionListRenderer": [
              "contents": [
                [
                  "musicPlaylistShelfRenderer": [
                    "contents": [song(id: "track-1", title: "Track")],
                    "continuations": [
                      ["nextContinuationData": ["continuation": "inline-token"]]
                    ],
                  ]
                ]
              ],
              "continuations": [
                ["nextContinuationData": ["continuation": "section-token"]]
              ],
            ]
          ]
        ]
      ]
    ])

    let page = try CatalogResponseParser.playlistTrackPage(from: data)
    #expect(page.items.map { $0.id } == ["track-1"])
    #expect(page.next == PaginationToken(rawValue: "inline-token"))
  }

  @Test
  func continuationItemsAndEmptyTokensAreScopedToTheirContainer() throws {
    let data = try fixtureData([
      "continuationContents": [
        "musicPlaylistShelfContinuation": [
          "contents": [song(id: "track-2", title: "Next")],
          "continuations": [
            [
              "continuationItemRenderer": [
                "continuationEndpoint": [
                  "continuationCommand": ["token": "playlist-next"]
                ]
              ]
            ]
          ],
        ],
        "unrelatedNestedObject": [
          "continuations": [
            ["nextContinuationData": ["continuation": "wrong-token"]]
          ]
        ],
      ]
    ])

    let page = try CatalogResponseParser.playlistTrackPage(
      from: data,
      continuation: true
    )
    #expect(page.items.map { $0.id } == ["track-2"])
    #expect(page.next == PaginationToken(rawValue: "playlist-next"))

    let emptyToken = try fixtureData([
      "continuationContents": [
        "musicShelfContinuation": [
          "contents": [song(id: "track-3", title: "Last")],
          "continuations": [
            ["nextContinuationData": ["continuation": ""]]
          ],
        ]
      ]
    ])
    #expect(
      try CatalogResponseParser.playlistTrackPage(from: emptyToken, continuation: true).next == nil
    )
  }

  @Test
  func searchContinuationUsesShelfOnly() throws {
    let data = try fixtureData([
      "continuationContents": [
        "musicShelfContinuation": [
          "contents": [song(id: "search-song", title: "Result")],
          "continuations": [
            ["nextRadioContinuationData": ["continuation": "search-next"]]
          ],
        ],
        "unrelated": [
          "musicShelfContinuation": [
            "contents": [song(id: "wrong", title: "Wrong")]
          ]
        ],
      ]
    ])

    let page = try CatalogResponseParser.searchPage(from: data, continuation: true)
    #expect(page.items.count == 1)
    #expect(page.items.first?.id == "song-search-song")
    #expect(page.next == PaginationToken(rawValue: "search-next"))
  }

  @Test
  func initialSearchUsesTheLastShelfThatContributedAcceptedResults() throws {
    let data = try fixtureData([
      "contents": [
        "tabbedSearchResultsRenderer": [
          "tabs": [
            [
              "tabRenderer": [
                "content": [
                  "sectionListRenderer": [
                    "contents": [
                      [
                        "musicShelfRenderer": [
                          "contents": [song(id: "first-result", title: "First")],
                          "continuations": [
                            ["nextContinuationData": ["continuation": "first-token"]]
                          ],
                        ]
                      ],
                      [
                        "musicShelfRenderer": [
                          "contents": [],
                          "continuations": [
                            ["nextContinuationData": ["continuation": "trailing-token"]]
                          ],
                        ]
                      ],
                    ]
                  ]
                ]
              ]
            ],
            [
              "tabRenderer": [
                "content": [
                  "sectionListRenderer": ["contents": []]
                ]
              ]
            ],
          ]
        ]
      ]
    ])

    let page = try CatalogResponseParser.searchPage(from: data)
    #expect(page.items.count == 1)
    #expect(page.next == PaginationToken(rawValue: "first-token"))
  }

  @Test
  func playlistContinuationNormalizesNestedDirectAndAppendedShapes() throws {
    let nestedSectionList = try fixtureData([
      "continuationContents": [
        "sectionListContinuation": [
          "contents": [
            [
              "musicPlaylistShelfRenderer": [
                "contents": [song(id: "nested-track", title: "Nested")]
              ]
            ],
            [
              "musicShelfContinuation": [
                "contents": [song(id: "nested-continuation-track", title: "Nested continuation")]
              ]
            ],
          ],
          "continuations": [
            ["nextContinuationData": ["continuation": "enclosing-token"]]
          ],
        ]
      ]
    ])
    let nestedPage = try CatalogResponseParser.playlistTrackPage(
      from: nestedSectionList,
      continuation: true
    )
    #expect(nestedPage.items.map(\.id) == ["nested-track", "nested-continuation-track"])
    #expect(nestedPage.next == PaginationToken(rawValue: "enclosing-token"))

    let directShelf = try fixtureData([
      "continuationContents": [
        "musicPlaylistShelfContinuation": [
          "contents": [song(id: "direct-track", title: "Direct")],
          "continuations": [
            [
              "continuationItemRenderer": [
                "continuationEndpoint": [
                  "continuationCommand": ["token": "direct-token"]
                ]
              ]
            ]
          ],
        ]
      ]
    ])
    let directPage = try CatalogResponseParser.playlistTrackPage(
      from: directShelf,
      continuation: true
    )
    #expect(directPage.items.map(\.id) == ["direct-track"])
    #expect(directPage.next == PaginationToken(rawValue: "direct-token"))

    let combined = try fixtureData([
      "continuationContents": [
        "sectionListContinuation": [
          "contents": [
            [
              "musicShelfRenderer": [
                "contents": [song(id: "section-track", title: "Section")]
              ]
            ]
          ]
        ]
      ],
      "onResponseReceivedActions": [
        [
          "appendContinuationItemsAction": [
            "continuationItems": [
              song(id: "appended-track", title: "Appended"),
              [
                "continuationItemRenderer": [
                  "continuationEndpoint": [
                    "continuationCommand": ["token": "appended-token"]
                  ]
                ]
              ],
            ]
          ]
        ]
      ],
    ])
    let combinedPage = try CatalogResponseParser.playlistTrackPage(
      from: combined,
      continuation: true
    )
    #expect(combinedPage.items.map(\.id) == ["section-track", "appended-track"])
    #expect(combinedPage.next == PaginationToken(rawValue: "appended-token"))
  }

  @Test
  func initialShelfContinuationItemRendererAndMalformedEmptyEnvelopesAreDistinct() throws {
    let initial = try fixtureData([
      "contents": [
        "twoColumnBrowseResultsRenderer": [
          "secondaryContents": [
            "sectionListRenderer": [
              "contents": [
                [
                  "musicPlaylistShelfRenderer": [
                    "contents": [
                      song(id: "initial-track", title: "Initial"),
                      continuationItem(token: "initial-next"),
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ])
    let initialPage = try CatalogResponseParser.playlistTrackPage(from: initial)
    #expect(initialPage.items.map(\.id) == ["initial-track"])
    #expect(initialPage.next == PaginationToken(rawValue: "initial-next"))

    let empty = try fixtureData([
      "continuationContents": [
        "sectionListContinuation": [
          "contents": []
        ]
      ]
    ])
    let emptyPage = try CatalogResponseParser.playlistTrackPage(
      from: empty,
      continuation: true
    )
    #expect(emptyPage.items.isEmpty)
    #expect(emptyPage.next == nil)

    let malformed = try fixtureData([
      "continuationContents": [
        "gridContinuation": [
          "items": [song(id: "wrong-track", title: "Wrong")]
        ]
      ]
    ])
    #expect(
      throws: InnerTubeError.self,
      performing: {
        try CatalogResponseParser.playlistTrackPage(from: malformed, continuation: true)
      }
    )
  }

  @Test
  func homeContinuationAppendsItemsAndNamespacesChunksByInputToken() throws {
    let data = try fixtureData([
      "continuationContents": [
        "sectionListContinuation": [
          "contents": [
            carousel(title: "Section", items: [song(id: "home-section", title: "Section")]),
            [
              "musicCarouselShelfContinuation": [
                "header": [
                  "musicCarouselShelfBasicHeaderRenderer": [
                    "title": ["simpleText": "Nested section"]
                  ]
                ],
                "contents": [song(id: "home-nested", title: "Nested")],
              ]
            ],
          ]
        ]
      ],
      "onResponseReceivedActions": [
        [
          "appendContinuationItemsAction": [
            "continuationItems": [
              carousel(title: "Appended", items: [song(id: "home-appended", title: "Appended")])
            ]
          ]
        ]
      ],
    ])

    let first = try CatalogResponseParser.homeContinuationPage(
      from: data,
      sectionIDPrefix: "home-anonymous",
      continuationToken: "opaque-token-one"
    )
    let second = try CatalogResponseParser.homeContinuationPage(
      from: data,
      sectionIDPrefix: "home-anonymous",
      continuationToken: "opaque-token-two"
    )
    #expect(first.sections.count == 3)
    #expect(second.sections.count == 3)
    #expect(first.sections.map(\.id).allSatisfy { !$0.contains("opaque-token") })
    #expect(Set(first.sections.map(\.id)).isDisjoint(with: second.sections.map(\.id)))
  }

  @Test
  func homeContinuationRejectsWrongEnvelopeButAcceptsEmptySectionList() throws {
    let malformed = try fixtureData([
      "continuationContents": [
        "musicPlaylistShelfContinuation": [
          "contents": []
        ]
      ]
    ])
    #expect(
      throws: InnerTubeError.self,
      performing: {
        try CatalogResponseParser.homeContinuationPage(
          from: malformed,
          sectionIDPrefix: "home",
          continuationToken: "opaque"
        )
      }
    )

    let empty = try fixtureData([
      "continuationContents": [
        "sectionListContinuation": [
          "contents": []
        ]
      ]
    ])
    let page = try CatalogResponseParser.homeContinuationPage(
      from: empty,
      sectionIDPrefix: "home",
      continuationToken: "opaque"
    )
    #expect(page.sections.isEmpty)
    #expect(page.next == nil)
  }

  @Test
  func albumBackingPlaylistUsesPlaylistRequestAndRawBrowseFallback() async throws {
    let response = try fixtureData([
      "contents": [
        "twoColumnBrowseResultsRenderer": [
          "secondaryContents": [
            "sectionListRenderer": [
              "contents": [
                [
                  "musicPlaylistShelfRenderer": [
                    "contents": [song(id: "album-track", title: "Album track")]
                  ]
                ]
              ]
            ]
          ]
        ]
      ],
      "continuationContents": [
        "musicPlaylistShelfContinuation": [
          "contents": []
        ]
      ],
    ])
    let (service, recorder) = makeCatalogService(response: response)
    let backingAlbum = Album(
      browseID: "MPREraw",
      playlistID: "PLbacking",
      title: "Fixture album"
    )
    _ = try await service.albumTrackPage(
      in: backingAlbum,
      continuation: nil,
      policy: .reload
    )
    let backingRequest = try #require(recorder.requests.first)
    let backingBody = try jsonObject(from: backingRequest)
    #expect(backingBody["browseId"] as? String == "VLPLbacking")

    recorder.clear()
    _ = try await service.albumTrackPage(
      in: backingAlbum,
      continuation: PaginationToken(rawValue: "album-next"),
      policy: .reload
    )
    let continuationRequest = try #require(recorder.requests.first)
    let continuationBody = try jsonObject(from: continuationRequest)
    #expect(continuationBody["browseId"] as? String == "")
    #expect(continuationBody["continuation"] as? String == "album-next")

    recorder.clear()
    let rawAlbum = Album(browseID: "MPREraw", title: "Fixture album")
    _ = try await service.albumTrackPage(
      in: rawAlbum,
      continuation: nil,
      policy: .reload
    )
    let rawRequest = try #require(recorder.requests.first)
    let rawBody = try jsonObject(from: rawRequest)
    #expect(rawBody["browseId"] as? String == "MPREraw")
  }

  @Test func scopedSearchRequestUsesFilterOnlyOnFirstPageAndPreservesCursor() async throws {
    let initial = try fixtureData([
      "contents": [
        "tabbedSearchResultsRenderer": [
          "tabs": [
            ["tabRenderer": ["content": ["sectionListRenderer": ["contents": []]]]]
          ]
        ]
      ]
    ])
    let (service, recorder) = makeCatalogService(response: initial)
    for scope in [SearchScope.artists, .albums, .songs, .playlists, .all] {
      recorder.clear()
      _ = try await service.searchPage(
        query: "  fixture  ", scope: scope, continuation: nil, policy: .reload)
      let request = try #require(recorder.requests.first)
      let body = try jsonObject(from: request)
      #expect(body["query"] as? String == "fixture")
      #expect(body["params"] as? String == SearchParameters.value(for: scope))
    }
    let continuationResponse = try fixtureData([
      "continuationContents": [
        "musicShelfContinuation": ["contents": []]
      ]
    ])
    let (continuationService, continuationRecorder) = makeCatalogService(
      response: continuationResponse)
    _ = try await continuationService.searchPage(
      query: "fixture", scope: .artists,
      continuation: PaginationToken(rawValue: "opaque/next?="), policy: .cacheFirst)
    let request = try #require(continuationRecorder.requests.first)
    let body = try jsonObject(from: request)
    #expect(body["query"] == nil)
    #expect(body["params"] == nil)
    let url = try #require(request.url)
    let components = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false))
    #expect(
      components.queryItems?.first(where: { $0.name == "continuation" })?.value == "opaque/next?=")
    #expect(components.queryItems?.first(where: { $0.name == "ctoken" })?.value == "opaque/next?=")
  }

  // Synthetic header shapes from the pinned AuraMusic adapters, 2026-10-14.
  @Test(arguments: [
    "musicImmersiveHeaderRenderer", "musicVisualHeaderRenderer", "musicHeaderRenderer",
  ])
  func artistPageRetainsItsOwnHeaderArtwork(rendererName: String) throws {
    let expected = "https://example.invalid/artist-portrait.png"
    var renderer: [String: Any] = [
      "title": ["simpleText": "Fixture Artist"],
      "thumbnail": headerArtwork("https://example.invalid/background.png"),
    ]
    if rendererName == "musicVisualHeaderRenderer" {
      renderer["foregroundThumbnail"] = headerArtwork(expected)
    } else if rendererName == "musicHeaderRenderer" {
      renderer["thumbnail"] = [
        "musicThumbnailRenderer": ["thumbnails": [["url": expected, "width": 640, "height": 640]]]
      ]
    } else {
      renderer["thumbnail"] = headerArtwork(expected)
    }
    var object = detailBrowseFixture()
    object["header"] = [rendererName: renderer]
    let page = try CatalogResponseParser.artistPage(
      from: fixtureData(object), artist: Artist(browseID: "UCfixture", title: "Fixture Artist"))
    #expect(page.header?.thumbnailURL?.absoluteString == expected)
    #expect(page.sections.flatMap(\.items).count == 1)
  }

  @Test
  func albumPageRetainsPrimaryColumnCoverAndLinkedCredits() throws {
    let expected = "https://example.invalid/album-cover.png"
    let endpoint: [String: Any] = [
      "browseId": "UCfixture", "params": "opaque-header-params",
      "browseEndpointContextSupportedConfigs": [
        "browseEndpointContextMusicConfig": ["pageType": "MUSIC_PAGE_TYPE_ARTIST"]
      ],
    ]
    let header: [String: Any] = [
      "title": ["simpleText": "Fixture Album"],
      "subtitle": ["simpleText": "Album • 2026"],
      "straplineTextOne": [
        "runs": [
          ["text": "Fixture Artist", "navigationEndpoint": ["browseEndpoint": endpoint]]
        ]
      ],
      "thumbnail": headerArtwork(expected),
    ]
    let object: [String: Any] = [
      "contents": [
        "twoColumnBrowseResultsRenderer": [
          "tabs": [
            [
              "tabRenderer": [
                "content": [
                  "sectionListRenderer": [
                    "contents": [["musicResponsiveHeaderRenderer": header]]
                  ]
                ]
              ]
            ]
          ],
          "secondaryContents": [
            "sectionListRenderer": [
              "contents": [
                [
                  "musicPlaylistShelfRenderer": [
                    "contents": [song(id: "track", title: "Track")]
                  ]
                ]
              ]
            ]
          ],
        ]
      ]
    ]
    let page = try CatalogResponseParser.albumTrackPage(from: fixtureData(object))
    #expect(page.header?.thumbnailURL?.absoluteString == expected)
    #expect(page.header?.artistReferences?.map(\.id) == ["UCfixture"])
    #expect(page.header?.artistReferences?.first?.params == "opaque-header-params")
    #expect(page.items.map(\.id) == ["track"])
  }

  @Test(arguments: [false, true])
  func albumPageAcceptsLegacyCoverAndPageBackground(backgroundOnly: Bool) throws {
    let expected = "https://example.invalid/album-cover.png"
    var object = detailBrowseFixture()
    var renderer: [String: Any] = ["title": ["simpleText": "Fixture Album"]]
    if backgroundOnly {
      object["background"] = headerArtwork(expected)
    } else {
      renderer["thumbnail"] = [
        "croppedSquareThumbnailRenderer": [
          "thumbnail": ["thumbnails": [["url": expected, "width": 640, "height": 640]]]
        ]
      ]
    }
    object["header"] = ["musicDetailHeaderRenderer": renderer]
    let page = try CatalogResponseParser.albumTrackPage(from: fixtureData(object))
    #expect(page.header?.thumbnailURL?.absoluteString == expected)
  }

  @Test
  func missingHeaderNeverUsesAFeaturedSongOrContinuationAsArtistArtwork() throws {
    var object = detailBrowseFixture()
    object["menu"] = [
      "musicImmersiveHeaderRenderer": [
        "thumbnail": headerArtwork("https://example.invalid/unrelated.png")
      ]
    ]
    let artist = Artist(browseID: "UCfixture", title: "Fixture Artist")
    let initial = try CatalogResponseParser.artistPage(from: fixtureData(object), artist: artist)
    #expect(initial.header == nil)
    let continuation: [String: Any] = [
      "header": [
        "musicImmersiveHeaderRenderer": [
          "thumbnail": headerArtwork("https://example.invalid/unrelated.png")
        ]
      ],
      "continuationContents": [
        "musicShelfContinuation": [
          "contents": [song(id: "more", title: "More")]
        ]
      ],
    ]
    let page = try CatalogResponseParser.artistPage(
      from: fixtureData(continuation), artist: artist, continuation: true)
    #expect(page.header == nil)
    #expect(page.sections.flatMap(\.items).count == 1)
  }

  private func detailBrowseFixture() -> [String: Any] {
    [
      "contents": [
        "singleColumnBrowseResultsRenderer": [
          "tabs": [
            [
              "tabRenderer": [
                "content": [
                  "sectionListRenderer": [
                    "contents": [
                      [
                        "musicShelfRenderer": [
                          "title": ["simpleText": "Songs"],
                          "contents": [song(id: "detail", title: "Detail")],
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ]
  }

  private func headerArtwork(_ url: String) -> [String: Any] {
    [
      "musicThumbnailRenderer": [
        "thumbnail": ["thumbnails": [["url": url, "width": 640, "height": 640]]]
      ]
    ]
  }

  private func fixtureData(_ object: [String: Any]) throws -> Data {
    try JSONSerialization.data(withJSONObject: object)
  }

  private func carousel(title: String, items: [[String: Any]]) -> [String: Any] {
    [
      "musicCarouselShelfRenderer": [
        "header": [
          "musicCarouselShelfBasicHeaderRenderer": [
            "title": ["simpleText": title]
          ]
        ],
        "contents": items,
      ]
    ]
  }

  private func song(id: String, title: String) -> [String: Any] {
    [
      "musicResponsiveListItemRenderer": [
        "playlistItemData": ["videoId": id],
        "flexColumns": [
          [
            "musicResponsiveListItemFlexColumnRenderer": [
              "text": ["simpleText": title]
            ]
          ],
          [
            "musicResponsiveListItemFlexColumnRenderer": [
              "text": ["simpleText": "Fixture artist"]
            ]
          ],
        ],
      ]
    ]
  }

  private func playlist(id: String, title: String) -> [String: Any] {
    [
      "musicTwoRowItemRenderer": [
        "title": ["simpleText": title],
        "navigationEndpoint": [
          "browseEndpoint": ["browseId": id]
        ],
      ]
    ]
  }

  private func album(id: String, title: String) -> [String: Any] {
    [
      "musicTwoRowItemRenderer": [
        "title": ["simpleText": title],
        "navigationEndpoint": [
          "browseEndpoint": [
            "browseId": id,
            "browseEndpointContextSupportedConfigs": [
              "browseEndpointContextMusicConfig": [
                "pageType": "MUSIC_PAGE_TYPE_ALBUM"
              ]
            ],
          ]
        ],
      ]
    ]
  }

  private func artist(id: String, title: String) -> [String: Any] {
    [
      "musicTwoRowItemRenderer": [
        "title": ["simpleText": title],
        "navigationEndpoint": [
          "browseEndpoint": [
            "browseId": id,
            "browseEndpointContextSupportedConfigs": [
              "browseEndpointContextMusicConfig": [
                "pageType": "MUSIC_PAGE_TYPE_ARTIST"
              ]
            ],
          ]
        ],
      ]
    ]
  }
}

private func continuationItem(token: String) -> [String: Any] {
  [
    "continuationItemRenderer": [
      "continuationEndpoint": [
        "continuationCommand": ["token": token]
      ]
    ]
  ]
}

private func jsonObject(from request: URLRequest) throws -> [String: Any] {
  let body: Data
  if let httpBody = request.httpBody {
    body = httpBody
  } else {
    let stream = try #require(request.httpBodyStream)
    stream.open()
    defer { stream.close() }
    var bytes = Data()
    var buffer = [UInt8](repeating: 0, count: 4 * 1024)
    while stream.hasBytesAvailable {
      let count = stream.read(&buffer, maxLength: buffer.count)
      guard count >= 0 else {
        throw InnerTubeError.invalidResponse("fixture request body could not be read")
      }
      if count == 0 {
        break
      }
      bytes.append(buffer, count: count)
    }
    body = bytes
  }
  let object = try JSONSerialization.jsonObject(with: body)
  return try #require(object as? [String: Any])
}

private final class CatalogRequestRecorder: @unchecked Sendable {
  private let lock = NSLock()
  private var storedRequests: [URLRequest] = []

  func append(_ request: URLRequest) {
    lock.lock()
    storedRequests.append(request)
    lock.unlock()
  }

  func clear() {
    lock.lock()
    storedRequests.removeAll()
    lock.unlock()
  }

  var requests: [URLRequest] {
    lock.lock()
    defer { lock.unlock() }
    return storedRequests
  }
}

private final class CatalogFixtureURLProtocol: URLProtocol {
  private final class State: @unchecked Sendable {
    let lock = NSLock()
    var body: Data?
    var recorder: CatalogRequestRecorder?
  }

  private static let state = State()

  static func install(body: Data) -> CatalogRequestRecorder {
    let recorder = CatalogRequestRecorder()
    state.lock.lock()
    state.body = body
    state.recorder = recorder
    state.lock.unlock()
    return recorder
  }

  override class func canInit(with request: URLRequest) -> Bool {
    request.url != nil
  }

  override class func canonicalRequest(for request: URLRequest) -> URLRequest {
    request
  }

  override func startLoading() {
    Self.state.lock.lock()
    let body = Self.state.body
    let recorder = Self.state.recorder
    Self.state.lock.unlock()
    guard let body, let recorder, let url = request.url else {
      client?.urlProtocol(self, didFailWithError: URLError(.resourceUnavailable))
      return
    }
    recorder.append(request)
    guard
      let response = HTTPURLResponse(
        url: url,
        statusCode: 200,
        httpVersion: "HTTP/1.1",
        headerFields: ["Content-Type": "application/json"]
      )
    else {
      client?.urlProtocol(self, didFailWithError: URLError(.badURL))
      return
    }
    client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
    client?.urlProtocol(self, didLoad: body)
    client?.urlProtocolDidFinishLoading(self)
  }

  override func stopLoading() {}
}

private func makeCatalogService(
  response: Data
) -> (InnerTubeMusicService, CatalogRequestRecorder) {
  let recorder = CatalogFixtureURLProtocol.install(body: response)
  let configuration = URLSessionConfiguration.ephemeral
  configuration.protocolClasses = [CatalogFixtureURLProtocol.self]
  let session = URLSession(configuration: configuration)
  let client = InnerTubeClient(
    urlSession: session,
    configuration: MusicWebConfiguration(
      apiKey: "",
      clientName: "WEB_REMIX",
      clientVersion: "fixture-version",
      clientID: "67",
      visitorData: "fixture-visitor"
    )
  )
  return (InnerTubeMusicService(client: client), recorder)
}