react-native-audio-browser 1.0.0-next.2 → 1.0.0-next.3

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 (147) hide show
  1. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +19 -2
  2. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +29 -8
  3. package/android/src/main/java/com/audiobrowser/http/RequestConfigBuilder.kt +8 -10
  4. package/android/src/main/java/com/audiobrowser/model/PlayerSetupOptions.kt +2 -2
  5. package/android/src/main/java/com/audiobrowser/player/AutomaticBufferManager.kt +17 -16
  6. package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +11 -0
  7. package/android/src/main/java/com/audiobrowser/player/Player.kt +8 -4
  8. package/android/src/test/java/com/audiobrowser/ContentRefreshNavigationErrorTest.kt +236 -0
  9. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerUnparsableResponseTest.kt +82 -0
  10. package/android/src/test/java/com/audiobrowser/browser/BrowserUrlResolutionTest.kt +15 -0
  11. package/android/src/test/java/com/audiobrowser/http/RequestConfigBuilderTest.kt +26 -0
  12. package/android/src/test/java/com/audiobrowser/model/PlayerSetupOptionsTest.kt +19 -2
  13. package/android/src/test/java/com/audiobrowser/player/AutomaticBufferManagerTest.kt +17 -0
  14. package/android/src/test/java/com/audiobrowser/player/SessionQueueShuffleOrderTest.kt +38 -0
  15. package/ios/Browser/BrowserError.swift +8 -0
  16. package/ios/Browser/BrowserManager.swift +29 -28
  17. package/ios/Browser/BrowserPathHelper.swift +26 -24
  18. package/ios/Browser/FavoriteSet.swift +16 -8
  19. package/ios/Browser/Favorites.swift +66 -0
  20. package/ios/Browser/JsonModels.swift +27 -7
  21. package/ios/Browser/NavigationErrorState.swift +18 -1
  22. package/ios/Browser/PageResolver.swift +2 -2
  23. package/ios/Browser/RequestLayer.swift +11 -4
  24. package/ios/Browser/RequestPipeline.swift +8 -4
  25. package/ios/Browser/TabBarEntries.swift +7 -0
  26. package/ios/CarPlay/CarPlayImageLoader.swift +3 -7
  27. package/ios/CarPlay/CarPlaySession+Navigator.swift +3 -1
  28. package/ios/CarPlay/IntentHandlers.swift +1 -7
  29. package/ios/CarPlay/MediaIntentCriteria.swift +4 -4
  30. package/ios/Extension/CGSize+AspectFit.swift +11 -0
  31. package/ios/Extension/Dictionary+Headers.swift +8 -0
  32. package/ios/Extension/NavigationError+Conversion.swift +4 -3
  33. package/ios/Extension/ResolvedTrack+Copying.swift +15 -0
  34. package/ios/Http/HttpClient.swift +37 -11
  35. package/ios/HybridAudioBrowser+Browser.swift +9 -16
  36. package/ios/HybridAudioBrowser+Options.swift +1 -0
  37. package/ios/HybridAudioBrowser+Player.swift +24 -23
  38. package/ios/HybridAudioBrowser+PlayerCallbacks.swift +1 -2
  39. package/ios/Model/NitroTypeStubs.swift +39 -0
  40. package/ios/Model/TrackPlayerError.swift +21 -2
  41. package/ios/Player/AudioSessionController.swift +2 -2
  42. package/ios/Player/MediaLoader.swift +1 -1
  43. package/ios/Player/PlaybackStateMachine.swift +1 -2
  44. package/ios/Player/Player.swift +59 -20
  45. package/ios/Player/PlayerEngine.swift +5 -0
  46. package/ios/Player/QueueManager.swift +21 -4
  47. package/ios/Tests/BrowserErrorTests.swift +21 -0
  48. package/ios/Tests/BrowserPathHelperTests.swift +18 -0
  49. package/ios/Tests/CGSizeAspectFitTests.swift +36 -0
  50. package/ios/Tests/ClampedVolumeTests.swift +26 -0
  51. package/ios/Tests/FavoriteSetTests.swift +68 -3
  52. package/ios/Tests/FavoritesTests.swift +102 -0
  53. package/ios/Tests/HttpClientUserAgentTests.swift +45 -0
  54. package/ios/Tests/JsonModelsTests.swift +74 -6
  55. package/ios/Tests/MediaIntentCriteriaTests.swift +11 -1
  56. package/ios/Tests/MediaLoaderAssetOptionsTests.swift +7 -0
  57. package/ios/Tests/NavigationErrorStateTests.swift +73 -0
  58. package/ios/Tests/PlaybackStateMachineTests.swift +6 -4
  59. package/ios/Tests/PlayerPolicyTests.swift +38 -0
  60. package/ios/Tests/PlayerProgressTests.swift +109 -0
  61. package/ios/Tests/PlayerTests.swift +106 -0
  62. package/ios/Tests/QueueIndexTests.swift +43 -0
  63. package/ios/Tests/QueueManagerTests.swift +79 -15
  64. package/ios/Tests/RequestLayerTests.swift +22 -3
  65. package/ios/Tests/TabBarEntriesTests.swift +19 -0
  66. package/ios/Tests/TrackSelectorTests.swift +154 -0
  67. package/ios/Tests/UnparsableResponseTests.swift +91 -0
  68. package/ios/TrackSelector.swift +28 -8
  69. package/ios/Util/ArtworkImageFetcher.swift +9 -8
  70. package/ios/Util/SVGProcessor.swift +6 -17
  71. package/lib/commonjs/features/browser-config.js +6 -3
  72. package/lib/commonjs/features/browser-config.js.map +1 -1
  73. package/lib/commonjs/features/errors.js +12 -7
  74. package/lib/commonjs/features/errors.js.map +1 -1
  75. package/lib/commonjs/features/nowPlaying.js +9 -3
  76. package/lib/commonjs/features/nowPlaying.js.map +1 -1
  77. package/lib/commonjs/features/playback/trackPlaybackTime.js +2 -1
  78. package/lib/commonjs/features/playback/trackPlaybackTime.js.map +1 -1
  79. package/lib/commonjs/features/player/setup.js +2 -2
  80. package/lib/commonjs/features/queue/activeTrack.js +4 -2
  81. package/lib/commonjs/features/queue/activeTrack.js.map +1 -1
  82. package/lib/commonjs/features/sleepTimer.js +6 -5
  83. package/lib/commonjs/features/sleepTimer.js.map +1 -1
  84. package/lib/commonjs/utils/LazyNativeEmitter.js +2 -1
  85. package/lib/commonjs/utils/LazyNativeEmitter.js.map +1 -1
  86. package/lib/commonjs/utils/NativeUpdatedValue.js +2 -1
  87. package/lib/commonjs/utils/NativeUpdatedValue.js.map +1 -1
  88. package/lib/commonjs/utils/callListener.js +23 -0
  89. package/lib/commonjs/utils/callListener.js.map +1 -0
  90. package/lib/module/features/browser-config.js +6 -3
  91. package/lib/module/features/browser-config.js.map +1 -1
  92. package/lib/module/features/errors.js +12 -7
  93. package/lib/module/features/errors.js.map +1 -1
  94. package/lib/module/features/nowPlaying.js +9 -3
  95. package/lib/module/features/nowPlaying.js.map +1 -1
  96. package/lib/module/features/playback/trackPlaybackTime.js +2 -1
  97. package/lib/module/features/playback/trackPlaybackTime.js.map +1 -1
  98. package/lib/module/features/player/setup.js +2 -2
  99. package/lib/module/features/queue/activeTrack.js +4 -2
  100. package/lib/module/features/queue/activeTrack.js.map +1 -1
  101. package/lib/module/features/sleepTimer.js +6 -5
  102. package/lib/module/features/sleepTimer.js.map +1 -1
  103. package/lib/module/utils/LazyNativeEmitter.js +2 -1
  104. package/lib/module/utils/LazyNativeEmitter.js.map +1 -1
  105. package/lib/module/utils/NativeUpdatedValue.js +2 -1
  106. package/lib/module/utils/NativeUpdatedValue.js.map +1 -1
  107. package/lib/module/utils/callListener.js +19 -0
  108. package/lib/module/utils/callListener.js.map +1 -0
  109. package/lib/typescript/src/features/browser-config.d.ts.map +1 -1
  110. package/lib/typescript/src/features/errors.d.ts +8 -6
  111. package/lib/typescript/src/features/errors.d.ts.map +1 -1
  112. package/lib/typescript/src/features/nowPlaying.d.ts +2 -1
  113. package/lib/typescript/src/features/nowPlaying.d.ts.map +1 -1
  114. package/lib/typescript/src/features/playback/trackPlaybackTime.d.ts.map +1 -1
  115. package/lib/typescript/src/features/player/setup.d.ts +2 -2
  116. package/lib/typescript/src/features/queue/activeTrack.d.ts +2 -1
  117. package/lib/typescript/src/features/queue/activeTrack.d.ts.map +1 -1
  118. package/lib/typescript/src/features/sleepTimer.d.ts +2 -1
  119. package/lib/typescript/src/features/sleepTimer.d.ts.map +1 -1
  120. package/lib/typescript/src/types/browser.d.ts +3 -2
  121. package/lib/typescript/src/types/browser.d.ts.map +1 -1
  122. package/lib/typescript/src/utils/LazyNativeEmitter.d.ts.map +1 -1
  123. package/lib/typescript/src/utils/NativeUpdatedValue.d.ts.map +1 -1
  124. package/lib/typescript/src/utils/callListener.d.ts +7 -0
  125. package/lib/typescript/src/utils/callListener.d.ts.map +1 -0
  126. package/package.json +1 -1
  127. package/src/features/browser-config.test.ts +15 -0
  128. package/src/features/browser-config.ts +6 -3
  129. package/src/features/errors.test.ts +83 -0
  130. package/src/features/errors.ts +12 -7
  131. package/src/features/hook-wiring.test.ts +11 -10
  132. package/src/features/nowPlaying.ts +9 -3
  133. package/src/features/playback/trackPlaybackTime.test.ts +24 -1
  134. package/src/features/playback/trackPlaybackTime.ts +2 -1
  135. package/src/features/player/setup.ts +2 -2
  136. package/src/features/queue/activeTrack.test.ts +32 -0
  137. package/src/features/queue/activeTrack.ts +8 -2
  138. package/src/features/sleepTimer.test.ts +24 -0
  139. package/src/features/sleepTimer.ts +6 -5
  140. package/src/types/browser.ts +3 -2
  141. package/src/utils/LazyNativeEmitter.test.ts +32 -0
  142. package/src/utils/LazyNativeEmitter.ts +3 -1
  143. package/src/utils/NativeUpdatedValue.test.ts +32 -0
  144. package/src/utils/NativeUpdatedValue.ts +3 -1
  145. package/src/utils/callListener.ts +17 -0
  146. package/website/guide/configuration.md +3 -3
  147. package/website/guide/errors.md +3 -1
@@ -72,9 +72,9 @@ public struct MediaIntentCriteria: Sendable {
72
72
  }
73
73
  }
74
74
 
75
- /// Whole-word subset match in either direction, case- and diacritic-insensitive. Siri may
76
- /// deliver only part of the name, so a partial match counts; a substring match would swallow
77
- /// any query inside the app name and make one-word stations unreachable by voice.
75
+ /// True when every word of `query` is a word of the app name, case- and diacritic-insensitive.
76
+ /// Siri may deliver only part of the name, so a partial match counts; a substring match would
77
+ /// swallow any query inside the app name and make one-word stations unreachable by voice.
78
78
  private static func queryMatchesAppName(_ query: String, appName: String?) -> Bool {
79
79
  guard let appName else { return false }
80
80
  let tokens: (String) -> Set<String> = {
@@ -86,6 +86,6 @@ public struct MediaIntentCriteria: Sendable {
86
86
  }
87
87
  let q = tokens(query), a = tokens(appName)
88
88
  guard !q.isEmpty, !a.isEmpty else { return false }
89
- return q.isSubset(of: a) || a.isSubset(of: q)
89
+ return q.isSubset(of: a)
90
90
  }
91
91
  }
@@ -0,0 +1,11 @@
1
+ import CoreGraphics
2
+
3
+ extension CGSize {
4
+ /// The largest size with this size's aspect ratio that fits inside `bounds`; nil when this size
5
+ /// has no usable aspect ratio (a zero, negative or non-finite side).
6
+ func aspectFitted(in bounds: CGSize) -> CGSize? {
7
+ guard width > 0, height > 0, width.isFinite, height.isFinite else { return nil }
8
+ let factor = min(bounds.width / width, bounds.height / height)
9
+ return CGSize(width: width * factor, height: height * factor)
10
+ }
11
+ }
@@ -0,0 +1,8 @@
1
+ import Foundation
2
+
3
+ extension [String: String] {
4
+ /// Whether these headers set `name`, in any case: HTTP header names are case-insensitive.
5
+ func hasHeader(_ name: String) -> Bool {
6
+ keys.contains { $0.caseInsensitiveCompare(name) == .orderedSame }
7
+ }
8
+ }
@@ -2,7 +2,8 @@ import Foundation
2
2
 
3
3
  extension NavigationError {
4
4
  /// Maps any thrown error to a NavigationError. `BrowserError.invalidConfiguration`,
5
- /// and any error that is not a BrowserError, HttpException or URLError, becomes `.unknownError`.
5
+ /// and any error that is not a BrowserError, HttpStatusError or URLError, becomes
6
+ /// `.unknownError`.
6
7
  static func from(_ error: Error) -> NavigationError {
7
8
  if let browserError = error as? BrowserError {
8
9
  switch browserError {
@@ -13,7 +14,7 @@ extension NavigationError {
13
14
  case .callbackError:
14
15
  NavigationError(code: .callbackError, message: browserError.localizedDescription, statusCode: nil, statusCodeSuccess: nil)
15
16
  }
16
- } else if let httpError = error as? HttpClient.HttpException {
17
+ } else if let httpError = error as? any HttpStatusError {
17
18
  NavigationError(code: .httpError, message: httpError.localizedDescription, statusCode: Double(httpError.code), statusCodeSuccess: (200 ... 299).contains(httpError.code))
18
19
  } else if error is URLError {
19
20
  NavigationError(code: .networkError, message: error.localizedDescription, statusCode: nil, statusCodeSuccess: nil)
@@ -30,7 +31,7 @@ extension NavigationError {
30
31
  case .networkError:
31
32
  "Network Error"
32
33
  case .httpError:
33
- if let statusCode {
34
+ if let statusCode, statusCodeSuccess != true {
34
35
  HTTPURLResponse.localizedString(forStatusCode: Int(statusCode)).capitalized
35
36
  } else {
36
37
  "Server Error"
@@ -54,4 +54,19 @@ extension ResolvedTrack {
54
54
  icyCharset: icyCharset ?? self.icyCharset,
55
55
  )
56
56
  }
57
+
58
+ /// A copy with each section track `transform` returns a track for replaced; nil when it
59
+ /// replaces none.
60
+ func replacingEachTrack(_ transform: (Track) -> Track?) -> ResolvedTrack? {
61
+ guard let sections else { return nil }
62
+ var replaced = false
63
+ let updated = sections.map { section in
64
+ section.copying(children: section.children.map { track in
65
+ guard let replacement = transform(track) else { return track }
66
+ replaced = true
67
+ return replacement
68
+ })
69
+ }
70
+ return replaced ? copying(sections: updated) : nil
71
+ }
57
72
  }
@@ -1,6 +1,11 @@
1
1
  import Foundation
2
2
  import os.log
3
3
 
4
+ /// A response that failed with its HTTP status.
5
+ protocol HttpStatusError: LocalizedError {
6
+ var code: Int { get }
7
+ }
8
+
4
9
  /// Counterpart of the Kotlin `HttpClient`; change request building and error messages in both.
5
10
  final class HttpClient: @unchecked Sendable {
6
11
  static let defaultUserAgent = "react-native-audio-browser"
@@ -20,7 +25,7 @@ final class HttpClient: @unchecked Sendable {
20
25
  }
21
26
 
22
27
  /// A non-2xx response.
23
- struct HttpException: LocalizedError {
28
+ struct HttpException: HttpStatusError {
24
29
  let code: Int
25
30
  let responseBody: String
26
31
 
@@ -36,18 +41,26 @@ final class HttpClient: @unchecked Sendable {
36
41
  }
37
42
  }
38
43
 
44
+ /// A 2xx response whose body does not decode as the type asked for.
45
+ struct UndecodableResponse: HttpStatusError {
46
+ let code: Int
47
+ let reason: String
48
+
49
+ var errorDescription: String? {
50
+ reason
51
+ }
52
+ }
53
+
39
54
  enum HttpClientError: LocalizedError {
40
55
  case invalidUrl(String)
41
56
  case unsupportedMethod(HttpMethod)
42
57
  case notHttp
43
- case undecodable(String)
44
58
 
45
59
  var errorDescription: String? {
46
60
  switch self {
47
61
  case let .invalidUrl(url): "Invalid URL: \(url)"
48
62
  case let .unsupportedMethod(method): "Unsupported HTTP method: \(method.stringValue)"
49
63
  case .notHttp: "Invalid response type"
50
- case let .undecodable(reason): reason
51
64
  }
52
65
  }
53
66
  }
@@ -66,7 +79,7 @@ final class HttpClient: @unchecked Sendable {
66
79
  urlRequest.setValue(value, forHTTPHeaderField: name)
67
80
  }
68
81
  // A `User-Agent` header wins over `userAgent`, as in the media and artwork paths.
69
- if httpRequest.headers?["User-Agent"] == nil {
82
+ if urlRequest.value(forHTTPHeaderField: "User-Agent") == nil {
70
83
  urlRequest.setValue(httpRequest.userAgent, forHTTPHeaderField: "User-Agent")
71
84
  }
72
85
 
@@ -98,7 +111,8 @@ final class HttpClient: @unchecked Sendable {
98
111
  }
99
112
  }
100
113
 
101
- /// Sends `httpRequest` and decodes a 2xx body as `T`; any other status throws `HttpException`.
114
+ /// Sends `httpRequest` and decodes a 2xx body as `T`, throwing `UndecodableResponse` when it
115
+ /// does not decode; any other status throws `HttpException`.
102
116
  /// A GET sends no body; HEAD and OPTIONS throw `HttpClientError.unsupportedMethod`.
103
117
  func requestJson<T: Decodable>(_ httpRequest: HttpRequest, as type: T.Type) async throws -> T {
104
118
  let (code, data) = try await request(httpRequest)
@@ -107,12 +121,24 @@ final class HttpClient: @unchecked Sendable {
107
121
  }
108
122
  do {
109
123
  return try JSONDecoder().decode(type, from: data)
110
- } catch let DecodingError.keyNotFound(key, context) {
111
- throw HttpClientError.undecodable("Missing required key '\(key.stringValue)' at path: \(Self.path(context))")
112
- } catch let DecodingError.typeMismatch(type, context) {
113
- throw HttpClientError.undecodable("Type mismatch for \(type) at path: \(Self.path(context))")
114
- } catch let DecodingError.valueNotFound(type, context) {
115
- throw HttpClientError.undecodable("Value not found for \(type) at path: \(Self.path(context))")
124
+ } catch {
125
+ throw UndecodableResponse(code: code, reason: Self.reason(error))
126
+ }
127
+ }
128
+
129
+ private static func reason(_ error: Error) -> String {
130
+ guard let error = error as? DecodingError else { return error.localizedDescription }
131
+ return switch error {
132
+ case let .keyNotFound(key, context):
133
+ "Missing required key '\(key.stringValue)' at path: \(path(context))"
134
+ case let .typeMismatch(type, context):
135
+ "Type mismatch for \(type) at path: \(path(context))"
136
+ case let .valueNotFound(type, context):
137
+ "Value not found for \(type) at path: \(path(context))"
138
+ case let .dataCorrupted(context):
139
+ context.debugDescription
140
+ @unknown default:
141
+ error.localizedDescription
116
142
  }
117
143
  }
118
144
 
@@ -18,17 +18,11 @@ public extension HybridAudioBrowser {
18
18
  }
19
19
 
20
20
  @MainActor
21
- private func loadPath(_ path: String) async {
22
- do {
23
- try await browserManager.load(path)
24
- } catch {
25
- await reportNavigationError(error, path: path)
26
- }
27
- }
28
-
29
- @MainActor
30
- private func reportNavigationError(_ error: Error, path: String) async {
31
- await navigationError.report(NavigationError.from(error)) { [browserManager] in
21
+ private func loadPath(_ path: String, bypassCache: Bool = false) async {
22
+ await navigationError.follow(
23
+ { try await browserManager.load(path, bypassCache: bypassCache) },
24
+ describe: { NavigationError.from($0) },
25
+ ) { [browserManager] in
32
26
  await browserManager.formatted($0, path: path)
33
27
  }
34
28
  }
@@ -46,7 +40,7 @@ public extension HybridAudioBrowser {
46
40
  switch result {
47
41
  case let .play(intent):
48
42
  player.execute(intent)
49
- case .intercepted:
43
+ case .intercepted, .superseded:
50
44
  break
51
45
  case let .browse(path):
52
46
  navigate(path, clearError: true)
@@ -88,14 +82,13 @@ public extension HybridAudioBrowser {
88
82
  return browserManager.path == path
89
83
  }
90
84
  externalContentChangedEmitter.emit(path)
91
- if isCurrentPath { Task { @MainActor in await loadPath(path) } }
85
+ if isCurrentPath { Task { @MainActor in await loadPath(path, bypassCache: true) } }
92
86
  }
93
87
 
94
88
  func invalidateAllContent() throws {
95
89
  onMainActor {
96
- browserManager.invalidateAll { error, path in
97
- await self.reportNavigationError(error, path: path)
98
- }
90
+ browserManager.invalidateAll()
91
+ Task { @MainActor in await loadPath(browserManager.path, bypassCache: true) }
99
92
  }
100
93
  externalContentChangedEmitter.emit(Self.invalidateAllSentinel)
101
94
  }
@@ -35,6 +35,7 @@ public extension HybridAudioBrowser {
35
35
  engine = newEngine
36
36
  player = newPlayer
37
37
  audioSession.player = newPlayer
38
+ browserManager.favorites.queue = newPlayer
38
39
 
39
40
  // `options.keepSessionAliveOnError` is ignored: on iOS an error never clears the now-playing
40
41
  // info, and next/previous follow the queue, not the state.
@@ -71,7 +71,11 @@ public extension HybridAudioBrowser {
71
71
  }
72
72
 
73
73
  func setVolume(level: Double) throws {
74
- onMainActor { engine?.volume = Float(level) }
74
+ guard let volume = clampedVolume(level) else {
75
+ logger.error("setVolume ignored a NaN level")
76
+ return
77
+ }
78
+ onMainActor { engine?.volume = volume }
75
79
  }
76
80
 
77
81
  func getVolume() throws -> Double {
@@ -90,8 +94,8 @@ public extension HybridAudioBrowser {
90
94
  onMainActor {
91
95
  Progress(
92
96
  position: player?.currentTime ?? 0,
93
- duration: engine?.duration ?? 0,
94
- buffered: engine?.bufferedPosition ?? 0,
97
+ duration: player?.duration ?? 0,
98
+ buffered: player?.bufferedPosition ?? 0,
95
99
  )
96
100
  }
97
101
  }
@@ -167,7 +171,7 @@ public extension HybridAudioBrowser {
167
171
  try onMainActor {
168
172
  guard let player else { return }
169
173
  if let index = insertBeforeIndex {
170
- try player.add(tracks, at: Int(index))
174
+ try player.add(tracks, at: Int(queueIndex: index))
171
175
  } else {
172
176
  try player.add(tracks)
173
177
  }
@@ -176,7 +180,7 @@ public extension HybridAudioBrowser {
176
180
 
177
181
  func move(fromIndex: Double, toIndex: Double) throws {
178
182
  try onMainActor {
179
- try player?.move(fromIndex: Int(fromIndex), toIndex: Int(toIndex))
183
+ try player?.move(fromIndex: Int(queueIndex: fromIndex), toIndex: Int(queueIndex: toIndex))
180
184
  }
181
185
  }
182
186
 
@@ -184,8 +188,8 @@ public extension HybridAudioBrowser {
184
188
  try onMainActor {
185
189
  guard let player else { return }
186
190
  // Highest index first, so earlier removals don't shift the ones still to go.
187
- for index in indexes.sorted().reversed() {
188
- try player.remove(Int(index))
191
+ for index in try indexes.map({ try Int(queueIndex: $0) }).sorted().reversed() {
192
+ try player.remove(index)
189
193
  }
190
194
  }
191
195
  }
@@ -196,7 +200,7 @@ public extension HybridAudioBrowser {
196
200
 
197
201
  func skip(index: Double, initialPosition: Double?) throws {
198
202
  try onMainActor {
199
- try player?.skipTo(Int(index))
203
+ try player?.skipTo(Int(queueIndex: index))
200
204
  if let position = initialPosition.flatMap({ finite($0, "skip") }) {
201
205
  player?.seek(to: position)
202
206
  }
@@ -222,20 +226,18 @@ public extension HybridAudioBrowser {
222
226
  }
223
227
 
224
228
  func setActiveTrackFavorited(favorited: Bool) throws {
225
- try favoriteActiveTrack(favorited)
229
+ favoriteActiveTrack(favorited)
226
230
  }
227
231
 
228
- /// Sets the active track's favorite state: in the favorite set first, so the now-playing
229
- /// heart (hydrated from it) flips at once, then on the queued track. False when nothing is
230
- /// playing or the track has no identity.
232
+ /// Sets the active track's favorite state in the favorite set, which restamps every copy of
233
+ /// the track, on screen and queued. False when nothing is playing or the track has no
234
+ /// identity.
231
235
  @discardableResult
232
- internal func favoriteActiveTrack(_ favorited: Bool) throws -> Bool {
233
- try onMainActor {
236
+ internal func favoriteActiveTrack(_ favorited: Bool) -> Bool {
237
+ onMainActor {
234
238
  guard let player, let track = player.currentTrack, let identity = track.identity else { return false }
235
239
  browserManager.setFavorited(identity: identity, favorited: favorited)
236
- // Hydration never overrides a track's own flag, so the queued copy must carry it.
237
- let updated = track.copying(favorited: favorited)
238
- try player.replace(player.queue.currentIndex, updated)
240
+ let updated = player.currentTrack ?? track
239
241
  // The only emit: a favorite toggle mutates the active track in place, so
240
242
  // onPlaybackActiveTrackChanged stays transition-only.
241
243
  let event = FavoriteChangedEvent(track: updated, favorited: favorited)
@@ -250,7 +252,7 @@ public extension HybridAudioBrowser {
250
252
  }
251
253
 
252
254
  func toggleActiveTrackFavorited() throws {
253
- try favoriteActiveTrack(!isActiveTrackFavorited())
255
+ favoriteActiveTrack(!isActiveTrackFavorited())
254
256
  }
255
257
 
256
258
  func setQueue(tracks: [Track], startIndex: Double?, startPosition: Double?) throws {
@@ -258,7 +260,7 @@ public extension HybridAudioBrowser {
258
260
  guard let player else { return }
259
261
  try player.setQueue(
260
262
  tracks,
261
- initialIndex: startIndex.map { Int($0) } ?? 0,
263
+ initialIndex: startIndex.map { try Int(queueIndex: $0) } ?? 0,
262
264
  startPositionMs: startPosition.flatMap { finite($0, "setQueue") }.map { $0 * 1000 },
263
265
  )
264
266
  }
@@ -274,8 +276,7 @@ public extension HybridAudioBrowser {
274
276
 
275
277
  func getTrack(index: Double) throws -> Track? {
276
278
  onMainActor {
277
- guard let tracks = player?.tracks else { return nil }
278
- let i = Int(index)
279
+ guard let tracks = player?.tracks, let i = try? Int(queueIndex: index) else { return nil }
279
280
  guard i >= 0, i < tracks.count else { return nil }
280
281
  return tracks[i]
281
282
  }
@@ -289,8 +290,8 @@ public extension HybridAudioBrowser {
289
290
  }
290
291
 
291
292
  func getActiveTrack() throws -> Track? {
292
- // The now-playing track is loaded outside the browse cache: a missing `favorited` is filled
293
- // from the favorite set, but a track's own value wins, so writers must update the queued copy too.
293
+ // A queued track that carries no `favorited` (a queue set from JS) is filled from the
294
+ // favorite set; one that carries it is kept current by `setFavorites` and the heart toggle.
294
295
  onMainActor { player?.currentTrack.map(browserManager.hydrateFavorite) }
295
296
  }
296
297
 
@@ -13,8 +13,7 @@ extension HybridAudioBrowser: PlayerCallbacks, AVPlayerEngineCallbacks {
13
13
  }
14
14
 
15
15
  public func playerDidChangeActiveTrack(_ event: PlaybackActiveTrackChangedEvent) {
16
- // The queue track's `favorited` is not kept in sync; hydrate it so useActiveTrack matches
17
- // getActiveTrack().
16
+ // A queued track that carries no `favorited` is hydrated here, as getActiveTrack() does.
18
17
  let hydrated = PlaybackActiveTrackChangedEvent(
19
18
  lastIndex: event.lastIndex,
20
19
  lastTrack: event.lastTrack,
@@ -121,6 +121,45 @@
121
121
  case delete
122
122
  case head
123
123
  case options
124
+
125
+ var stringValue: String {
126
+ switch self {
127
+ case .get: "GET"
128
+ case .post: "POST"
129
+ case .put: "PUT"
130
+ case .patch: "PATCH"
131
+ case .delete: "DELETE"
132
+ case .head: "HEAD"
133
+ case .options: "OPTIONS"
134
+ }
135
+ }
136
+ }
137
+
138
+ enum NavigationErrorType {
139
+ case contentNotFound
140
+ case networkError
141
+ case httpError
142
+ case callbackError
143
+ case unknownError
144
+ case emptyContent
145
+ case timeout
146
+ }
147
+
148
+ struct NavigationError: Equatable {
149
+ var code: NavigationErrorType
150
+ var message: String
151
+ var statusCode: Double?
152
+ var statusCodeSuccess: Bool?
153
+ }
154
+
155
+ struct FormattedNavigationError: Equatable {
156
+ var title: String
157
+ var message: String?
158
+ }
159
+
160
+ enum NavigationErrorKind {
161
+ case browse
162
+ case search
124
163
  }
125
164
 
126
165
  enum SearchMode {
@@ -18,7 +18,8 @@ public enum TrackPlayerError: Error {
18
18
 
19
19
  public enum QueueError: Error {
20
20
  case noCurrentItem
21
- case invalidIndex(index: Int, message: String)
21
+ /// `index` is nil when the number JS passed names no `Int`.
22
+ case invalidIndex(index: Int?, message: String)
22
23
  case empty
23
24
  case invalidTrack(title: String)
24
25
  }
@@ -52,8 +53,10 @@ extension TrackPlayerError.QueueError: LocalizedError {
52
53
  switch self {
53
54
  case .noCurrentItem:
54
55
  "No current track"
55
- case let .invalidIndex(index, message):
56
+ case let .invalidIndex(index?, message):
56
57
  "Invalid track index \(index): \(message)"
58
+ case let .invalidIndex(nil, message):
59
+ "Invalid track index: \(message)"
57
60
  case .empty:
58
61
  "Queue is empty"
59
62
  case let .invalidTrack(title):
@@ -62,6 +65,22 @@ extension TrackPlayerError.QueueError: LocalizedError {
62
65
  }
63
66
  }
64
67
 
68
+ // MARK: - Index Conversion
69
+
70
+ extension Int {
71
+ /// The queue index a JS number names, its fraction dropped. Throws `QueueError.invalidIndex`
72
+ /// for a number no `Int` holds: NaN, infinite, or beyond `Int`'s range.
73
+ init(queueIndex number: Double) throws {
74
+ guard let index = Int(exactly: number.rounded(.towardZero)) else {
75
+ throw TrackPlayerError.QueueError.invalidIndex(
76
+ index: nil,
77
+ message: "index must be a finite number within the range of Int, got \(number)",
78
+ )
79
+ }
80
+ self = index
81
+ }
82
+ }
83
+
65
84
  // MARK: - Cross-platform Classification
66
85
 
67
86
  public extension TrackPlayerError.PlaybackError {
@@ -4,7 +4,7 @@ import NitroModules
4
4
  /// What `AudioSessionController` tells the player about the audio session.
5
5
  @MainActor
6
6
  protocol AudioSessionPlayer: AnyObject {
7
- var playWhenReady: Bool { get }
7
+ var canReleaseAudioSession: Bool { get }
8
8
  var willResumeAfterInterruption: Bool { get }
9
9
  func handleInterruptionBegan()
10
10
  func handleInterruptionEnded(shouldResume: Bool)
@@ -108,7 +108,7 @@ final class AudioSessionController {
108
108
  func scheduleRelease() {
109
109
  releaseWork?.cancel()
110
110
  let release = DispatchWorkItem { [weak self] in
111
- guard let self, player?.playWhenReady == false else { return }
111
+ guard let self, player?.canReleaseAudioSession == true else { return }
112
112
  releaseWork = nil
113
113
  activationQueue.async {
114
114
  try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
@@ -174,7 +174,7 @@ final class MediaLoader {
174
174
  userAgent: String?,
175
175
  ) -> [String: Any]? {
176
176
  var merged = headers ?? [:]
177
- if let userAgent, !userAgent.isEmpty, merged["User-Agent"] == nil {
177
+ if let userAgent, !userAgent.isEmpty, !merged.hasHeader("User-Agent") {
178
178
  merged["User-Agent"] = userAgent
179
179
  }
180
180
  return merged.isEmpty ? nil : ["AVURLAssetHTTPHeaderFieldsKey": merged]
@@ -20,11 +20,10 @@ func nextPlaybackState(from current: PlaybackState, on event: PlaybackEvent) ->
20
20
  return .ready
21
21
  case let .avPlayerPaused(hasAsset):
22
22
  guard current != .stopped else { return nil }
23
- if !hasAsset { return PlaybackState.none }
24
23
  // .error and .ended hold against stray pause observations; .ended sees them because the
25
24
  // natural-end intent clear opens the call site's `!playWhenReady` gate.
26
25
  guard current != .error, current != .ended else { return nil }
27
- return .paused
26
+ return hasAsset ? .paused : PlaybackState.none
28
27
  case .bufferingSufficient:
29
28
  // .ended still has the play intent: a move to .ready would restart the finished track.
30
29
  guard current != .playing, !current.isTerminal else { return nil }