@francofantomius/jellyfin 0.2.0 → 0.4.1

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.
package/dist/index.js CHANGED
@@ -123,7 +123,15 @@ var HttpTransport = class {
123
123
  throw new JellyfinAuthError(`Unauthorized (HTTP ${response.status}) on ${endpoint}`, response.status, endpoint);
124
124
  }
125
125
  if (!response.ok) {
126
- throw new JellyfinApiError(`Jellyfin API request failed (${endpoint}): ${response.statusText}`, response.status, endpoint);
126
+ let details = "";
127
+ try {
128
+ const text = await response.text();
129
+ if (text) {
130
+ details = `: ${text.slice(0, 500)}`;
131
+ }
132
+ } catch {
133
+ }
134
+ throw new JellyfinApiError(`Jellyfin API request failed (${endpoint}): ${response.statusText || response.status}${details}`, response.status, endpoint);
127
135
  }
128
136
  return response;
129
137
  }
@@ -217,11 +225,22 @@ var AuthModule = class {
217
225
  const payload = {
218
226
  PlayableMediaTypes: ["Audio", "Video"],
219
227
  SupportedCommands: [
220
- "Play",
228
+ "MoveUp",
229
+ "MoveDown",
230
+ "MoveLeft",
231
+ "MoveRight",
232
+ "Select",
233
+ "Back",
234
+ "VolumeUp",
235
+ "VolumeDown",
236
+ "Mute",
237
+ "Unmute",
238
+ "ToggleMute",
239
+ "SetVolume",
221
240
  "PlayState",
222
- "PlayNext",
223
241
  "SetRepeatMode",
224
- "SetShuffleQueue"
242
+ "SetShuffleQueue",
243
+ "DisplayMessage"
225
244
  ],
226
245
  SupportsMediaControl: true,
227
246
  SupportsSync: false,
@@ -1167,28 +1186,41 @@ var MediaModule = class {
1167
1186
  const qualityResolved = resolveAudioQuality(options.quality);
1168
1187
  const maxStreamingBitrate = options.maxStreamingBitrate ?? qualityResolved.maxStreamingBitrate;
1169
1188
  const {
1189
+ mediaSourceId,
1190
+ static: isStatic = false,
1170
1191
  startTimeTicks = 0,
1171
1192
  container = "opus,mp3|mp3,aac,m4a,m4b,flac,wav,ogg",
1172
1193
  transcodingContainer = "mp3",
1173
1194
  audioCodec = "mp3",
1174
1195
  useQueryToken = true
1175
1196
  } = options;
1176
- const url = new URL(`${serverUrl}/Audio/${itemId}/universal`);
1177
- if (token && useQueryToken) url.searchParams.append("api_key", token);
1197
+ const endpoint = isStatic ? `/Audio/${itemId}/stream` : `/Audio/${itemId}/universal`;
1198
+ const url = new URL(`${serverUrl}${endpoint}`);
1199
+ if (token && useQueryToken) {
1200
+ url.searchParams.append("ApiKey", token);
1201
+ url.searchParams.append("api_key", token);
1202
+ url.searchParams.append("X-Emby-Token", token);
1203
+ }
1178
1204
  if (userId) url.searchParams.append("UserId", userId);
1179
- if (clientInfo.deviceId) url.searchParams.append("DeviceId", clientInfo.deviceId);
1180
- url.searchParams.append("Container", container);
1181
- url.searchParams.append("TranscodingContainer", transcodingContainer);
1182
- url.searchParams.append("TranscodingProtocol", "http");
1183
- url.searchParams.append("AudioCodec", audioCodec);
1205
+ const targetDeviceId = options.deviceId !== void 0 ? options.deviceId : clientInfo.deviceId;
1206
+ if (targetDeviceId) url.searchParams.append("DeviceId", targetDeviceId);
1207
+ if (mediaSourceId) url.searchParams.append("MediaSourceId", mediaSourceId);
1208
+ if (isStatic) {
1209
+ url.searchParams.append("static", "true");
1210
+ } else {
1211
+ url.searchParams.append("Container", container);
1212
+ url.searchParams.append("TranscodingContainer", transcodingContainer);
1213
+ url.searchParams.append("TranscodingProtocol", "http");
1214
+ url.searchParams.append("AudioCodec", audioCodec);
1215
+ url.searchParams.append("EnableRedirection", "true");
1216
+ url.searchParams.append("EnableRemoteMedia", "false");
1217
+ }
1184
1218
  if (maxStreamingBitrate && maxStreamingBitrate !== "Direct") {
1185
1219
  url.searchParams.append("MaxStreamingBitrate", String(maxStreamingBitrate));
1186
1220
  }
1187
1221
  if (startTimeTicks > 0) {
1188
1222
  url.searchParams.append("StartTimeTicks", String(startTimeTicks));
1189
1223
  }
1190
- url.searchParams.append("EnableRedirection", "true");
1191
- url.searchParams.append("EnableRemoteMedia", "false");
1192
1224
  return url.toString();
1193
1225
  }
1194
1226
  /**
@@ -1203,16 +1235,24 @@ var MediaModule = class {
1203
1235
  const qualityResolved = resolveAudioQuality(options.quality);
1204
1236
  const maxStreamingBitrate = options.maxStreamingBitrate ?? qualityResolved.maxStreamingBitrate;
1205
1237
  const {
1238
+ mediaSourceId,
1206
1239
  startTimeTicks = 0,
1207
1240
  audioCodec = "aac,mp3",
1208
1241
  segmentLength = 3,
1209
1242
  useQueryToken = true
1210
1243
  } = options;
1211
1244
  const url = new URL(`${serverUrl}/Audio/${itemId}/master.m3u8`);
1212
- if (token && useQueryToken) url.searchParams.append("api_key", token);
1245
+ if (token && useQueryToken) {
1246
+ url.searchParams.append("ApiKey", token);
1247
+ url.searchParams.append("api_key", token);
1248
+ url.searchParams.append("X-Emby-Token", token);
1249
+ }
1213
1250
  if (userId) url.searchParams.append("UserId", userId);
1214
- if (clientInfo.deviceId) url.searchParams.append("DeviceId", clientInfo.deviceId);
1215
- url.searchParams.append("MediaSourceId", itemId);
1251
+ const targetDeviceId = options.deviceId !== void 0 ? options.deviceId : clientInfo.deviceId;
1252
+ if (targetDeviceId) url.searchParams.append("DeviceId", targetDeviceId);
1253
+ if (mediaSourceId) {
1254
+ url.searchParams.append("MediaSourceId", mediaSourceId);
1255
+ }
1216
1256
  url.searchParams.append("AudioCodec", audioCodec);
1217
1257
  url.searchParams.append("TranscodingContainer", "ts");
1218
1258
  url.searchParams.append("TranscodingProtocol", "hls");
@@ -1257,9 +1297,14 @@ var MediaModule = class {
1257
1297
  } = options;
1258
1298
  const endpoint = container && !container.includes(",") ? `/Videos/${itemId}/stream.${container}` : `/Videos/${itemId}/stream`;
1259
1299
  const url = new URL(`${serverUrl}${endpoint}`);
1260
- if (token && useQueryToken) url.searchParams.append("api_key", token);
1300
+ if (token && useQueryToken) {
1301
+ url.searchParams.append("ApiKey", token);
1302
+ url.searchParams.append("api_key", token);
1303
+ url.searchParams.append("X-Emby-Token", token);
1304
+ }
1261
1305
  if (userId) url.searchParams.append("UserId", userId);
1262
- if (clientInfo.deviceId) url.searchParams.append("DeviceId", clientInfo.deviceId);
1306
+ const targetDeviceId = options.deviceId !== void 0 ? options.deviceId : clientInfo.deviceId;
1307
+ if (targetDeviceId) url.searchParams.append("DeviceId", targetDeviceId);
1263
1308
  if (mediaSourceId) url.searchParams.append("MediaSourceId", mediaSourceId);
1264
1309
  if (isStatic) {
1265
1310
  url.searchParams.append("Static", "true");
@@ -1318,9 +1363,14 @@ var MediaModule = class {
1318
1363
  useQueryToken = true
1319
1364
  } = options;
1320
1365
  const url = new URL(`${serverUrl}/Videos/${itemId}/master.m3u8`);
1321
- if (token && useQueryToken) url.searchParams.append("api_key", token);
1366
+ if (token && useQueryToken) {
1367
+ url.searchParams.append("ApiKey", token);
1368
+ url.searchParams.append("api_key", token);
1369
+ url.searchParams.append("X-Emby-Token", token);
1370
+ }
1322
1371
  if (userId) url.searchParams.append("UserId", userId);
1323
- if (clientInfo.deviceId) url.searchParams.append("DeviceId", clientInfo.deviceId);
1372
+ const targetDeviceId = options.deviceId !== void 0 ? options.deviceId : clientInfo.deviceId;
1373
+ if (targetDeviceId) url.searchParams.append("DeviceId", targetDeviceId);
1324
1374
  if (mediaSourceId) url.searchParams.append("MediaSourceId", mediaSourceId);
1325
1375
  url.searchParams.append("VideoCodec", videoCodec);
1326
1376
  url.searchParams.append("AudioCodec", audioCodec);
@@ -1357,6 +1407,7 @@ var MediaModule = class {
1357
1407
  const sourceId = mediaSourceId || itemId;
1358
1408
  const url = new URL(`${serverUrl}/Videos/${itemId}/${sourceId}/Subtitles/${subtitleStreamIndex}/Stream.${format}`);
1359
1409
  if (token && useQueryToken) {
1410
+ url.searchParams.append("ApiKey", token);
1360
1411
  url.searchParams.append("api_key", token);
1361
1412
  }
1362
1413
  if (startTimeTicks > 0) {
@@ -1430,6 +1481,7 @@ var MediaModule = class {
1430
1481
  if (!serverUrl || !itemId) return "";
1431
1482
  const url = new URL(`${serverUrl}/Items/${itemId}/Download`);
1432
1483
  if (token && useQueryToken) {
1484
+ url.searchParams.append("ApiKey", token);
1433
1485
  url.searchParams.append("api_key", token);
1434
1486
  }
1435
1487
  if (filename) {
@@ -1476,13 +1528,17 @@ var MediaModule = class {
1476
1528
  /**
1477
1529
  * Returns authentication headers for media streaming requests (e.g., configuring hls.js xhrSetup).
1478
1530
  * Crucial for Jellyfin 12+ servers where query-based auth (?api_key=) is disabled.
1531
+ * Pass { legacy: false } to only send Authorization and avoid conflicting headers or reverse-proxy CORS rejections.
1479
1532
  */
1480
- getStreamHeaders() {
1533
+ getStreamHeaders(options = {}) {
1481
1534
  const authHeader = this.http.getAuthHeader();
1482
- return {
1483
- Authorization: authHeader,
1484
- "X-Emby-Authorization": authHeader
1535
+ const headers = {
1536
+ Authorization: authHeader
1485
1537
  };
1538
+ if (options.legacy ?? true) {
1539
+ headers["X-Emby-Authorization"] = authHeader;
1540
+ }
1541
+ return headers;
1486
1542
  }
1487
1543
  };
1488
1544
 
@@ -2217,180 +2273,1452 @@ var SearchModule = class {
2217
2273
  }
2218
2274
  };
2219
2275
 
2220
- // src/cache.ts
2221
- var MemoryCacheAdapter = class {
2222
- cache = /* @__PURE__ */ new Map();
2223
- get(key) {
2224
- const entry = this.cache.get(key);
2225
- return entry ? entry.data : null;
2276
+ // src/websocket.ts
2277
+ var WebSocketModule = class {
2278
+ http;
2279
+ getDeviceId;
2280
+ ws = null;
2281
+ keepAliveTimer = null;
2282
+ reconnectTimer = null;
2283
+ listeners = /* @__PURE__ */ new Map();
2284
+ reconnectAttempts = 0;
2285
+ explicitlyClosed = false;
2286
+ options = {};
2287
+ constructor(http, getDeviceId) {
2288
+ this.http = http;
2289
+ this.getDeviceId = getDeviceId;
2226
2290
  }
2227
- set(key, data) {
2228
- this.cache.set(key, { data, timestamp: Date.now() });
2291
+ /**
2292
+ * Check whether the WebSocket is currently open and connected.
2293
+ */
2294
+ get isConnected() {
2295
+ return this.ws !== null && this.ws.readyState === 1;
2229
2296
  }
2230
- delete(key) {
2231
- this.cache.delete(key);
2297
+ /**
2298
+ * Build the Jellyfin WebSocket URL from current serverUrl, accessToken, and deviceId.
2299
+ */
2300
+ getWebSocketUrl() {
2301
+ const serverUrl = this.http.getServerUrl();
2302
+ if (!serverUrl) {
2303
+ throw new JellyfinError("Server URL is required to connect to WebSocket.");
2304
+ }
2305
+ const token = this.http.getToken();
2306
+ if (!token) {
2307
+ throw new JellyfinError("Access token is required to connect to WebSocket. Please authenticate first.");
2308
+ }
2309
+ const deviceId = this.getDeviceId();
2310
+ const wsBaseUrl = serverUrl.replace(/^http:\/\//i, "ws://").replace(/^https:\/\//i, "wss://").replace(/\/+$/, "");
2311
+ const url = new URL(`${wsBaseUrl}/socket`);
2312
+ url.searchParams.set("api_key", token);
2313
+ if (deviceId) {
2314
+ url.searchParams.set("deviceId", deviceId);
2315
+ }
2316
+ return url.toString();
2232
2317
  }
2233
- clear() {
2234
- this.cache.clear();
2318
+ /**
2319
+ * Connect to the Jellyfin WebSocket endpoint.
2320
+ */
2321
+ connect(options = {}) {
2322
+ this.options = {
2323
+ autoReconnect: true,
2324
+ reconnectIntervalMs: 5e3,
2325
+ maxReconnectAttempts: 10,
2326
+ keepAliveIntervalMs: 3e4,
2327
+ ...options
2328
+ };
2329
+ this.explicitlyClosed = false;
2330
+ this.cleanup();
2331
+ const socketUrl = this.options.url || this.getWebSocketUrl();
2332
+ let SocketConstructor = this.options.webSocketFactory ? null : typeof globalThis !== "undefined" ? globalThis.WebSocket : null;
2333
+ if (this.options.webSocketFactory) {
2334
+ this.ws = this.options.webSocketFactory(socketUrl);
2335
+ } else if (SocketConstructor) {
2336
+ this.ws = new SocketConstructor(socketUrl);
2337
+ } else {
2338
+ throw new JellyfinError("WebSocket constructor is not available in the current environment. Please supply webSocketFactory in options.");
2339
+ }
2340
+ this.setupSocketEvents();
2235
2341
  }
2236
- };
2237
- var IndexedDBCacheAdapter = class {
2238
- dbName;
2239
- dbVersion;
2240
- storeName;
2241
- dbPromise = null;
2242
- constructor(dbName = "JellyfinSdkCache", dbVersion = 1, storeName = "api_cache") {
2243
- this.dbName = dbName;
2244
- this.dbVersion = dbVersion;
2245
- this.storeName = storeName;
2342
+ /**
2343
+ * Disconnect the WebSocket and prevent automatic reconnection.
2344
+ */
2345
+ disconnect() {
2346
+ this.explicitlyClosed = true;
2347
+ this.cleanup();
2246
2348
  }
2247
- async getDB() {
2248
- if (this.dbPromise) return this.dbPromise;
2249
- this.dbPromise = new Promise((resolve) => {
2250
- if (typeof window === "undefined" || !("indexedDB" in window)) {
2251
- resolve(null);
2252
- return;
2253
- }
2254
- const request = indexedDB.open(this.dbName, this.dbVersion);
2255
- request.onupgradeneeded = (event) => {
2256
- const db = event.target.result;
2257
- if (!db.objectStoreNames.contains(this.storeName)) {
2258
- db.createObjectStore(this.storeName, { keyPath: "key" });
2259
- }
2260
- };
2261
- request.onsuccess = () => resolve(request.result);
2262
- request.onerror = (e) => {
2263
- console.warn("[Jellyfin Cache] IndexedDB open error:", e);
2264
- resolve(null);
2265
- };
2349
+ /**
2350
+ * Send a raw string or JSON message through the open WebSocket.
2351
+ */
2352
+ send(message) {
2353
+ if (!this.isConnected) {
2354
+ throw new JellyfinError("Cannot send message: WebSocket is not open.");
2355
+ }
2356
+ const payload = typeof message === "string" ? message : JSON.stringify(message);
2357
+ this.ws.send(payload);
2358
+ }
2359
+ /**
2360
+ * Send a KeepAlive message to the Jellyfin server.
2361
+ */
2362
+ sendKeepAlive() {
2363
+ this.send({ MessageType: "KeepAlive" });
2364
+ }
2365
+ /**
2366
+ * Subscribe to real-time session updates from the server.
2367
+ */
2368
+ startSessionsSubscription(intervalMs = 1500) {
2369
+ this.send({
2370
+ MessageType: "SessionsStart",
2371
+ Data: `0,${intervalMs}`
2266
2372
  });
2267
- return this.dbPromise;
2268
2373
  }
2269
- async get(key) {
2270
- try {
2271
- const db = await this.getDB();
2272
- if (!db) return null;
2273
- return new Promise((resolve) => {
2274
- const tx = db.transaction(this.storeName, "readonly");
2275
- const store = tx.objectStore(this.storeName);
2276
- const request = store.get(key);
2277
- request.onsuccess = () => {
2278
- const record = request.result;
2279
- resolve(record ? record.data : null);
2280
- };
2281
- request.onerror = () => resolve(null);
2282
- });
2283
- } catch {
2284
- return null;
2285
- }
2374
+ /**
2375
+ * Stop receiving real-time session updates.
2376
+ */
2377
+ stopSessionsSubscription() {
2378
+ this.send({ MessageType: "SessionsStop" });
2286
2379
  }
2287
- async set(key, data) {
2288
- if (!data) return;
2289
- try {
2290
- const db = await this.getDB();
2291
- if (!db) return;
2292
- return new Promise((resolve) => {
2293
- const tx = db.transaction(this.storeName, "readwrite");
2294
- const store = tx.objectStore(this.storeName);
2295
- const record = { key, data, timestamp: Date.now() };
2296
- const request = store.put(record);
2297
- request.onsuccess = () => resolve();
2298
- request.onerror = () => resolve();
2299
- });
2300
- } catch {
2301
- }
2380
+ /**
2381
+ * Subscribe to scheduled tasks updates from the server.
2382
+ */
2383
+ startScheduledTasksSubscription(intervalMs = 1500) {
2384
+ this.send({
2385
+ MessageType: "ScheduledTasksInfoStart",
2386
+ Data: `0,${intervalMs}`
2387
+ });
2302
2388
  }
2303
- async delete(key) {
2304
- try {
2305
- const db = await this.getDB();
2306
- if (!db) return;
2307
- return new Promise((resolve) => {
2308
- const tx = db.transaction(this.storeName, "readwrite");
2309
- const store = tx.objectStore(this.storeName);
2310
- const request = store.delete(key);
2311
- request.onsuccess = () => resolve();
2312
- request.onerror = () => resolve();
2313
- });
2314
- } catch {
2389
+ /**
2390
+ * Stop scheduled tasks updates.
2391
+ */
2392
+ stopScheduledTasksSubscription() {
2393
+ this.send({ MessageType: "ScheduledTasksInfoStop" });
2394
+ }
2395
+ /**
2396
+ * Subscribe to server activity log updates.
2397
+ */
2398
+ startActivityLogSubscription(intervalMs = 1500) {
2399
+ this.send({
2400
+ MessageType: "ActivityLogEntryStart",
2401
+ Data: `0,${intervalMs}`
2402
+ });
2403
+ }
2404
+ /**
2405
+ * Stop server activity log updates.
2406
+ */
2407
+ stopActivityLogSubscription() {
2408
+ this.send({ MessageType: "ActivityLogEntryStop" });
2409
+ }
2410
+ on(event, listener) {
2411
+ const key = event.toLowerCase();
2412
+ if (!this.listeners.has(key)) {
2413
+ this.listeners.set(key, /* @__PURE__ */ new Set());
2315
2414
  }
2415
+ this.listeners.get(key).add(listener);
2416
+ return () => this.off(key, listener);
2316
2417
  }
2317
- async clear() {
2318
- try {
2319
- const db = await this.getDB();
2320
- if (!db) return;
2321
- return new Promise((resolve) => {
2322
- const tx = db.transaction(this.storeName, "readwrite");
2323
- const store = tx.objectStore(this.storeName);
2324
- const request = store.clear();
2325
- request.onsuccess = () => resolve();
2326
- request.onerror = () => resolve();
2327
- });
2328
- } catch {
2418
+ off(event, listener) {
2419
+ const key = event.toLowerCase();
2420
+ const set = this.listeners.get(key);
2421
+ if (set) {
2422
+ set.delete(listener);
2329
2423
  }
2330
2424
  }
2331
- };
2332
- async function fetchWithCache(cache, cacheKey, fetchFn, onFreshData) {
2333
- const cached = await cache.get(cacheKey);
2334
- const backgroundFetch = fetchFn().then(async (freshData) => {
2335
- if (freshData !== null && freshData !== void 0) {
2336
- await cache.set(cacheKey, freshData);
2337
- if (onFreshData) {
2425
+ emit(event, ...args) {
2426
+ const key = event.toLowerCase();
2427
+ const set = this.listeners.get(key);
2428
+ if (set) {
2429
+ set.forEach((listener) => {
2338
2430
  try {
2339
- onFreshData(freshData);
2431
+ listener(...args);
2340
2432
  } catch (e) {
2341
- console.warn("[Jellyfin Cache] Error in onFreshData callback for %s:", cacheKey, e);
2433
+ console.error(`[Jellyfin SDK] WebSocket listener error on '${event}':`, e);
2342
2434
  }
2343
- }
2435
+ });
2344
2436
  }
2345
- return freshData;
2346
- }).catch((err) => {
2347
- console.warn("[Jellyfin Cache] Background fetch failed for %s:", cacheKey, err);
2348
- if (!cached) throw err;
2349
- return cached;
2350
- });
2351
- if (cached !== null && cached !== void 0) {
2352
- return cached;
2353
- }
2354
- return await backgroundFetch;
2355
- }
2356
-
2357
- // src/storage.ts
2358
- var MemoryStorage = class {
2359
- store = /* @__PURE__ */ new Map();
2360
- getItem(key) {
2361
- return this.store.has(key) ? this.store.get(key) : null;
2362
- }
2363
- setItem(key, value) {
2364
- this.store.set(key, value);
2365
2437
  }
2366
- removeItem(key) {
2367
- this.store.delete(key);
2438
+ // --- Internal Socket Helpers ---
2439
+ setupSocketEvents() {
2440
+ if (!this.ws) return;
2441
+ this.ws.onopen = () => {
2442
+ this.reconnectAttempts = 0;
2443
+ this.startKeepAlive();
2444
+ this.emit("open");
2445
+ };
2446
+ this.ws.onclose = (ev) => {
2447
+ this.stopKeepAlive();
2448
+ this.emit("close", ev?.code, ev?.reason);
2449
+ if (!this.explicitlyClosed && this.options.autoReconnect) {
2450
+ this.scheduleReconnect();
2451
+ }
2452
+ };
2453
+ this.ws.onerror = (err) => {
2454
+ this.emit("error", err);
2455
+ };
2456
+ this.ws.onmessage = (event) => {
2457
+ try {
2458
+ const text = typeof event.data === "string" ? event.data : String(event.data);
2459
+ const parsed = JSON.parse(text);
2460
+ this.emit("message", parsed);
2461
+ if (parsed.MessageType) {
2462
+ this.emit(parsed.MessageType, parsed.Data);
2463
+ if (parsed.MessageType === "ForceKeepAlive") {
2464
+ this.sendKeepAlive();
2465
+ }
2466
+ }
2467
+ } catch (e) {
2468
+ this.emit("rawMessage", event.data);
2469
+ }
2470
+ };
2368
2471
  }
2369
- clear() {
2370
- this.store.clear();
2472
+ startKeepAlive() {
2473
+ this.stopKeepAlive();
2474
+ const interval = this.options.keepAliveIntervalMs || 3e4;
2475
+ if (interval > 0) {
2476
+ this.keepAliveTimer = setInterval(() => {
2477
+ if (this.isConnected) {
2478
+ try {
2479
+ this.sendKeepAlive();
2480
+ } catch {
2481
+ }
2482
+ }
2483
+ }, interval);
2484
+ }
2371
2485
  }
2372
- };
2373
- var LocalStorageAdapter = class {
2374
- getItem(key) {
2375
- if (typeof localStorage !== "undefined") {
2376
- return localStorage.getItem(key);
2486
+ stopKeepAlive() {
2487
+ if (this.keepAliveTimer) {
2488
+ clearInterval(this.keepAliveTimer);
2489
+ this.keepAliveTimer = null;
2377
2490
  }
2378
- return null;
2379
2491
  }
2380
- setItem(key, value) {
2381
- if (typeof localStorage !== "undefined") {
2382
- localStorage.setItem(key, value);
2492
+ scheduleReconnect() {
2493
+ const maxAttempts = this.options.maxReconnectAttempts ?? 10;
2494
+ if (this.reconnectAttempts >= maxAttempts) {
2495
+ return;
2383
2496
  }
2497
+ const interval = this.options.reconnectIntervalMs ?? 5e3;
2498
+ const backoffDelay = Math.min(interval * Math.pow(1.5, this.reconnectAttempts), 6e4);
2499
+ this.reconnectAttempts++;
2500
+ this.reconnectTimer = setTimeout(() => {
2501
+ if (!this.explicitlyClosed) {
2502
+ try {
2503
+ this.connect(this.options);
2504
+ } catch (e) {
2505
+ this.emit("error", e);
2506
+ }
2507
+ }
2508
+ }, backoffDelay);
2384
2509
  }
2385
- removeItem(key) {
2386
- if (typeof localStorage !== "undefined") {
2387
- localStorage.removeItem(key);
2510
+ cleanup() {
2511
+ this.stopKeepAlive();
2512
+ if (this.reconnectTimer) {
2513
+ clearTimeout(this.reconnectTimer);
2514
+ this.reconnectTimer = null;
2515
+ }
2516
+ if (this.ws) {
2517
+ try {
2518
+ this.ws.onopen = null;
2519
+ this.ws.onclose = null;
2520
+ this.ws.onerror = null;
2521
+ this.ws.onmessage = null;
2522
+ if (this.ws.readyState === 0 || this.ws.readyState === 1) {
2523
+ this.ws.close();
2524
+ }
2525
+ } catch {
2526
+ }
2527
+ this.ws = null;
2388
2528
  }
2389
2529
  }
2390
2530
  };
2391
- function getDefaultStorage() {
2392
- if (typeof window !== "undefined" && typeof window.localStorage !== "undefined") {
2393
- return new LocalStorageAdapter();
2531
+
2532
+ // src/sessions.ts
2533
+ var SessionsModule = class {
2534
+ http;
2535
+ getUserId;
2536
+ constructor(http, getUserId) {
2537
+ this.http = http;
2538
+ this.getUserId = getUserId;
2539
+ }
2540
+ /**
2541
+ * Query active client sessions across the Jellyfin server via GET /Sessions.
2542
+ */
2543
+ async getSessions(options = {}) {
2544
+ const params = {};
2545
+ if (options.controllableByUserId) {
2546
+ params.ControllableByUserId = options.controllableByUserId;
2547
+ }
2548
+ if (options.deviceId) {
2549
+ params.DeviceId = options.deviceId;
2550
+ }
2551
+ if (options.activeWithinSeconds !== void 0) {
2552
+ params.ActiveWithinSeconds = options.activeWithinSeconds;
2553
+ }
2554
+ const result = await this.http.request("/Sessions", { params });
2555
+ return Array.isArray(result) ? result : [];
2556
+ }
2557
+ /**
2558
+ * Instruct a remote session to start playback of specified items via POST /Sessions/{sessionId}/Playing.
2559
+ *
2560
+ * @param sessionId The target session ID.
2561
+ * @param itemIds Single item ID or array of item IDs to play.
2562
+ * @param options Additional playback parameters (command type, start ticks, etc.).
2563
+ */
2564
+ async play(sessionId, itemIds, options = {}) {
2565
+ if (!sessionId) {
2566
+ throw new JellyfinError("sessionId is required to send a play command.");
2567
+ }
2568
+ const ids = Array.isArray(itemIds) ? itemIds : [itemIds];
2569
+ if (ids.length === 0) {
2570
+ throw new JellyfinError("At least one itemId is required to send a play command.");
2571
+ }
2572
+ const params = {
2573
+ ItemIds: ids.join(","),
2574
+ PlayCommand: options.playCommand || "PlayNow"
2575
+ };
2576
+ if (options.startPositionTicks !== void 0) {
2577
+ params.StartPositionTicks = options.startPositionTicks;
2578
+ }
2579
+ if (options.mediaSourceId) {
2580
+ params.MediaSourceId = options.mediaSourceId;
2581
+ }
2582
+ if (options.audioStreamIndex !== void 0) {
2583
+ params.AudioStreamIndex = options.audioStreamIndex;
2584
+ }
2585
+ if (options.subtitleStreamIndex !== void 0) {
2586
+ params.SubtitleStreamIndex = options.subtitleStreamIndex;
2587
+ }
2588
+ if (options.startIndex !== void 0) {
2589
+ params.StartIndex = options.startIndex;
2590
+ }
2591
+ await this.http.request(`/Sessions/${sessionId}/Playing`, {
2592
+ method: "POST",
2593
+ params
2594
+ });
2595
+ }
2596
+ /**
2597
+ * Send a playback control command to a remote session via POST /Sessions/{sessionId}/Playing/{command}.
2598
+ */
2599
+ async sendPlaystateCommand(sessionId, command, params = {}) {
2600
+ if (!sessionId) {
2601
+ throw new JellyfinError("sessionId is required to send a playstate command.");
2602
+ }
2603
+ await this.http.request(`/Sessions/${sessionId}/Playing/${command}`, {
2604
+ method: "POST",
2605
+ params
2606
+ });
2607
+ }
2608
+ /**
2609
+ * Toggle play / pause on a remote session.
2610
+ */
2611
+ async playPause(sessionId) {
2612
+ return await this.sendPlaystateCommand(sessionId, "PlayPause");
2613
+ }
2614
+ /**
2615
+ * Pause playback on a remote session.
2616
+ */
2617
+ async pause(sessionId) {
2618
+ return await this.sendPlaystateCommand(sessionId, "Pause");
2619
+ }
2620
+ /**
2621
+ * Resume playback on a remote session.
2622
+ */
2623
+ async unpause(sessionId) {
2624
+ return await this.sendPlaystateCommand(sessionId, "Unpause");
2625
+ }
2626
+ /**
2627
+ * Stop playback on a remote session.
2628
+ */
2629
+ async stop(sessionId) {
2630
+ return await this.sendPlaystateCommand(sessionId, "Stop");
2631
+ }
2632
+ /**
2633
+ * Seek to a specific tick position on a remote session.
2634
+ *
2635
+ * @param sessionId Target session ID.
2636
+ * @param positionTicks Position in ticks (1 tick = 10,000 milliseconds = 100 nanoseconds).
2637
+ */
2638
+ async seek(sessionId, positionTicks) {
2639
+ return await this.sendPlaystateCommand(sessionId, "Seek", {
2640
+ SeekPositionTicks: positionTicks
2641
+ });
2642
+ }
2643
+ /**
2644
+ * Skip to the next track on a remote session.
2645
+ */
2646
+ async nextTrack(sessionId) {
2647
+ return await this.sendPlaystateCommand(sessionId, "NextTrack");
2648
+ }
2649
+ /**
2650
+ * Skip to the previous track on a remote session.
2651
+ */
2652
+ async previousTrack(sessionId) {
2653
+ return await this.sendPlaystateCommand(sessionId, "PreviousTrack");
2654
+ }
2655
+ /**
2656
+ * Send a general command to a remote session via POST /Sessions/{sessionId}/Command.
2657
+ */
2658
+ async sendGeneralCommand(sessionId, command) {
2659
+ if (!sessionId) {
2660
+ throw new JellyfinError("sessionId is required to send a general command.");
2661
+ }
2662
+ await this.http.request(`/Sessions/${sessionId}/Command`, {
2663
+ method: "POST",
2664
+ body: {
2665
+ Name: command.Name,
2666
+ Arguments: command.Arguments || {}
2667
+ }
2668
+ });
2669
+ }
2670
+ /**
2671
+ * Set volume level on a remote session (0-100).
2672
+ */
2673
+ async setVolume(sessionId, volume) {
2674
+ const clamped = Math.max(0, Math.min(100, Math.round(volume)));
2675
+ return await this.sendGeneralCommand(sessionId, {
2676
+ Name: "SetVolume",
2677
+ Arguments: { Volume: String(clamped) }
2678
+ });
2679
+ }
2680
+ /**
2681
+ * Mute audio on a remote session.
2682
+ */
2683
+ async mute(sessionId) {
2684
+ return await this.sendGeneralCommand(sessionId, { Name: "Mute" });
2685
+ }
2686
+ /**
2687
+ * Unmute audio on a remote session.
2688
+ */
2689
+ async unmute(sessionId) {
2690
+ return await this.sendGeneralCommand(sessionId, { Name: "Unmute" });
2691
+ }
2692
+ /**
2693
+ * Toggle mute on a remote session.
2694
+ */
2695
+ async toggleMute(sessionId) {
2696
+ return await this.sendGeneralCommand(sessionId, { Name: "ToggleMute" });
2697
+ }
2698
+ /**
2699
+ * Switch the audio stream index on a remote session.
2700
+ */
2701
+ async setAudioStreamIndex(sessionId, index) {
2702
+ return await this.sendGeneralCommand(sessionId, {
2703
+ Name: "SetAudioStreamIndex",
2704
+ Arguments: { Index: String(index) }
2705
+ });
2706
+ }
2707
+ /**
2708
+ * Switch the subtitle stream index on a remote session.
2709
+ */
2710
+ async setSubtitleStreamIndex(sessionId, index) {
2711
+ return await this.sendGeneralCommand(sessionId, {
2712
+ Name: "SetSubtitleStreamIndex",
2713
+ Arguments: { Index: String(index) }
2714
+ });
2715
+ }
2716
+ /**
2717
+ * Display an on-screen dialog message modal on a remote session via POST /Sessions/{sessionId}/Message.
2718
+ */
2719
+ async sendMessage(sessionId, options) {
2720
+ if (!sessionId) {
2721
+ throw new JellyfinError("sessionId is required to send a message.");
2722
+ }
2723
+ const payload = typeof options === "string" ? { Text: options, Header: "Message" } : {
2724
+ Text: options.text,
2725
+ Header: options.header || "Message",
2726
+ TimeoutMs: options.timeoutMs
2727
+ };
2728
+ await this.http.request(`/Sessions/${sessionId}/Message`, {
2729
+ method: "POST",
2730
+ body: payload
2731
+ });
2732
+ }
2733
+ /**
2734
+ * Instruct a remote session to navigate and view an item or page via POST /Sessions/{sessionId}/Viewing.
2735
+ */
2736
+ async viewItem(sessionId, itemType, itemId, itemName) {
2737
+ if (!sessionId) {
2738
+ throw new JellyfinError("sessionId is required to instruct session navigation.");
2739
+ }
2740
+ await this.http.request(`/Sessions/${sessionId}/Viewing`, {
2741
+ method: "POST",
2742
+ params: {
2743
+ ItemType: itemType,
2744
+ ItemId: itemId,
2745
+ ItemName: itemName
2746
+ }
2747
+ });
2748
+ }
2749
+ };
2750
+
2751
+ // src/quick-connect.ts
2752
+ var QuickConnectModule = class {
2753
+ http;
2754
+ constructor(http) {
2755
+ this.http = http;
2756
+ }
2757
+ /**
2758
+ * Check whether Quick Connect is enabled on the connected Jellyfin server.
2759
+ */
2760
+ async isEnabled() {
2761
+ try {
2762
+ const result = await this.http.request("/QuickConnect/Enabled");
2763
+ if (typeof result === "boolean") {
2764
+ return result;
2765
+ }
2766
+ return String(result).toLowerCase() === "true";
2767
+ } catch {
2768
+ return false;
2769
+ }
2770
+ }
2771
+ /**
2772
+ * Initiate a Quick Connect authentication session.
2773
+ * Typically called by a client device (e.g. Smart TV or CLI) to generate a user-facing pairing code.
2774
+ */
2775
+ async initiate() {
2776
+ const result = await this.http.request("/QuickConnect/Initiate", {
2777
+ method: "POST"
2778
+ });
2779
+ if (!result || !result.Code || !result.Secret) {
2780
+ throw new JellyfinError("Quick Connect initiate failed: Invalid server response.");
2781
+ }
2782
+ return result;
2783
+ }
2784
+ /**
2785
+ * Check the current authorization status of an initiated Quick Connect secret.
2786
+ *
2787
+ * @param secret The secret token returned from initiate().
2788
+ */
2789
+ async check(secret) {
2790
+ if (!secret) {
2791
+ throw new JellyfinError("secret is required to check Quick Connect status.");
2792
+ }
2793
+ return await this.http.request("/QuickConnect/Connect", {
2794
+ method: "GET",
2795
+ params: { secret }
2796
+ });
2797
+ }
2798
+ /**
2799
+ * Authorize a Quick Connect pairing code from an authenticated session.
2800
+ * Typically called on a mobile app or browser where the user is already logged in.
2801
+ *
2802
+ * @param code The pairing code shown on the target device.
2803
+ * @param userId Optional specific user ID to authenticate as (defaults to the currently authenticated user).
2804
+ */
2805
+ async authorize(code, userId) {
2806
+ if (!code) {
2807
+ throw new JellyfinError("code is required to authorize Quick Connect.");
2808
+ }
2809
+ const params = {
2810
+ Code: code.replace(/\s+/g, "")
2811
+ // Normalize code by removing spaces
2812
+ };
2813
+ if (userId) {
2814
+ params.UserId = userId;
2815
+ }
2816
+ await this.http.request("/QuickConnect/Authorize", {
2817
+ method: "POST",
2818
+ params
2819
+ });
2820
+ return true;
2821
+ }
2822
+ /**
2823
+ * Repeatedly poll until the user authorizes the Quick Connect request or a timeout occurs.
2824
+ *
2825
+ * @param secret The secret token returned from initiate().
2826
+ * @param options Polling configuration (intervalMs, timeoutMs, signal).
2827
+ */
2828
+ async poll(secret, options = {}) {
2829
+ const { intervalMs = 2e3, timeoutMs = 18e4, signal } = options;
2830
+ const startTime = Date.now();
2831
+ while (Date.now() - startTime < timeoutMs) {
2832
+ if (signal?.aborted) {
2833
+ throw new JellyfinError("Quick Connect polling was aborted.");
2834
+ }
2835
+ const state = await this.check(secret);
2836
+ if (state.Authenticated) {
2837
+ return state;
2838
+ }
2839
+ await new Promise((resolve, reject) => {
2840
+ const timer = setTimeout(() => resolve(), intervalMs);
2841
+ if (signal) {
2842
+ signal.addEventListener(
2843
+ "abort",
2844
+ () => {
2845
+ clearTimeout(timer);
2846
+ reject(new JellyfinError("Quick Connect polling was aborted."));
2847
+ },
2848
+ { once: true }
2849
+ );
2850
+ }
2851
+ });
2852
+ }
2853
+ throw new JellyfinError(`Quick Connect timed out after ${timeoutMs}ms.`);
2854
+ }
2855
+ };
2856
+
2857
+ // src/trickplay.ts
2858
+ var TrickplayModule = class {
2859
+ http;
2860
+ constructor(http) {
2861
+ this.http = http;
2862
+ }
2863
+ /**
2864
+ * Generates the HLS playlist URL for trickplay scrubbing image tiles.
2865
+ * E.g. /Videos/{itemId}/Trickplay/{width}/tiles.m3u8
2866
+ */
2867
+ getTilesHlsUrl(itemId, width, options = {}) {
2868
+ const serverUrl = this.http.getServerUrl();
2869
+ const token = this.http.getToken();
2870
+ const { mediaSourceId, useQueryToken = true } = options;
2871
+ const url = new URL(`${serverUrl}/Videos/${itemId}/Trickplay/${width}/tiles.m3u8`);
2872
+ if (token && useQueryToken) {
2873
+ url.searchParams.append("ApiKey", token);
2874
+ url.searchParams.append("api_key", token);
2875
+ url.searchParams.append("X-Emby-Token", token);
2876
+ }
2877
+ if (mediaSourceId) {
2878
+ url.searchParams.append("MediaSourceId", mediaSourceId);
2879
+ }
2880
+ return url.toString();
2881
+ }
2882
+ /**
2883
+ * Generates the URL for a specific trickplay thumbnail tile image sheet.
2884
+ * E.g. /Videos/{itemId}/Trickplay/{width}/{index}.jpg
2885
+ */
2886
+ getTileImageUrl(itemId, width, index, options = {}) {
2887
+ const serverUrl = this.http.getServerUrl();
2888
+ const token = this.http.getToken();
2889
+ const { mediaSourceId, useQueryToken = true } = options;
2890
+ const url = new URL(`${serverUrl}/Videos/${itemId}/Trickplay/${width}/${index}.jpg`);
2891
+ if (token && useQueryToken) {
2892
+ url.searchParams.append("ApiKey", token);
2893
+ url.searchParams.append("api_key", token);
2894
+ url.searchParams.append("X-Emby-Token", token);
2895
+ }
2896
+ if (mediaSourceId) {
2897
+ url.searchParams.append("MediaSourceId", mediaSourceId);
2898
+ }
2899
+ return url.toString();
2900
+ }
2901
+ /**
2902
+ * Fetches and parses the HLS trickplay manifest (tiles.m3u8) for the given item and resolution.
2903
+ */
2904
+ async getTrickplayManifest(itemId, width, options = {}) {
2905
+ const params = {};
2906
+ if (options.mediaSourceId) {
2907
+ params.MediaSourceId = options.mediaSourceId;
2908
+ }
2909
+ const endpoint = `/Videos/${itemId}/Trickplay/${width}/tiles.m3u8`;
2910
+ const rawM3u8 = await this.http.requestText(endpoint, { params });
2911
+ const tiles = this.parseTilesM3u8(itemId, width, rawM3u8, options.mediaSourceId, options.useQueryToken);
2912
+ return {
2913
+ width,
2914
+ rawM3u8,
2915
+ tiles
2916
+ };
2917
+ }
2918
+ /**
2919
+ * Helper to parse #EXTINF and tile file names from a tiles.m3u8 playlist.
2920
+ */
2921
+ parseTilesM3u8(itemId, width, rawM3u8, mediaSourceId, useQueryToken = true) {
2922
+ const lines = rawM3u8.split(/\r?\n/);
2923
+ const tiles = [];
2924
+ let currentDurationMs = 0;
2925
+ for (const line of lines) {
2926
+ const trimmed = line.trim();
2927
+ if (!trimmed) continue;
2928
+ if (trimmed.startsWith("#EXTINF:")) {
2929
+ const secondsStr = trimmed.substring(8).split(",")[0];
2930
+ const seconds = parseFloat(secondsStr);
2931
+ currentDurationMs = !isNaN(seconds) ? Math.round(seconds * 1e3) : 0;
2932
+ } else if (!trimmed.startsWith("#")) {
2933
+ const indexMatch = trimmed.match(/^(\d+)\.(jpg|jpeg|png|webp)/i);
2934
+ const index = indexMatch ? parseInt(indexMatch[1], 10) : tiles.length;
2935
+ const url = this.getTileImageUrl(itemId, width, index, { mediaSourceId, useQueryToken });
2936
+ tiles.push({
2937
+ index,
2938
+ durationMs: currentDurationMs,
2939
+ url
2940
+ });
2941
+ }
2942
+ }
2943
+ return tiles;
2944
+ }
2945
+ /**
2946
+ * Extracts the available trickplay thumbnail widths from a BaseItemDto's Trickplay metadata.
2947
+ */
2948
+ getAvailableResolutions(item, mediaSourceId) {
2949
+ if (!item.Trickplay) {
2950
+ return [];
2951
+ }
2952
+ const targetMediaSourceId = mediaSourceId || item.MediaSources && item.MediaSources[0]?.Id || Object.keys(item.Trickplay)[0];
2953
+ if (!targetMediaSourceId || !item.Trickplay[targetMediaSourceId]) {
2954
+ return [];
2955
+ }
2956
+ const sourceTrickplay = item.Trickplay[targetMediaSourceId];
2957
+ return Object.keys(sourceTrickplay).map((w) => parseInt(w, 10)).filter((w) => !isNaN(w)).sort((a, b) => a - b);
2958
+ }
2959
+ /**
2960
+ * Retrieves the TrickplayInfoDto metadata for a specified item and optional width.
2961
+ */
2962
+ getTrickplayInfo(item, width, mediaSourceId) {
2963
+ if (!item.Trickplay) {
2964
+ return null;
2965
+ }
2966
+ const targetMediaSourceId = mediaSourceId || item.MediaSources && item.MediaSources[0]?.Id || Object.keys(item.Trickplay)[0];
2967
+ if (!targetMediaSourceId || !item.Trickplay[targetMediaSourceId]) {
2968
+ return null;
2969
+ }
2970
+ const sourceTrickplay = item.Trickplay[targetMediaSourceId];
2971
+ if (width !== void 0 && sourceTrickplay[String(width)]) {
2972
+ return sourceTrickplay[String(width)];
2973
+ }
2974
+ const availableWidths = Object.keys(sourceTrickplay);
2975
+ if (availableWidths.length === 0) {
2976
+ return null;
2977
+ }
2978
+ return sourceTrickplay[availableWidths[0]];
2979
+ }
2980
+ /**
2981
+ * Calculates the exact tile sheet index, image URL, and sprite coordinates (x, y, width, height)
2982
+ * for a given playback timestamp to render scrubbing thumbnails in a player or seekbar UI.
2983
+ */
2984
+ getThumbnailForTimestamp(options) {
2985
+ const {
2986
+ item,
2987
+ timestampMs,
2988
+ timestampTicks,
2989
+ width,
2990
+ mediaSourceId,
2991
+ useQueryToken = true
2992
+ } = options;
2993
+ let info = options.trickplayInfo;
2994
+ if (!info && item) {
2995
+ info = this.getTrickplayInfo(item, width, mediaSourceId) || void 0;
2996
+ }
2997
+ if (!info) {
2998
+ return null;
2999
+ }
3000
+ const timeMs = timestampMs !== void 0 ? timestampMs : timestampTicks !== void 0 ? Math.round(timestampTicks / 1e4) : 0;
3001
+ const interval = info.Interval > 0 ? info.Interval : 1e4;
3002
+ let thumbIndex = Math.floor(Math.max(0, timeMs) / interval);
3003
+ if (info.ThumbnailCount > 0 && thumbIndex >= info.ThumbnailCount) {
3004
+ thumbIndex = info.ThumbnailCount - 1;
3005
+ }
3006
+ const tileCols = info.TileWidth > 0 ? info.TileWidth : 1;
3007
+ const tileRows = info.TileHeight > 0 ? info.TileHeight : 1;
3008
+ const thumbsPerSheet = tileCols * tileRows;
3009
+ const sheetIndex = Math.floor(thumbIndex / thumbsPerSheet);
3010
+ const indexInSheet = thumbIndex % thumbsPerSheet;
3011
+ const col = indexInSheet % tileCols;
3012
+ const row = Math.floor(indexInSheet / tileCols);
3013
+ const x = col * info.Width;
3014
+ const y = row * info.Height;
3015
+ const itemId = item?.Id || "";
3016
+ if (!itemId) {
3017
+ throw new JellyfinError("Item or itemId is required to generate the thumbnail URL.");
3018
+ }
3019
+ const imageUrl = this.getTileImageUrl(itemId, info.Width, sheetIndex, {
3020
+ mediaSourceId,
3021
+ useQueryToken
3022
+ });
3023
+ return {
3024
+ tileIndex: sheetIndex,
3025
+ imageUrl,
3026
+ x,
3027
+ y,
3028
+ width: info.Width,
3029
+ height: info.Height,
3030
+ thumbnailIndex: thumbIndex
3031
+ };
3032
+ }
3033
+ };
3034
+
3035
+ // src/chapters.ts
3036
+ var ChaptersModule = class {
3037
+ http;
3038
+ getUserId;
3039
+ constructor(http, getUserId) {
3040
+ this.http = http;
3041
+ this.getUserId = getUserId;
3042
+ }
3043
+ /**
3044
+ * Synchronously extracts chapter markers from an already fetched BaseItemDto.
3045
+ */
3046
+ extractChapters(item) {
3047
+ return item.Chapters || [];
3048
+ }
3049
+ /**
3050
+ * Fetches the chapter markers for an item from the server.
3051
+ */
3052
+ async getChapters(itemId) {
3053
+ const userId = this.getUserId ? this.getUserId() : "";
3054
+ const endpoint = userId ? `/Users/${userId}/Items/${itemId}` : `/Items/${itemId}`;
3055
+ const item = await this.http.request(endpoint, {
3056
+ params: {
3057
+ Fields: "Chapters"
3058
+ }
3059
+ });
3060
+ return item.Chapters || [];
3061
+ }
3062
+ /**
3063
+ * Generates the URL for a chapter preview thumbnail image.
3064
+ * E.g. /Items/{itemId}/Images/Chapter/{chapterIndex}
3065
+ */
3066
+ getChapterImageUrl(itemId, chapterIndex, options = {}) {
3067
+ const serverUrl = this.http.getServerUrl();
3068
+ const token = this.http.getToken();
3069
+ const {
3070
+ maxWidth,
3071
+ maxHeight,
3072
+ width,
3073
+ height,
3074
+ quality,
3075
+ format,
3076
+ tag,
3077
+ fillWidth,
3078
+ fillHeight,
3079
+ useQueryToken = true
3080
+ } = options;
3081
+ const url = new URL(`${serverUrl}/Items/${itemId}/Images/Chapter/${chapterIndex}`);
3082
+ if (token && useQueryToken) {
3083
+ url.searchParams.append("ApiKey", token);
3084
+ url.searchParams.append("api_key", token);
3085
+ url.searchParams.append("X-Emby-Token", token);
3086
+ }
3087
+ if (tag) url.searchParams.append("tag", tag);
3088
+ if (maxWidth) url.searchParams.append("maxWidth", String(maxWidth));
3089
+ if (maxHeight) url.searchParams.append("maxHeight", String(maxHeight));
3090
+ if (width) url.searchParams.append("width", String(width));
3091
+ if (height) url.searchParams.append("height", String(height));
3092
+ if (quality) url.searchParams.append("quality", String(quality));
3093
+ if (format) url.searchParams.append("format", format);
3094
+ if (fillWidth) url.searchParams.append("fillWidth", String(fillWidth));
3095
+ if (fillHeight) url.searchParams.append("fillHeight", String(fillHeight));
3096
+ return url.toString();
3097
+ }
3098
+ /**
3099
+ * Retrieves media segments (Intro, Outro, Recap, Commercials) for an item via Jellyfin 10.10+ /MediaSegments.
3100
+ */
3101
+ async getMediaSegments(itemId, options = {}) {
3102
+ const params = {
3103
+ itemId
3104
+ };
3105
+ if (options.includeSegmentTypes && options.includeSegmentTypes.length > 0) {
3106
+ params.includeSegmentTypes = options.includeSegmentTypes.join(",");
3107
+ }
3108
+ try {
3109
+ const res = await this.http.request(
3110
+ "/MediaSegments",
3111
+ { params }
3112
+ );
3113
+ if (Array.isArray(res)) {
3114
+ return res;
3115
+ }
3116
+ if (res && Array.isArray(res.Items)) {
3117
+ return res.Items;
3118
+ }
3119
+ return [];
3120
+ } catch {
3121
+ return [];
3122
+ }
3123
+ }
3124
+ /**
3125
+ * Resolves intro and end credits markers for an item, combining /MediaSegments API
3126
+ * and chapter marker heuristics (MarkerType or naming like 'Intro', 'Opening', 'Credits', 'Ending').
3127
+ */
3128
+ async getIntroCredits(itemOrChaptersOrId, mediaSegments) {
3129
+ let itemId = "";
3130
+ let chapters = [];
3131
+ let segments = mediaSegments || [];
3132
+ if (typeof itemOrChaptersOrId === "string") {
3133
+ itemId = itemOrChaptersOrId;
3134
+ if (segments.length === 0) {
3135
+ segments = await this.getMediaSegments(itemId);
3136
+ }
3137
+ if (segments.length === 0) {
3138
+ chapters = await this.getChapters(itemId);
3139
+ }
3140
+ } else if (Array.isArray(itemOrChaptersOrId)) {
3141
+ chapters = itemOrChaptersOrId;
3142
+ } else if (typeof itemOrChaptersOrId === "object" && itemOrChaptersOrId !== null) {
3143
+ itemId = itemOrChaptersOrId.Id;
3144
+ chapters = itemOrChaptersOrId.Chapters || [];
3145
+ if (segments.length === 0 && itemId) {
3146
+ segments = await this.getMediaSegments(itemId);
3147
+ }
3148
+ }
3149
+ const markers = {
3150
+ segments
3151
+ };
3152
+ for (const seg of segments) {
3153
+ const type = String(seg.Type).toLowerCase();
3154
+ if (type === "intro" && !markers.intro) {
3155
+ markers.intro = {
3156
+ startTicks: seg.StartTicks,
3157
+ endTicks: seg.EndTicks,
3158
+ startMs: Math.round(seg.StartTicks / 1e4),
3159
+ endMs: Math.round(seg.EndTicks / 1e4)
3160
+ };
3161
+ } else if ((type === "outro" || type === "credits") && !markers.credits) {
3162
+ markers.credits = {
3163
+ startTicks: seg.StartTicks,
3164
+ endTicks: seg.EndTicks,
3165
+ startMs: Math.round(seg.StartTicks / 1e4),
3166
+ endMs: Math.round(seg.EndTicks / 1e4)
3167
+ };
3168
+ }
3169
+ }
3170
+ if ((!markers.intro || !markers.credits) && chapters.length > 0) {
3171
+ for (let i = 0; i < chapters.length; i++) {
3172
+ const chapter = chapters[i];
3173
+ const nextChapter = chapters[i + 1];
3174
+ const name = (chapter.Name || "").trim();
3175
+ const markerType = (chapter.MarkerType || "").toLowerCase();
3176
+ if (!markers.intro) {
3177
+ if (markerType === "introstart" || /^(intro|opening|theme\s*song)/i.test(name)) {
3178
+ const startTicks = chapter.StartPositionTicks;
3179
+ const endTicks = nextChapter ? nextChapter.StartPositionTicks : startTicks + 90 * 1e7;
3180
+ markers.intro = {
3181
+ startTicks,
3182
+ endTicks,
3183
+ startMs: Math.round(startTicks / 1e4),
3184
+ endMs: Math.round(endTicks / 1e4)
3185
+ };
3186
+ }
3187
+ }
3188
+ if (!markers.credits) {
3189
+ if (markerType === "creditsstart" || /^(credits|outro|ending|end\s*credits)/i.test(name)) {
3190
+ const startTicks = chapter.StartPositionTicks;
3191
+ const endTicks = nextChapter ? nextChapter.StartPositionTicks : startTicks + 180 * 1e7;
3192
+ markers.credits = {
3193
+ startTicks,
3194
+ endTicks,
3195
+ startMs: Math.round(startTicks / 1e4),
3196
+ endMs: Math.round(endTicks / 1e4)
3197
+ };
3198
+ }
3199
+ }
3200
+ }
3201
+ }
3202
+ return markers;
3203
+ }
3204
+ /**
3205
+ * Checks whether the current playback position falls within an intro or credits range.
3206
+ */
3207
+ findCurrentSegment(positionTicks, markersOrSegments) {
3208
+ if (Array.isArray(markersOrSegments)) {
3209
+ for (const seg of markersOrSegments) {
3210
+ if (positionTicks >= seg.StartTicks && positionTicks < seg.EndTicks) {
3211
+ return {
3212
+ type: seg.Type,
3213
+ startTicks: seg.StartTicks,
3214
+ endTicks: seg.EndTicks
3215
+ };
3216
+ }
3217
+ }
3218
+ return null;
3219
+ }
3220
+ const { intro, credits } = markersOrSegments;
3221
+ if (intro && positionTicks >= intro.startTicks && positionTicks < intro.endTicks) {
3222
+ return {
3223
+ type: "Intro",
3224
+ startTicks: intro.startTicks,
3225
+ endTicks: intro.endTicks
3226
+ };
3227
+ }
3228
+ if (credits && positionTicks >= credits.startTicks && positionTicks < credits.endTicks) {
3229
+ return {
3230
+ type: "Credits",
3231
+ startTicks: credits.startTicks,
3232
+ endTicks: credits.endTicks
3233
+ };
3234
+ }
3235
+ return null;
3236
+ }
3237
+ /**
3238
+ * Returns the timestamp ticks to skip to if the current position is within a skippable segment,
3239
+ * or null if not currently within any skippable range.
3240
+ */
3241
+ getSkipPosition(positionTicks, markersOrSegments) {
3242
+ const current = this.findCurrentSegment(positionTicks, markersOrSegments);
3243
+ return current ? current.endTicks : null;
3244
+ }
3245
+ };
3246
+
3247
+ // src/genres.ts
3248
+ var GenresModule = class {
3249
+ http;
3250
+ getUserId;
3251
+ constructor(http, getUserId) {
3252
+ this.http = http;
3253
+ this.getUserId = getUserId;
3254
+ }
3255
+ resolveUserId(explicitUserId) {
3256
+ return explicitUserId || this.getUserId() || "";
3257
+ }
3258
+ /**
3259
+ * Retrieves video/movie genres from the server via GET /Genres.
3260
+ */
3261
+ async getGenres(options = {}) {
3262
+ const userId = this.resolveUserId(options.userId);
3263
+ const params = {};
3264
+ if (userId) params.UserId = userId;
3265
+ if (options.parentId) params.ParentId = options.parentId;
3266
+ if (options.startIndex !== void 0) params.StartIndex = options.startIndex;
3267
+ if (options.limit !== void 0) params.Limit = options.limit;
3268
+ if (options.searchTerm) params.SearchTerm = options.searchTerm;
3269
+ if (options.sortBy) params.SortBy = options.sortBy;
3270
+ if (options.sortOrder) params.SortOrder = options.sortOrder;
3271
+ if (options.enableImages !== void 0) params.EnableImages = options.enableImages;
3272
+ if (options.imageTypeLimit !== void 0) params.ImageTypeLimit = options.imageTypeLimit;
3273
+ if (options.enableImageTypes && options.enableImageTypes.length > 0) {
3274
+ params.EnableImageTypes = options.enableImageTypes.join(",");
3275
+ }
3276
+ return await this.http.request("/Genres", { params });
3277
+ }
3278
+ /**
3279
+ * Retrieves a single genre by name via GET /Genres/{genreName}.
3280
+ */
3281
+ async getGenre(genreName, options = {}) {
3282
+ const userId = this.resolveUserId(options.userId);
3283
+ const params = {};
3284
+ if (userId) params.UserId = userId;
3285
+ return await this.http.request(`/Genres/${encodeURIComponent(genreName)}`, {
3286
+ params
3287
+ });
3288
+ }
3289
+ /**
3290
+ * Retrieves music genres from the server via GET /MusicGenres.
3291
+ */
3292
+ async getMusicGenres(options = {}) {
3293
+ const userId = this.resolveUserId(options.userId);
3294
+ const params = {};
3295
+ if (userId) params.UserId = userId;
3296
+ if (options.parentId) params.ParentId = options.parentId;
3297
+ if (options.startIndex !== void 0) params.StartIndex = options.startIndex;
3298
+ if (options.limit !== void 0) params.Limit = options.limit;
3299
+ if (options.searchTerm) params.SearchTerm = options.searchTerm;
3300
+ if (options.sortBy) params.SortBy = options.sortBy;
3301
+ if (options.sortOrder) params.SortOrder = options.sortOrder;
3302
+ if (options.enableImages !== void 0) params.EnableImages = options.enableImages;
3303
+ if (options.imageTypeLimit !== void 0) params.ImageTypeLimit = options.imageTypeLimit;
3304
+ if (options.enableImageTypes && options.enableImageTypes.length > 0) {
3305
+ params.EnableImageTypes = options.enableImageTypes.join(",");
3306
+ }
3307
+ return await this.http.request("/MusicGenres", { params });
3308
+ }
3309
+ /**
3310
+ * Retrieves a single music genre by name via GET /MusicGenres/{genreName}.
3311
+ */
3312
+ async getMusicGenre(genreName, options = {}) {
3313
+ const userId = this.resolveUserId(options.userId);
3314
+ const params = {};
3315
+ if (userId) params.UserId = userId;
3316
+ return await this.http.request(`/MusicGenres/${encodeURIComponent(genreName)}`, {
3317
+ params
3318
+ });
3319
+ }
3320
+ /**
3321
+ * Retrieves studios/production companies from the server via GET /Studios.
3322
+ */
3323
+ async getStudios(options = {}) {
3324
+ const userId = this.resolveUserId(options.userId);
3325
+ const params = {};
3326
+ if (userId) params.UserId = userId;
3327
+ if (options.parentId) params.ParentId = options.parentId;
3328
+ if (options.startIndex !== void 0) params.StartIndex = options.startIndex;
3329
+ if (options.limit !== void 0) params.Limit = options.limit;
3330
+ if (options.searchTerm) params.SearchTerm = options.searchTerm;
3331
+ if (options.sortBy) params.SortBy = options.sortBy;
3332
+ if (options.sortOrder) params.SortOrder = options.sortOrder;
3333
+ if (options.enableImages !== void 0) params.EnableImages = options.enableImages;
3334
+ if (options.imageTypeLimit !== void 0) params.ImageTypeLimit = options.imageTypeLimit;
3335
+ if (options.enableImageTypes && options.enableImageTypes.length > 0) {
3336
+ params.EnableImageTypes = options.enableImageTypes.join(",");
3337
+ }
3338
+ return await this.http.request("/Studios", { params });
3339
+ }
3340
+ /**
3341
+ * Retrieves a single studio by name via GET /Studios/{studioName}.
3342
+ */
3343
+ async getStudio(studioName, options = {}) {
3344
+ const userId = this.resolveUserId(options.userId);
3345
+ const params = {};
3346
+ if (userId) params.UserId = userId;
3347
+ return await this.http.request(`/Studios/${encodeURIComponent(studioName)}`, {
3348
+ params
3349
+ });
3350
+ }
3351
+ };
3352
+
3353
+ // src/collections.ts
3354
+ var CollectionsModule = class {
3355
+ http;
3356
+ getUserId;
3357
+ constructor(http, getUserId) {
3358
+ this.http = http;
3359
+ this.getUserId = getUserId;
3360
+ }
3361
+ resolveUserId(explicitUserId) {
3362
+ return explicitUserId || this.getUserId() || "";
3363
+ }
3364
+ /**
3365
+ * Retrieves user BoxSet / Collections via GET /Collections.
3366
+ */
3367
+ async getCollections(options = {}) {
3368
+ const userId = this.resolveUserId(options.userId);
3369
+ const params = {};
3370
+ if (userId) params.UserId = userId;
3371
+ if (options.parentId) params.ParentId = options.parentId;
3372
+ if (options.startIndex !== void 0) params.StartIndex = options.startIndex;
3373
+ if (options.limit !== void 0) params.Limit = options.limit;
3374
+ if (options.searchTerm) params.SearchTerm = options.searchTerm;
3375
+ if (options.sortBy) params.SortBy = options.sortBy;
3376
+ if (options.sortOrder) params.SortOrder = options.sortOrder;
3377
+ if (options.enableImages !== void 0) params.EnableImages = options.enableImages;
3378
+ if (options.imageTypeLimit !== void 0) params.ImageTypeLimit = options.imageTypeLimit;
3379
+ if (options.enableImageTypes && options.enableImageTypes.length > 0) {
3380
+ params.EnableImageTypes = options.enableImageTypes.join(",");
3381
+ }
3382
+ return await this.http.request("/Collections", { params });
3383
+ }
3384
+ /**
3385
+ * Retrieves the items belonging to a collection / BoxSet.
3386
+ */
3387
+ async getCollectionItems(collectionId, options = {}) {
3388
+ const userId = this.resolveUserId(options.userId);
3389
+ const endpoint = userId ? `/Users/${userId}/Items` : "/Items";
3390
+ const params = {
3391
+ ParentId: collectionId
3392
+ };
3393
+ if (options.startIndex !== void 0) params.StartIndex = options.startIndex;
3394
+ if (options.limit !== void 0) params.Limit = options.limit;
3395
+ if (options.fields) params.Fields = options.fields;
3396
+ if (options.sortBy) params.SortBy = options.sortBy;
3397
+ if (options.sortOrder) params.SortOrder = options.sortOrder;
3398
+ return await this.http.request(endpoint, { params });
3399
+ }
3400
+ /**
3401
+ * Creates a new BoxSet / Collection via POST /Collections.
3402
+ */
3403
+ async createCollection(options) {
3404
+ const params = {
3405
+ Name: options.name
3406
+ };
3407
+ if (options.ids && options.ids.length > 0) {
3408
+ params.Ids = options.ids.join(",");
3409
+ }
3410
+ if (options.parentId) {
3411
+ params.ParentId = options.parentId;
3412
+ }
3413
+ if (options.isFolder !== void 0) {
3414
+ params.IsFolder = options.isFolder;
3415
+ }
3416
+ return await this.http.request("/Collections", {
3417
+ method: "POST",
3418
+ params
3419
+ });
3420
+ }
3421
+ /**
3422
+ * Adds items to an existing BoxSet / Collection via POST /Collections/{collectionId}/Items.
3423
+ */
3424
+ async addToCollection(collectionId, itemIds) {
3425
+ const ids = Array.isArray(itemIds) ? itemIds.join(",") : itemIds;
3426
+ await this.http.request(`/Collections/${collectionId}/Items`, {
3427
+ method: "POST",
3428
+ params: {
3429
+ Ids: ids
3430
+ }
3431
+ });
3432
+ }
3433
+ /**
3434
+ * Removes items from an existing BoxSet / Collection via DELETE /Collections/{collectionId}/Items.
3435
+ */
3436
+ async removeFromCollection(collectionId, itemIds) {
3437
+ const ids = Array.isArray(itemIds) ? itemIds.join(",") : itemIds;
3438
+ await this.http.request(`/Collections/${collectionId}/Items`, {
3439
+ method: "DELETE",
3440
+ params: {
3441
+ Ids: ids
3442
+ }
3443
+ });
3444
+ }
3445
+ };
3446
+
3447
+ // src/display-preferences.ts
3448
+ var DisplayPreferencesModule = class {
3449
+ http;
3450
+ getUserId;
3451
+ defaultClient;
3452
+ constructor(http, getUserId, defaultClient = "emby") {
3453
+ this.http = http;
3454
+ this.getUserId = getUserId;
3455
+ this.defaultClient = defaultClient;
3456
+ }
3457
+ resolveUserId(explicitUserId) {
3458
+ const userId = explicitUserId || this.getUserId();
3459
+ if (!userId) {
3460
+ throw new JellyfinError(
3461
+ "User ID is required for DisplayPreferences. Please authenticate or specify userId."
3462
+ );
3463
+ }
3464
+ return userId;
3465
+ }
3466
+ /**
3467
+ * Retrieves the user's display preferences for a specific folder or view.
3468
+ * GET /DisplayPreferences/{displayPreferencesId}
3469
+ */
3470
+ async getDisplayPreferences(displayPreferencesId, options = {}) {
3471
+ const userId = this.resolveUserId(options.userId);
3472
+ const client = options.client || this.defaultClient;
3473
+ return await this.http.request(
3474
+ `/DisplayPreferences/${displayPreferencesId}`,
3475
+ {
3476
+ params: {
3477
+ userId,
3478
+ client
3479
+ }
3480
+ }
3481
+ );
3482
+ }
3483
+ /**
3484
+ * Updates display preferences for a specific folder or view.
3485
+ * POST /DisplayPreferences/{displayPreferencesId}
3486
+ */
3487
+ async updateDisplayPreferences(displayPreferencesId, preferences, options = {}) {
3488
+ const userId = this.resolveUserId(options.userId);
3489
+ const client = options.client || this.defaultClient;
3490
+ const payload = {
3491
+ ...preferences,
3492
+ Id: preferences.Id || displayPreferencesId,
3493
+ Client: preferences.Client || client
3494
+ };
3495
+ await this.http.request(`/DisplayPreferences/${displayPreferencesId}`, {
3496
+ method: "POST",
3497
+ params: {
3498
+ userId,
3499
+ client
3500
+ },
3501
+ body: payload
3502
+ });
3503
+ }
3504
+ /**
3505
+ * Sets a custom client-specific key-value pair in CustomPrefs.
3506
+ */
3507
+ async setCustomPreference(displayPreferencesId, key, value, options = {}) {
3508
+ const current = await this.getDisplayPreferences(displayPreferencesId, options);
3509
+ const customPrefs = {
3510
+ ...current.CustomPrefs || {},
3511
+ [key]: value
3512
+ };
3513
+ const updated = {
3514
+ ...current,
3515
+ CustomPrefs: customPrefs
3516
+ };
3517
+ await this.updateDisplayPreferences(displayPreferencesId, updated, options);
3518
+ return updated;
3519
+ }
3520
+ /**
3521
+ * Updates sort field and order preferences for a view.
3522
+ */
3523
+ async setSortPreferences(displayPreferencesId, sortBy, sortOrder, options = {}) {
3524
+ const current = await this.getDisplayPreferences(displayPreferencesId, options);
3525
+ const updated = {
3526
+ ...current,
3527
+ SortBy: sortBy,
3528
+ SortOrder: sortOrder,
3529
+ RememberSorting: true
3530
+ };
3531
+ await this.updateDisplayPreferences(displayPreferencesId, updated, options);
3532
+ return updated;
3533
+ }
3534
+ /**
3535
+ * Sets the view presentation layout type (e.g. 'Poster', 'Thumb', 'Banner', 'List').
3536
+ */
3537
+ async setViewType(displayPreferencesId, viewType, options = {}) {
3538
+ const current = await this.getDisplayPreferences(displayPreferencesId, options);
3539
+ const updated = {
3540
+ ...current,
3541
+ ViewType: viewType
3542
+ };
3543
+ await this.updateDisplayPreferences(displayPreferencesId, updated, options);
3544
+ return updated;
3545
+ }
3546
+ };
3547
+
3548
+ // src/cache.ts
3549
+ var MemoryCacheAdapter = class {
3550
+ cache = /* @__PURE__ */ new Map();
3551
+ get(key) {
3552
+ const entry = this.cache.get(key);
3553
+ return entry ? entry.data : null;
3554
+ }
3555
+ set(key, data) {
3556
+ this.cache.set(key, { data, timestamp: Date.now() });
3557
+ }
3558
+ delete(key) {
3559
+ this.cache.delete(key);
3560
+ }
3561
+ clear() {
3562
+ this.cache.clear();
3563
+ }
3564
+ };
3565
+ var IndexedDBCacheAdapter = class {
3566
+ dbName;
3567
+ dbVersion;
3568
+ storeName;
3569
+ dbPromise = null;
3570
+ constructor(dbName = "JellyfinSdkCache", dbVersion = 1, storeName = "api_cache") {
3571
+ this.dbName = dbName;
3572
+ this.dbVersion = dbVersion;
3573
+ this.storeName = storeName;
3574
+ }
3575
+ async getDB() {
3576
+ if (this.dbPromise) return this.dbPromise;
3577
+ this.dbPromise = new Promise((resolve) => {
3578
+ if (typeof window === "undefined" || !("indexedDB" in window)) {
3579
+ resolve(null);
3580
+ return;
3581
+ }
3582
+ const request = indexedDB.open(this.dbName, this.dbVersion);
3583
+ request.onupgradeneeded = (event) => {
3584
+ const db = event.target.result;
3585
+ if (!db.objectStoreNames.contains(this.storeName)) {
3586
+ db.createObjectStore(this.storeName, { keyPath: "key" });
3587
+ }
3588
+ };
3589
+ request.onsuccess = () => resolve(request.result);
3590
+ request.onerror = (e) => {
3591
+ console.warn("[Jellyfin Cache] IndexedDB open error:", e);
3592
+ resolve(null);
3593
+ };
3594
+ });
3595
+ return this.dbPromise;
3596
+ }
3597
+ async get(key) {
3598
+ try {
3599
+ const db = await this.getDB();
3600
+ if (!db) return null;
3601
+ return new Promise((resolve) => {
3602
+ const tx = db.transaction(this.storeName, "readonly");
3603
+ const store = tx.objectStore(this.storeName);
3604
+ const request = store.get(key);
3605
+ request.onsuccess = () => {
3606
+ const record = request.result;
3607
+ resolve(record ? record.data : null);
3608
+ };
3609
+ request.onerror = () => resolve(null);
3610
+ });
3611
+ } catch {
3612
+ return null;
3613
+ }
3614
+ }
3615
+ async set(key, data) {
3616
+ if (!data) return;
3617
+ try {
3618
+ const db = await this.getDB();
3619
+ if (!db) return;
3620
+ return new Promise((resolve) => {
3621
+ const tx = db.transaction(this.storeName, "readwrite");
3622
+ const store = tx.objectStore(this.storeName);
3623
+ const record = { key, data, timestamp: Date.now() };
3624
+ const request = store.put(record);
3625
+ request.onsuccess = () => resolve();
3626
+ request.onerror = () => resolve();
3627
+ });
3628
+ } catch {
3629
+ }
3630
+ }
3631
+ async delete(key) {
3632
+ try {
3633
+ const db = await this.getDB();
3634
+ if (!db) return;
3635
+ return new Promise((resolve) => {
3636
+ const tx = db.transaction(this.storeName, "readwrite");
3637
+ const store = tx.objectStore(this.storeName);
3638
+ const request = store.delete(key);
3639
+ request.onsuccess = () => resolve();
3640
+ request.onerror = () => resolve();
3641
+ });
3642
+ } catch {
3643
+ }
3644
+ }
3645
+ async clear() {
3646
+ try {
3647
+ const db = await this.getDB();
3648
+ if (!db) return;
3649
+ return new Promise((resolve) => {
3650
+ const tx = db.transaction(this.storeName, "readwrite");
3651
+ const store = tx.objectStore(this.storeName);
3652
+ const request = store.clear();
3653
+ request.onsuccess = () => resolve();
3654
+ request.onerror = () => resolve();
3655
+ });
3656
+ } catch {
3657
+ }
3658
+ }
3659
+ };
3660
+ async function fetchWithCache(cache, cacheKey, fetchFn, onFreshData) {
3661
+ const cached = await cache.get(cacheKey);
3662
+ const backgroundFetch = fetchFn().then(async (freshData) => {
3663
+ if (freshData !== null && freshData !== void 0) {
3664
+ await cache.set(cacheKey, freshData);
3665
+ if (onFreshData) {
3666
+ try {
3667
+ onFreshData(freshData);
3668
+ } catch (e) {
3669
+ console.warn("[Jellyfin Cache] Error in onFreshData callback for %s:", cacheKey, e);
3670
+ }
3671
+ }
3672
+ }
3673
+ return freshData;
3674
+ }).catch((err) => {
3675
+ console.warn("[Jellyfin Cache] Background fetch failed for %s:", cacheKey, err);
3676
+ if (!cached) throw err;
3677
+ return cached;
3678
+ });
3679
+ if (cached !== null && cached !== void 0) {
3680
+ return cached;
3681
+ }
3682
+ return await backgroundFetch;
3683
+ }
3684
+
3685
+ // src/storage.ts
3686
+ var MemoryStorage = class {
3687
+ store = /* @__PURE__ */ new Map();
3688
+ getItem(key) {
3689
+ return this.store.has(key) ? this.store.get(key) : null;
3690
+ }
3691
+ setItem(key, value) {
3692
+ this.store.set(key, value);
3693
+ }
3694
+ removeItem(key) {
3695
+ this.store.delete(key);
3696
+ }
3697
+ clear() {
3698
+ this.store.clear();
3699
+ }
3700
+ };
3701
+ var LocalStorageAdapter = class {
3702
+ getItem(key) {
3703
+ if (typeof localStorage !== "undefined") {
3704
+ return localStorage.getItem(key);
3705
+ }
3706
+ return null;
3707
+ }
3708
+ setItem(key, value) {
3709
+ if (typeof localStorage !== "undefined") {
3710
+ localStorage.setItem(key, value);
3711
+ }
3712
+ }
3713
+ removeItem(key) {
3714
+ if (typeof localStorage !== "undefined") {
3715
+ localStorage.removeItem(key);
3716
+ }
3717
+ }
3718
+ };
3719
+ function getDefaultStorage() {
3720
+ if (typeof window !== "undefined" && typeof window.localStorage !== "undefined") {
3721
+ return new LocalStorageAdapter();
2394
3722
  }
2395
3723
  return new MemoryStorage();
2396
3724
  }
@@ -2419,6 +3747,14 @@ var JellyfinClient = class {
2419
3747
  nextUp;
2420
3748
  latest;
2421
3749
  transcode;
3750
+ websocket;
3751
+ sessions;
3752
+ quickConnect;
3753
+ trickplay;
3754
+ chapters;
3755
+ genres;
3756
+ collections;
3757
+ displayPreferences;
2422
3758
  http;
2423
3759
  storage;
2424
3760
  cache;
@@ -2429,7 +3765,7 @@ var JellyfinClient = class {
2429
3765
  this.cache = new MemoryCacheAdapter();
2430
3766
  this.clientInfo = {
2431
3767
  name: options.clientInfo?.name || "@francofantomius/jellyfin",
2432
- version: options.clientInfo?.version || "0.2.0",
3768
+ version: options.clientInfo?.version || "0.4.1",
2433
3769
  device: options.clientInfo?.device || (typeof window !== "undefined" ? "Web Browser" : "Node.js"),
2434
3770
  deviceId: options.clientInfo?.deviceId || generateDeviceId()
2435
3771
  };
@@ -2464,6 +3800,14 @@ var JellyfinClient = class {
2464
3800
  this.nextUp = new NextUpModule(this.http, getUserId);
2465
3801
  this.latest = new LatestModule(this.http, getUserId);
2466
3802
  this.transcode = new TranscodeModule(this.http, getDeviceId);
3803
+ this.websocket = new WebSocketModule(this.http, getDeviceId);
3804
+ this.sessions = new SessionsModule(this.http, getUserId);
3805
+ this.quickConnect = new QuickConnectModule(this.http);
3806
+ this.trickplay = new TrickplayModule(this.http);
3807
+ this.chapters = new ChaptersModule(this.http, getUserId);
3808
+ this.genres = new GenresModule(this.http, getUserId);
3809
+ this.collections = new CollectionsModule(this.http, getUserId);
3810
+ this.displayPreferences = new DisplayPreferencesModule(this.http, getUserId, this.clientInfo.name);
2467
3811
  }
2468
3812
  // --- Configuration Getters & Setters ---
2469
3813
  get serverUrl() {
@@ -2565,6 +3909,9 @@ var JellyfinClient = class {
2565
3909
  * Log out and clear tokens and session.
2566
3910
  */
2567
3911
  logout() {
3912
+ if (this.websocket.isConnected) {
3913
+ this.websocket.disconnect();
3914
+ }
2568
3915
  this.auth.logout();
2569
3916
  this.emit("logout");
2570
3917
  }
@@ -2580,6 +3927,6 @@ var JellyfinClient = class {
2580
3927
  }
2581
3928
  };
2582
3929
 
2583
- export { AUDIO_QUALITY_PRESETS, AuthModule, COMMON_SEARCH_FIELDS, FavoritesModule, HttpTransport, IndexedDBCacheAdapter, JellyfinApiError, JellyfinAuthError, JellyfinClient, JellyfinError, LatestModule, LibraryModule, LocalStorageAdapter, LyricsModule, MediaModule, MemoryCacheAdapter, MemoryStorage, NextUpModule, OfflineStorageManager, PlaybackModule, PlaylistsModule, ResumeModule, SearchModule, SystemModule, TranscodeModule, VIDEO_QUALITY_PRESETS, buildAuthHeader, cleanUrl, fetchWithCache, formatBitrate, generateDeviceId, getAudioQualityList, getDefaultStorage, getVideoQualityList, isV12OrHigher, isVersionAtLeast, parseSemVer, resolveAudioQuality, resolveVideoQuality };
3930
+ export { AUDIO_QUALITY_PRESETS, AuthModule, COMMON_SEARCH_FIELDS, ChaptersModule, CollectionsModule, DisplayPreferencesModule, FavoritesModule, GenresModule, HttpTransport, IndexedDBCacheAdapter, JellyfinApiError, JellyfinAuthError, JellyfinClient, JellyfinError, LatestModule, LibraryModule, LocalStorageAdapter, LyricsModule, MediaModule, MemoryCacheAdapter, MemoryStorage, NextUpModule, OfflineStorageManager, PlaybackModule, PlaylistsModule, QuickConnectModule, ResumeModule, SearchModule, SessionsModule, SystemModule, TranscodeModule, TrickplayModule, VIDEO_QUALITY_PRESETS, WebSocketModule, buildAuthHeader, cleanUrl, fetchWithCache, formatBitrate, generateDeviceId, getAudioQualityList, getDefaultStorage, getVideoQualityList, isV12OrHigher, isVersionAtLeast, parseSemVer, resolveAudioQuality, resolveVideoQuality };
2584
3931
  //# sourceMappingURL=index.js.map
2585
3932
  //# sourceMappingURL=index.js.map