@xiboplayer/pwa 0.7.21 → 0.7.23

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 (58) hide show
  1. package/dist/assets/__vite-browser-external-DeMPM02e.js +2 -0
  2. package/dist/assets/__vite-browser-external-DeMPM02e.js.map +1 -0
  3. package/dist/assets/chunk-DzMEjpoC.js +1 -0
  4. package/dist/assets/{html2canvas-BAfZNSwU.js → html2canvas-EikzC5d8.js} +2 -2
  5. package/dist/assets/{html2canvas-BAfZNSwU.js.map → html2canvas-EikzC5d8.js.map} +1 -1
  6. package/dist/assets/main-CRdq5ifQ.js +3 -0
  7. package/dist/assets/{main-vwJkNw4Y.js.map → main-CRdq5ifQ.js.map} +1 -1
  8. package/dist/assets/main-DTR2QDcF.js +108 -0
  9. package/dist/assets/main-DTR2QDcF.js.map +1 -0
  10. package/dist/assets/{pdf-Bxz9Nzto.js → pdf-CMz6puSt.js} +1 -1
  11. package/dist/assets/{pdf-Bxz9Nzto.js.map → pdf-CMz6puSt.js.map} +1 -1
  12. package/dist/assets/{setup-B4gZX38p.js → setup-Bw8T9Qq6.js} +2 -2
  13. package/dist/assets/{setup-B4gZX38p.js.map → setup-Bw8T9Qq6.js.map} +1 -1
  14. package/dist/assets/src-A5KHvitf.js +2 -0
  15. package/dist/assets/{src-CROvYSP8.js.map → src-A5KHvitf.js.map} +1 -1
  16. package/dist/assets/{src-DAB0dqGG.js → src-BHsN2u2P.js} +2 -2
  17. package/dist/assets/{src-DAB0dqGG.js.map → src-BHsN2u2P.js.map} +1 -1
  18. package/dist/assets/src-BLUMUwZR.js +1 -0
  19. package/dist/assets/src-BXXcWcHh.js +1 -0
  20. package/dist/assets/src-BxSOopk7.js +1 -0
  21. package/dist/assets/{src-WDu491CE.js → src-BxaX1gGg.js} +2 -2
  22. package/dist/assets/{src-WDu491CE.js.map → src-BxaX1gGg.js.map} +1 -1
  23. package/dist/assets/{src-BtVLiVYZ.js → src-CCAyzQUp.js} +3 -3
  24. package/dist/assets/{src-BtVLiVYZ.js.map → src-CCAyzQUp.js.map} +1 -1
  25. package/dist/assets/src-CWJcD3kA.js +1 -0
  26. package/dist/assets/{src-Cx3tXAAu.js → src-CZ1k5h23.js} +3 -3
  27. package/dist/assets/{src-Cx3tXAAu.js.map → src-CZ1k5h23.js.map} +1 -1
  28. package/dist/assets/src-ClrziKzV.js +16 -0
  29. package/dist/assets/src-ClrziKzV.js.map +1 -0
  30. package/dist/assets/{src-C_Lx4lXp.js → src-CtjjclS4.js} +2 -2
  31. package/dist/assets/{src-C_Lx4lXp.js.map → src-CtjjclS4.js.map} +1 -1
  32. package/dist/assets/src-CuVaZcMo.js +2 -0
  33. package/dist/assets/{src-B_BNICay.js.map → src-CuVaZcMo.js.map} +1 -1
  34. package/dist/assets/src-Cy5OUviT.js +1 -0
  35. package/dist/assets/src-DK5BYonP.js +630 -0
  36. package/dist/assets/src-DK5BYonP.js.map +1 -0
  37. package/dist/assets/src-Dk-W3N33.js +1 -0
  38. package/dist/assets/{src-cUopH0nN.js → src-xPTO7Ts6.js} +3 -3
  39. package/dist/assets/{src-cUopH0nN.js.map → src-xPTO7Ts6.js.map} +1 -1
  40. package/dist/assets/sync-manager-zf1tikPt.js +2 -0
  41. package/dist/assets/sync-manager-zf1tikPt.js.map +1 -0
  42. package/dist/index.html +1 -1
  43. package/dist/setup.html +3 -4
  44. package/dist/sw-pwa.js +2 -2
  45. package/dist/sw-pwa.js.map +1 -1
  46. package/package.json +15 -13
  47. package/dist/assets/chunk-7ZXdHUL4.js +0 -1
  48. package/dist/assets/main-oacre7st.js +0 -108
  49. package/dist/assets/main-oacre7st.js.map +0 -1
  50. package/dist/assets/main-vwJkNw4Y.js +0 -3
  51. package/dist/assets/src-B_BNICay.js +0 -2
  52. package/dist/assets/src-Bjt9ooXK.js +0 -16
  53. package/dist/assets/src-Bjt9ooXK.js.map +0 -1
  54. package/dist/assets/src-CKpVxGpH.js +0 -629
  55. package/dist/assets/src-CKpVxGpH.js.map +0 -1
  56. package/dist/assets/src-CROvYSP8.js +0 -2
  57. package/dist/assets/sync-manager-8Z-qwkod.js +0 -2
  58. package/dist/assets/sync-manager-8Z-qwkod.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"sw-pwa.js","names":["log","log","log","VERSION","pkg","_config","log","log","log","log","log","BASE","pkg","CACHE_VERSION"],"sources":["../../utils/package.json","../../utils/src/logger.js","../../crypto/src/rsa.js","../../utils/src/idb.js","../../utils/src/config.js","../../utils/src/fetch-retry.js","../../utils/src/cms-api.js","../../utils/src/index.js","../../cache/src/file-types.js","../../cache/src/download-manager.js","../../cache/package.json","../../cache/src/cache.js","../../cache/src/store-client.js","../../cache/src/cache-analyzer.js","../../cache/src/widget-html.js","../../cache/src/index.js","../../sw/src/sw-utils.js","../../sw/src/request-handler.js","../../sw/src/message-handler.js","../../sw/src/chunk-config.js","../public/sw-pwa.js"],"sourcesContent":["{\n \"name\": \"@xiboplayer/utils\",\n \"version\": \"0.7.21\",\n \"description\": \"Shared utilities for xiboplayer packages\",\n \"type\": \"module\",\n \"main\": \"./src/index.js\",\n \"types\": \"./src/index.d.ts\",\n \"exports\": {\n \".\": \"./src/index.js\",\n \"./logger\": \"./src/logger.js\",\n \"./event-emitter\": \"./src/event-emitter.js\",\n \"./config\": \"./src/config.js\"\n },\n \"scripts\": {\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\"\n },\n \"dependencies\": {\n \"@xiboplayer/crypto\": \"workspace:*\"\n },\n \"devDependencies\": {\n \"vitest\": \"^4.1.2\"\n },\n \"keywords\": [\n \"xibo\",\n \"digital-signage\",\n \"utilities\",\n \"logger\",\n \"event-emitter\"\n ],\n \"author\": \"Pau Aliagas <linuxnow@gmail.com>\",\n \"license\": \"AGPL-3.0-or-later\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/xibo-players/xiboplayer.git\",\n \"directory\": \"packages/utils\"\n },\n \"homepage\": \"https://xiboplayer.org\"\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Configurable Logger for xiboplayers\n *\n * Supports log levels: DEBUG, INFO, WARNING, ERROR, NONE\n *\n * Level precedence (highest wins):\n * 1. URL param ?logLevel=DEBUG\n * 2. localStorage xibo_log_level\n * 3. CMS setting via RegisterDisplay (call applyCmsLogLevel())\n * 4. Default: WARNING (production-safe)\n *\n * For development, pass ?logLevel=DEBUG in the URL.\n * Electron's --dev flag does this automatically.\n *\n * Loggers created without an explicit level are REACTIVE — they follow\n * the global level at call time, so setLogLevel() affects all of them.\n */\n\nconst LOG_LEVELS = {\n DEBUG: 0,\n INFO: 1,\n WARNING: 2,\n ERROR: 3,\n NONE: 4\n};\n\n// Log sink system — external consumers (e.g., LogReporter) can intercept all log output\nconst logSinks = [];\n\nclass Logger {\n /**\n * @param {string} name - Logger name (shown in prefix)\n * @param {string|null} level - Explicit level string, or null to follow global\n */\n constructor(name, level = null) {\n this.name = name;\n this.useGlobal = (level === null);\n if (!this.useGlobal) {\n this.setLevel(level);\n }\n }\n\n /** HH:MM:SS.mmm timestamp for log lines */\n _ts() {\n const d = new Date();\n return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}.${String(d.getMilliseconds()).padStart(3, '0')}`;\n }\n\n setLevel(level) {\n this.useGlobal = false;\n if (typeof level === 'string') {\n this.level = LOG_LEVELS[level.toUpperCase()] ?? LOG_LEVELS.INFO;\n } else {\n this.level = level;\n }\n }\n\n /** Effective level: own override or global */\n getEffectiveLevel() {\n return this.useGlobal ? globalConfig.level : this.level;\n }\n\n debug(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.DEBUG) {\n console.log(`${this._ts()} [${this.name}] DEBUG:`, ...args);\n }\n _dispatchToSinks('debug', this.name, args);\n }\n\n info(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.INFO) {\n console.log(`${this._ts()} [${this.name}]`, ...args);\n }\n _dispatchToSinks('info', this.name, args);\n }\n\n warn(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.WARNING) {\n console.warn(`${this._ts()} [${this.name}]`, ...args);\n }\n _dispatchToSinks('warning', this.name, args);\n }\n\n error(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.ERROR) {\n console.error(`${this._ts()} [${this.name}]`, ...args);\n }\n _dispatchToSinks('error', this.name, args);\n }\n\n // Convenience method for conditional logging\n log(level, ...args) {\n switch (level.toUpperCase()) {\n case 'DEBUG': return this.debug(...args);\n case 'INFO': return this.info(...args);\n case 'WARNING':\n case 'WARN': return this.warn(...args);\n case 'ERROR': return this.error(...args);\n }\n }\n}\n\n// Global log level configuration\nconst globalConfig = {\n level: LOG_LEVELS.WARNING, // Default: WARNING (production-safe)\n\n setGlobalLevel(level) {\n if (typeof level === 'string') {\n this.level = LOG_LEVELS[level.toUpperCase()] ?? LOG_LEVELS.INFO;\n } else {\n this.level = level;\n }\n\n console.log(`[Logger] Global log level set to: ${this.getLevelName(this.level)}`);\n },\n\n getLevelName(level) {\n return Object.keys(LOG_LEVELS).find(key => LOG_LEVELS[key] === level) || 'UNKNOWN';\n }\n};\n\n// Track whether the level was set by a local override (URL param / localStorage)\nlet hasLocalOverride = false;\n\n// Set global level from environment or localStorage\n// Default: WARNING (production-safe). Use ?logLevel=DEBUG for development,\n// or let the CMS override via applyCmsLogLevel().\nif (typeof window !== 'undefined') {\n const urlParams = new URLSearchParams(window.location.search);\n const urlLevel = urlParams.get('logLevel');\n const storageLevel = localStorage.getItem('xibo_log_level');\n\n // Also check config-injected logLevel (proxy writes xibo_config to localStorage)\n let configLevel = null;\n try {\n const cfg = JSON.parse(localStorage.getItem('xibo_config') || '{}');\n configLevel = cfg.logLevel || null;\n } catch (_) {}\n\n if (urlLevel) {\n globalConfig.setGlobalLevel(urlLevel);\n hasLocalOverride = true;\n } else if (storageLevel) {\n globalConfig.setGlobalLevel(storageLevel);\n hasLocalOverride = true;\n } else if (configLevel) {\n globalConfig.setGlobalLevel(configLevel);\n hasLocalOverride = true;\n } else {\n globalConfig.setGlobalLevel('WARNING');\n }\n} else if (typeof self !== 'undefined' && self.swLogLevel) {\n // Service Worker context: use self.swLogLevel (set before importing this module)\n globalConfig.setGlobalLevel(self.swLogLevel);\n}\n\n// Factory function — loggers follow global level by default (reactive)\nexport function createLogger(name, level = null) {\n return new Logger(name, level);\n}\n\n// Set global log level (and persist to localStorage)\nexport function setLogLevel(level) {\n globalConfig.setGlobalLevel(level);\n\n // Save to localStorage\n if (typeof window !== 'undefined') {\n localStorage.setItem('xibo_log_level', level.toUpperCase());\n }\n}\n\n// Get current log level name\nexport function getLogLevel() {\n return globalConfig.getLevelName(globalConfig.level);\n}\n\n/**\n * Returns true when the effective global level is DEBUG.\n * Use this for conditional debug features (video controls, overlays, etc.)\n */\nexport function isDebug() {\n return globalConfig.level <= LOG_LEVELS.DEBUG;\n}\n\n/**\n * Apply CMS logLevel setting — only if no local override (URL/localStorage) exists.\n * @param {string} cmsLevel - CMS level string: 'error', 'audit', 'info', 'debug'\n * @returns {boolean} true if the level was applied\n */\nexport function applyCmsLogLevel(cmsLevel) {\n if (hasLocalOverride) return false;\n if (!cmsLevel) return false;\n\n const mapped = mapCmsLogLevel(cmsLevel);\n globalConfig.setGlobalLevel(mapped);\n return true;\n}\n\n/**\n * Map CMS logLevel strings to internal level names.\n * CMS uses: 'emergency','alert','critical','error','warning','notice','info','debug','audit'\n * We collapse them to our 4 levels.\n */\nexport function mapCmsLogLevel(cmsLevel) {\n switch ((cmsLevel || '').toLowerCase()) {\n case 'debug':\n return 'DEBUG';\n case 'info':\n case 'notice':\n case 'audit':\n return 'INFO';\n case 'warning':\n return 'WARNING';\n case 'error':\n case 'critical':\n case 'alert':\n case 'emergency':\n return 'ERROR';\n default:\n return 'INFO';\n }\n}\n\n/**\n * Dispatch log entry to all registered sinks.\n * Sinks receive { level, name, args } and should not throw.\n * @private\n */\nfunction _dispatchToSinks(level, name, args) {\n if (logSinks.length === 0) return;\n for (const fn of logSinks) {\n try {\n fn({ level, name, args });\n } catch (_) {\n // Sink errors must never break logging\n }\n }\n}\n\n/**\n * Register a log sink — receives all log output regardless of level filtering.\n * @param {function} fn - Callback: ({ level, name, args }) => void\n */\nexport function registerLogSink(fn) {\n logSinks.push(fn);\n}\n\n/**\n * Unregister a previously registered log sink.\n * @param {function} fn - The same function reference passed to registerLogSink\n */\nexport function unregisterLogSink(fn) {\n const idx = logSinks.indexOf(fn);\n if (idx >= 0) logSinks.splice(idx, 1);\n}\n\nexport { LOG_LEVELS };\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * RSA key pair generation via Web Crypto API.\n *\n * Generates RSA-1024 keys compatible with the upstream .NET player.\n * The SPKI PEM public key works with PHP's openssl_get_publickey().\n *\n * No runtime dependencies — uses only the Web Crypto API available\n * in browsers, Electron, and Node.js 16+.\n */\n\n/**\n * Convert an ArrayBuffer (DER-encoded key) to PEM format.\n * @param {ArrayBuffer} buffer - DER-encoded key data\n * @param {string} type - Key type label ('PUBLIC KEY' or 'PRIVATE KEY')\n * @returns {string} PEM-formatted key string\n */\nexport function arrayBufferToPem(buffer, type) {\n const bytes = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n const base64 = btoa(binary);\n\n // Split into 64-character lines per PEM spec\n const lines = [];\n for (let i = 0; i < base64.length; i += 64) {\n lines.push(base64.substring(i, i + 64));\n }\n\n return `-----BEGIN ${type}-----\\n${lines.join('\\n')}\\n-----END ${type}-----`;\n}\n\n/**\n * Generate an RSA key pair for XMR registration.\n *\n * Uses RSA-OAEP with SHA-256 and a 1024-bit modulus to match\n * the upstream .NET player's key format.\n *\n * @returns {Promise<{publicKeyPem: string, privateKeyPem: string}>}\n */\nexport async function generateRsaKeyPair() {\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: 1024,\n publicExponent: new Uint8Array([1, 0, 1]), // 65537\n hash: 'SHA-256',\n },\n true, // extractable\n ['encrypt', 'decrypt']\n );\n\n const publicKeyDer = await crypto.subtle.exportKey('spki', keyPair.publicKey);\n const privateKeyDer = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey);\n\n return {\n publicKeyPem: arrayBufferToPem(publicKeyDer, 'PUBLIC KEY'),\n privateKeyPem: arrayBufferToPem(privateKeyDer, 'PRIVATE KEY'),\n };\n}\n\n/**\n * Validate that a string looks like a valid PEM key.\n * Checks for proper BEGIN/END headers and base64 content.\n *\n * @param {string} pem - String to validate\n * @returns {boolean} true if the string appears to be valid PEM\n */\nexport function isValidPemKey(pem) {\n if (!pem || typeof pem !== 'string') return false;\n\n const pemRegex = /^-----BEGIN (PUBLIC KEY|PRIVATE KEY)-----\\n[A-Za-z0-9+/=\\n]+\\n-----END \\1-----$/;\n return pemRegex.test(pem.trim());\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Shared IndexedDB open helper — avoids duplicating the open/upgrade\n * boilerplate across stats, core, and config packages.\n *\n * @param {string} dbName - Database name\n * @param {number} version - Schema version\n * @param {string} storeName - Object store to create on upgrade\n * @param {Object} [options]\n * @param {string} [options.keyPath] - Key path for the store (auto-increment if set)\n * @param {string} [options.indexName] - Index to create on the store\n * @param {string} [options.indexKey] - Key for the index\n * @returns {Promise<IDBDatabase>}\n */\nexport function openIDB(dbName, version, storeName, options = {}) {\n if (typeof indexedDB === 'undefined') {\n return Promise.reject(new Error('IndexedDB not available'));\n }\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(dbName, version);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(storeName)) {\n const storeOpts = options.keyPath\n ? { keyPath: options.keyPath, autoIncrement: true }\n : undefined;\n const store = db.createObjectStore(storeName, storeOpts);\n if (options.indexName && options.indexKey) {\n store.createIndex(options.indexName, options.indexKey, { unique: false });\n }\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\n/**\n * Query records from an IndexedDB index with a cursor, up to a limit.\n * @param {IDBDatabase} db - IndexedDB database instance\n * @param {string} storeName - Object store name\n * @param {string} indexName - Index name\n * @param {any} value - Key to query (passed to openCursor)\n * @param {number} limit - Maximum records to return\n * @returns {Promise<Array>}\n */\nexport function queryByIndex(db, storeName, indexName, value, limit) {\n return new Promise((resolve, reject) => {\n const tx = db.transaction([storeName], 'readonly');\n const index = tx.objectStore(storeName).index(indexName);\n const request = index.openCursor(value);\n const results = [];\n\n request.onsuccess = (event) => {\n const cursor = event.target.result;\n if (cursor && results.length < limit) {\n results.push(cursor.value);\n cursor.continue();\n } else {\n resolve(results);\n }\n };\n request.onerror = () => reject(new Error(`Index query failed: ${request.error}`));\n });\n}\n\n/**\n * Delete records by ID from an IndexedDB object store.\n * @param {IDBDatabase} db - IndexedDB database instance\n * @param {string} storeName - Object store name\n * @param {Array} ids - Array of record IDs to delete\n * @returns {Promise<number>} Number of deleted records\n */\nexport function deleteByIds(db, storeName, ids) {\n return new Promise((resolve, reject) => {\n const tx = db.transaction([storeName], 'readwrite');\n const store = tx.objectStore(storeName);\n let deleted = 0;\n\n for (const id of ids) {\n if (id) {\n const req = store.delete(id);\n req.onsuccess = () => { deleted++; };\n req.onerror = () => { /* individual delete failed — tx.onerror handles fatal */ };\n }\n }\n\n tx.oncomplete = () => resolve(deleted);\n tx.onerror = () => reject(new Error(`Delete failed: ${tx.error}`));\n });\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Configuration management with priority: env vars → localStorage → defaults\n *\n * Storage layout (per-CMS namespacing):\n * xibo_global — device identity: hardwareKey, xmrPubKey, xmrPrivKey\n * xibo_cms:{cmsId} — CMS-scoped: cmsUrl, cmsKey, displayName, xmrChannel, ...\n * xibo_active_cms — string cmsId of the currently active CMS\n * xibo_config — legacy flat key (written for rollback compatibility)\n *\n * In Node.js (tests, CLI): environment variables are the only source.\n * In browser (PWA player): localStorage is primary, env vars override if set.\n */\nimport { generateRsaKeyPair, isValidPemKey } from '@xiboplayer/crypto';\nimport { openIDB } from './idb.js';\nimport { createLogger } from './logger.js';\n\nconst log = createLogger('Config');\n\nconst GLOBAL_KEY = 'xibo_global'; // Device identity (all CMSes)\nconst CMS_PREFIX = 'xibo_cms:'; // Per-CMS config prefix\nconst ACTIVE_CMS_KEY = 'xibo_active_cms'; // Active CMS ID\nconst HW_DB_NAME = 'xibo-hw-backup';\nconst HW_DB_VERSION = 1;\n\n// Keys that belong to device identity (global, not CMS-scoped)\nconst GLOBAL_KEYS = new Set(['hardwareKey', 'xmrPubKey', 'xmrPrivKey']);\n\n/**\n * FNV-1a hash producing a 12-character hex string.\n * Deterministic: same input always produces same output.\n * @param {string} str - Input string to hash\n * @returns {string} 12-character lowercase hex string\n */\nexport function fnvHash(str) {\n let hash = 2166136261; // FNV offset basis\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n hash = hash >>> 0;\n\n // Extend to 12 chars with a second round using a different seed\n let hash2 = hash + 1234567;\n for (let i = 0; i < str.length; i++) {\n hash2 ^= str.charCodeAt(i) + 1;\n hash2 += (hash2 << 1) + (hash2 << 4) + (hash2 << 7) + (hash2 << 8) + (hash2 << 24);\n }\n hash2 = hash2 >>> 0;\n\n return (hash.toString(16).padStart(8, '0') + hash2.toString(16).padStart(8, '0')).substring(0, 12);\n}\n\n/**\n * Compute a deterministic CMS ID from a CMS URL.\n * Format: {hostname}-{fnvHash12}\n *\n * @param {string} cmsUrl - Full CMS URL (e.g. \"https://displays.superpantalles.com\")\n * @returns {string} CMS ID (e.g. \"displays.superpantalles.com-a1b2c3d4e5f6\")\n */\nexport function computeCmsId(cmsUrl) {\n if (!cmsUrl) return null;\n try {\n const url = new URL(cmsUrl);\n const origin = url.origin;\n return `${url.hostname}-${fnvHash(origin)}`;\n } catch (e) {\n // Invalid URL — hash the raw string\n return `unknown-${fnvHash(cmsUrl)}`;\n }\n}\n\n/**\n * Check for environment variable config (highest priority).\n * Env vars: CMS_URL, CMS_KEY, DISPLAY_NAME, HARDWARE_KEY, XMR_CHANNEL\n * Returns config object if any env vars are set, null otherwise.\n */\nfunction loadFromEnv() {\n // Check if process.env is available (Node.js or bundler injection)\n const env = typeof process !== 'undefined' && process.env ? process.env : {};\n\n const envConfig = {\n cmsUrl: env.CMS_URL || '',\n cmsKey: env.CMS_KEY || '',\n displayName: env.DISPLAY_NAME || '',\n hardwareKey: env.HARDWARE_KEY || '',\n xmrChannel: env.XMR_CHANNEL || '',\n googleGeoApiKey: env.GOOGLE_GEO_API_KEY || '',\n };\n\n // Return env config if any value is set\n const hasEnvValues = Object.values(envConfig).some(v => v !== '');\n return hasEnvValues ? envConfig : null;\n}\n\nexport class Config {\n constructor() {\n this._activeCmsId = null;\n this.data = this.load();\n // Async: try to restore hardware key from IndexedDB if localStorage lost it\n // (only when not running from env vars)\n if (!this._fromEnv) {\n this._restoreHardwareKeyFromBackup();\n }\n }\n\n load() {\n // Priority 1: Environment variables (Node.js, tests, CI)\n const envConfig = loadFromEnv();\n if (envConfig) {\n this._fromEnv = true;\n return envConfig;\n }\n\n // Priority 2: localStorage (browser)\n if (typeof localStorage === 'undefined') {\n return { cmsUrl: '', cmsKey: '', displayName: '', hardwareKey: '', xmrChannel: '' };\n }\n\n // Load from split storage (or fresh install)\n const globalJson = localStorage.getItem(GLOBAL_KEY);\n\n if (globalJson) {\n return this._loadSplit();\n }\n\n // Fresh install — no config at all\n return this._loadFresh();\n }\n\n /**\n * Load from split storage (new format).\n * Merges xibo_global + xibo_cms:{activeCmsId} into a single data object.\n */\n _loadSplit() {\n let global = {};\n try {\n global = JSON.parse(localStorage.getItem(GLOBAL_KEY) || '{}');\n } catch (e) {\n log.error('Failed to parse xibo_global:', e);\n }\n\n // Determine active CMS\n const activeCmsId = localStorage.getItem(ACTIVE_CMS_KEY) || null;\n this._activeCmsId = activeCmsId;\n\n let cmsConfig = {};\n if (activeCmsId) {\n try {\n const cmsJson = localStorage.getItem(CMS_PREFIX + activeCmsId);\n if (cmsJson) cmsConfig = JSON.parse(cmsJson);\n } catch (e) {\n log.error('Failed to parse CMS config:', e);\n }\n }\n\n // Merge global + CMS-scoped\n const config = { ...global, ...cmsConfig };\n\n // Validate and generate missing keys\n return this._validateConfig(config);\n }\n\n /**\n * Fresh install — no existing config.\n */\n _loadFresh() {\n const config = {};\n return this._validateConfig(config);\n }\n\n /**\n * Validate config, generate missing hardwareKey/xmrChannel.\n * Shared by all load paths.\n */\n _validateConfig(config) {\n let changed = false;\n\n if (!config.hardwareKey || config.hardwareKey.length < 10) {\n log.warn('Missing/invalid hardwareKey — generating');\n config.hardwareKey = this.generateStableHardwareKey();\n this._backupHardwareKey(config.hardwareKey);\n changed = true;\n } else {\n log.info('✓ Loaded existing hardwareKey:', config.hardwareKey);\n }\n\n if (!config.xmrChannel) {\n log.warn('Missing xmrChannel — generating');\n config.xmrChannel = this.generateXmrChannel();\n changed = true;\n }\n\n // Ensure optional fields have defaults\n config.cmsUrl = config.cmsUrl || '';\n config.cmsKey = config.cmsKey || '';\n config.displayName = config.displayName || '';\n\n if (changed && typeof localStorage !== 'undefined') {\n // Save via split storage\n this._saveSplit(config);\n }\n\n return config;\n }\n\n save() {\n if (typeof localStorage === 'undefined') return;\n this._saveSplit(this.data);\n }\n\n /**\n * Write data to split storage: xibo_global + xibo_cms:{id} + legacy xibo_config.\n */\n _saveSplit(data) {\n if (typeof localStorage === 'undefined') return;\n\n // Split into global and CMS-scoped\n const global = {};\n const cmsScoped = {};\n for (const [key, value] of Object.entries(data)) {\n if (GLOBAL_KEYS.has(key)) {\n global[key] = value;\n } else {\n cmsScoped[key] = value;\n }\n }\n\n localStorage.setItem(GLOBAL_KEY, JSON.stringify(global));\n\n // Compute CMS ID (may update if cmsUrl changed)\n const cmsId = computeCmsId(data.cmsUrl);\n if (cmsId) {\n localStorage.setItem(CMS_PREFIX + cmsId, JSON.stringify(cmsScoped));\n localStorage.setItem(ACTIVE_CMS_KEY, cmsId);\n this._activeCmsId = cmsId;\n }\n\n // Legacy flat key for rollback compatibility (index.html gate, tests, etc.)\n localStorage.setItem('xibo_config', JSON.stringify(data));\n }\n\n /**\n * Switch to a different CMS. Saves the current CMS profile,\n * loads (or creates) the target CMS profile.\n *\n * @param {string} cmsUrl - New CMS URL to switch to\n * @returns {{ cmsId: string, isNew: boolean }} The new CMS ID and whether it was newly created\n */\n switchCms(cmsUrl) {\n if (typeof localStorage === 'undefined') {\n throw new Error('switchCms requires localStorage (browser only)');\n }\n\n // Save current state\n this.save();\n\n const newCmsId = computeCmsId(cmsUrl);\n if (!newCmsId) throw new Error('Invalid CMS URL');\n\n // Try to load existing CMS profile\n const existingJson = localStorage.getItem(CMS_PREFIX + newCmsId);\n let cmsConfig = {};\n let isNew = true;\n\n if (existingJson) {\n try {\n cmsConfig = JSON.parse(existingJson);\n isNew = false;\n log.info(`Switching to existing CMS profile: ${newCmsId}`);\n } catch (e) {\n log.error('Failed to parse target CMS config:', e);\n }\n } else {\n log.info(`Creating new CMS profile: ${newCmsId}`);\n cmsConfig = {\n cmsUrl,\n cmsKey: '',\n displayName: '',\n xmrChannel: this.generateXmrChannel(),\n };\n localStorage.setItem(CMS_PREFIX + newCmsId, JSON.stringify(cmsConfig));\n }\n\n // Update active CMS\n localStorage.setItem(ACTIVE_CMS_KEY, newCmsId);\n this._activeCmsId = newCmsId;\n\n // Merge global + new CMS config into data\n let global = {};\n try {\n global = JSON.parse(localStorage.getItem(GLOBAL_KEY) || '{}');\n } catch (_) {}\n\n this.data = { ...global, ...cmsConfig };\n\n // Ensure cmsUrl is set (in case the profile was pre-existing without it)\n if (!this.data.cmsUrl) {\n this.data.cmsUrl = cmsUrl;\n }\n\n return { cmsId: newCmsId, isNew };\n }\n\n /**\n * List all CMS profiles stored in localStorage.\n * @returns {Array<{ cmsId: string, cmsUrl: string, displayName: string, isActive: boolean }>}\n */\n listCmsProfiles() {\n if (typeof localStorage === 'undefined') return [];\n\n const profiles = [];\n const activeCmsId = localStorage.getItem(ACTIVE_CMS_KEY) || null;\n\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (!key.startsWith(CMS_PREFIX)) continue;\n\n const cmsId = key.slice(CMS_PREFIX.length);\n try {\n const data = JSON.parse(localStorage.getItem(key));\n profiles.push({\n cmsId,\n cmsUrl: data.cmsUrl || '',\n displayName: data.displayName || '',\n isActive: cmsId === activeCmsId,\n });\n } catch (_) {}\n }\n\n return profiles;\n }\n\n /**\n * Get the active CMS ID (deterministic hash of the CMS URL origin).\n * Returns null if no CMS is configured.\n * @returns {string|null}\n */\n get activeCmsId() {\n // Return cached value if available\n if (this._activeCmsId) return this._activeCmsId;\n // Compute from current cmsUrl\n const id = computeCmsId(this.data?.cmsUrl);\n this._activeCmsId = id;\n return id;\n }\n\n isConfigured() {\n return !!(this.data.cmsUrl && this.data.cmsKey && this.data.displayName);\n }\n\n /**\n * Backup keys to IndexedDB (more persistent than localStorage).\n * IndexedDB survives \"Clear site data\" in some browsers where localStorage doesn't.\n * @param {Object} keys - Key-value pairs to store (e.g. { hardwareKey: '...', xmrPubKey: '...' })\n */\n async _backupKeys(keys) {\n try {\n const db = await openIDB(HW_DB_NAME, HW_DB_VERSION, 'keys');\n const tx = db.transaction('keys', 'readwrite');\n const store = tx.objectStore('keys');\n for (const [k, v] of Object.entries(keys)) {\n store.put(v, k);\n }\n tx.oncomplete = () => {\n log.info('Keys backed up to IndexedDB:', Object.keys(keys).join(', '));\n db.close();\n };\n } catch (e) {\n // IndexedDB not available — localStorage-only mode\n }\n }\n\n /**\n * Backup hardware key to IndexedDB (convenience wrapper).\n */\n _backupHardwareKey(key) {\n this._backupKeys({ hardwareKey: key });\n }\n\n /**\n * Restore hardware key from IndexedDB if localStorage was cleared.\n * Runs async after construction — if a backed-up key is found and\n * differs from the current one, it restores the original key.\n */\n async _restoreHardwareKeyFromBackup() {\n try {\n const db = await openIDB(HW_DB_NAME, HW_DB_VERSION, 'keys');\n\n const tx = db.transaction('keys', 'readonly');\n const store = tx.objectStore('keys');\n const backedUpKey = await new Promise((resolve) => {\n const req = store.get('hardwareKey');\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => resolve(null);\n });\n db.close();\n\n if (backedUpKey && backedUpKey !== this.data.hardwareKey) {\n log.info('Restoring hardware key from IndexedDB backup:', backedUpKey);\n log.info('(was:', this.data.hardwareKey, ')');\n this.data.hardwareKey = backedUpKey;\n this.save();\n } else if (!backedUpKey && this.data.hardwareKey) {\n // No backup yet — save current key as backup\n this._backupHardwareKey(this.data.hardwareKey);\n }\n } catch (e) {\n // IndexedDB not available — that's fine\n }\n }\n\n generateStableHardwareKey() {\n // Generate a stable UUID-based hardware key\n // CRITICAL: This is generated ONCE and saved to localStorage\n // It NEVER changes unless localStorage is cleared manually\n\n // Use crypto.randomUUID if available (best randomness)\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n const uuid = crypto.randomUUID().replace(/-/g, ''); // Remove dashes\n const hardwareKey = 'pwa-' + uuid.substring(0, 28);\n log.info('Generated new UUID-based hardware key:', hardwareKey);\n return hardwareKey;\n }\n\n // Fallback: Generate random hex string\n const randomHex = Array.from({ length: 28 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('');\n\n const hardwareKey = 'pwa-' + randomHex;\n log.info('Generated new random hardware key:', hardwareKey);\n return hardwareKey;\n }\n\n generateXmrChannel() {\n // Generate UUID for XMR channel\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n }\n\n /**\n * Ensure an RSA key pair exists for XMR registration.\n * If keys are missing or invalid, generates a new pair and persists them.\n * Idempotent — safe to call multiple times.\n */\n async ensureXmrKeyPair() {\n if (this.data.xmrPubKey && isValidPemKey(this.data.xmrPubKey)) {\n return;\n }\n\n log.info('Generating RSA key pair for XMR registration...');\n const { publicKeyPem, privateKeyPem } = await generateRsaKeyPair();\n\n this.data.xmrPubKey = publicKeyPem;\n this.data.xmrPrivKey = privateKeyPem;\n this.save();\n\n // Backup RSA keys to IndexedDB alongside hardware key\n if (typeof indexedDB !== 'undefined') {\n this._backupKeys({ xmrPubKey: publicKeyPem, xmrPrivKey: privateKeyPem });\n }\n\n log.info('RSA key pair generated and saved');\n }\n\n get cmsUrl() { return this.data.cmsUrl; }\n set cmsUrl(val) { this.data.cmsUrl = val; this.save(); }\n\n get cmsKey() { return this.data.cmsKey; }\n set cmsKey(val) { this.data.cmsKey = val; this.save(); }\n\n get displayName() { return this.data.displayName; }\n set displayName(val) { this.data.displayName = val; this.save(); }\n\n get hardwareKey() {\n // CRITICAL: Ensure hardware key never becomes undefined\n if (!this.data.hardwareKey) {\n log.error('CRITICAL: hardwareKey missing! Generating emergency key.');\n this.data.hardwareKey = this.generateStableHardwareKey();\n this.save();\n }\n return this.data.hardwareKey;\n }\n get xmrChannel() {\n if (!this.data.xmrChannel) {\n log.warn('xmrChannel missing at access time — generating');\n this.data.xmrChannel = this.generateXmrChannel();\n this.save();\n }\n return this.data.xmrChannel;\n }\n get xmrPubKey() { return this.data.xmrPubKey || ''; }\n get xmrPrivKey() { return this.data.xmrPrivKey || ''; }\n\n get googleGeoApiKey() { return this.data.googleGeoApiKey || ''; }\n set googleGeoApiKey(val) { this.data.googleGeoApiKey = val; this.save(); }\n\n get controls() { return this.data.controls || {}; }\n get transport() { return this.data.transport || 'auto'; }\n get debug() { return this.data.debug || {}; }\n}\n\nexport const config = new Config();\n\n/**\n * Shell-only config keys common to ALL player shells (Electron, Chromium, etc.).\n * These control the native shell window/process and must NOT be forwarded to the PWA.\n *\n * Each shell may have additional shell-specific keys — pass them as extraShellKeys\n * to extractPwaConfig().\n *\n * Electron extras: autoLaunch\n * Chromium extras: browser, extraBrowserFlags\n */\n/**\n * Keys that are specific to a particular shell platform.\n * Used by warnPlatformMismatch() to detect config.json mistakes.\n */\nconst PLATFORM_KEYS = {\n kioskMode: ['electron', 'chromium'],\n autoLaunch: ['electron'],\n allowShellCommands: ['electron', 'chromium'],\n browser: ['chromium'],\n extraBrowserFlags: ['chromium'],\n};\n\n/**\n * Log warnings for config keys that don't belong to the current platform.\n * Informational only — does not prevent startup.\n *\n * @param {Object} configObj - The full config.json object\n * @param {string} platform - Current platform: 'electron' or 'chromium'\n */\nexport function warnPlatformMismatch(configObj, platform) {\n if (!configObj || !platform) return;\n const p = platform.toLowerCase();\n for (const [key, platforms] of Object.entries(PLATFORM_KEYS)) {\n if (key in configObj && !platforms.includes(p)) {\n log.warn(\n `Key \"${key}\" is only supported on ${platforms.join('/')}, ` +\n `but current platform is ${p} — this key will be ignored`\n );\n }\n }\n}\n\nexport const SHELL_ONLY_KEYS = new Set([\n 'serverPort',\n 'kioskMode',\n 'fullscreen',\n 'hideMouseCursor',\n 'preventSleep',\n 'allowShellCommands',\n 'width',\n 'height',\n 'relaxSslCerts',\n]);\n\n/**\n * Extract PWA config from a full shell config.json.\n *\n * Uses a deny-list approach: filters out shell-only keys, passes everything else.\n * This is future-proof — new config.json fields automatically reach the PWA\n * without code changes in each shell.\n *\n * @param {Object} config - Full config object from config.json\n * @param {Iterable<string>} [extraShellKeys] - Additional shell-specific keys to exclude\n * @returns {Object} Config to pass to the PWA (via proxy pwaConfig)\n */\nexport function extractPwaConfig(config, extraShellKeys) {\n const exclude = new Set([...SHELL_ONLY_KEYS, ...(extraShellKeys || [])]);\n const pwaConfig = {};\n for (const [key, value] of Object.entries(config)) {\n if (!exclude.has(key)) {\n pwaConfig[key] = value;\n }\n }\n return Object.keys(pwaConfig).length > 0 ? pwaConfig : undefined;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Fetch with retry and exponential backoff\n *\n * Wraps native fetch() with configurable retry logic for transient failures.\n * Only retries on network errors and 5xx server errors (not 4xx client errors).\n * On final attempt, returns the response as-is so the caller can handle errors.\n */\n\nimport { createLogger } from './logger.js';\n\nconst log = createLogger('FetchRetry');\n\nconst DEFAULT_429_DELAY_MS = 30000;\nconst MAX_429_DELAY_MS = 120000;\n\n/**\n * Parse a Retry-After header value into milliseconds.\n * Supports both delta-seconds (\"120\") and HTTP-date (\"Fri, 21 Feb 2026 12:00:00 GMT\").\n * Returns a sensible default if the header is missing or unparseable.\n * The returned delay is NOT capped by maxDelayMs — the server's rate-limit\n * instruction takes priority over our backoff ceiling.\n * @param {string|null} headerValue\n * @returns {number} delay in milliseconds (clamped to MAX_429_DELAY_MS)\n */\nfunction parseRetryAfter(headerValue) {\n if (!headerValue) return DEFAULT_429_DELAY_MS;\n\n // Try delta-seconds first (most common)\n const seconds = Number(headerValue);\n if (!isNaN(seconds) && seconds >= 0) {\n return Math.min(seconds * 1000, MAX_429_DELAY_MS);\n }\n\n // Try HTTP-date format (RFC 7231 §7.1.3)\n const date = new Date(headerValue);\n if (!isNaN(date.getTime())) {\n const delayMs = date.getTime() - Date.now();\n return Math.min(Math.max(delayMs, 0), MAX_429_DELAY_MS);\n }\n\n return DEFAULT_429_DELAY_MS;\n}\n\n/**\n * Fetch with automatic retry on failure\n * @param {string|URL} url - URL to fetch\n * @param {RequestInit} [options] - Fetch options\n * @param {Object} [retryOptions] - Retry configuration\n * @param {number} [retryOptions.maxRetries=3] - Maximum retry attempts\n * @param {number} [retryOptions.baseDelayMs=1000] - Base delay between retries (doubles each time)\n * @param {number} [retryOptions.maxDelayMs=30000] - Maximum delay between retries\n * @returns {Promise<Response>}\n */\nexport async function fetchWithRetry(url, options = {}, retryOptions = {}) {\n const { maxRetries = 3, baseDelayMs = 1000, maxDelayMs = 30000 } = retryOptions;\n\n let lastError;\n let lastResponse;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n\n // HTTP 429 Too Many Requests — respect Retry-After header\n if (response.status === 429) {\n const delayMs = parseRetryAfter(response.headers.get('Retry-After'));\n log.debug(`429 Rate limited, waiting ${delayMs}ms (Retry-After: ${response.headers.get('Retry-After')})`);\n lastResponse = response;\n lastError = new Error(`HTTP 429: Too Many Requests`);\n lastError.status = 429;\n if (attempt < maxRetries) {\n await new Promise(resolve => setTimeout(resolve, delayMs));\n continue; // Skip the normal backoff delay below\n }\n break; // Exhausted retries\n }\n\n // Don't retry anything below 500 — only 5xx server errors are retryable.\n // This covers 2xx (success), 3xx (redirects including 304 Not Modified),\n // and 4xx (client errors that won't change with retries).\n if (response.status < 500) {\n return response;\n }\n\n // Server error (5xx) — retryable, but return on last attempt\n lastResponse = response;\n lastError = new Error(`HTTP ${response.status}: ${response.statusText}`);\n lastError.status = response.status;\n\n // Respect Retry-After on 503 Service Unavailable (e.g. CMS cache warming)\n if (response.status === 503 && attempt < maxRetries) {\n const retryAfter = response.headers.get('Retry-After');\n if (retryAfter) {\n const delayMs = parseRetryAfter(retryAfter);\n log.debug(`503 Service Unavailable, Retry-After: ${retryAfter} (${delayMs}ms)`);\n await new Promise(resolve => setTimeout(resolve, delayMs));\n continue;\n }\n }\n } catch (error) {\n // Network error — retryable\n log.warn(`Fetch error (attempt ${attempt + 1}/${maxRetries + 1}):`, error.message || error, String(url).slice(0, 80));\n lastError = error;\n lastResponse = null;\n }\n\n if (attempt < maxRetries) {\n const delay = Math.min(baseDelayMs * 2 ** attempt, maxDelayMs);\n const jitter = delay * (0.5 + Math.random() * 0.5); // 50-100% of delay\n log.debug(`Retry ${attempt + 1}/${maxRetries} in ${Math.round(jitter)}ms:`, String(url).slice(0, 80));\n await new Promise(resolve => setTimeout(resolve, jitter));\n }\n }\n\n // On exhausted retries: return response if we have one (let caller handle),\n // throw if we only have network errors\n if (lastResponse) {\n return lastResponse;\n }\n throw lastError;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CMS API Client — OAuth2-authenticated REST client for Xibo CMS\n *\n * Full CRUD client for all Xibo CMS REST API entities: displays, layouts,\n * regions, widgets, media, campaigns, schedules, display groups, resolutions,\n * commands, dayparts, playlists, datasets, notifications, folders, and tags.\n * Implements OAuth2 client_credentials flow (machine-to-machine).\n *\n * Usage:\n * const api = new CmsApiClient({ baseUrl: 'https://cms.example.com', clientId, clientSecret });\n * await api.authenticate();\n * const layout = await api.createLayout({ name: 'Test', resolutionId: 9 });\n * const region = await api.addRegion(layout.layoutId, { width: 1920, height: 1080 });\n * await api.addWidget('text', region.playlists[0].playlistId, { text: 'Hello' });\n * await api.publishLayout(layout.layoutId);\n */\n\nimport { createLogger } from './logger.js';\n\nconst log = createLogger('CmsApi');\n\nexport class CmsApiClient {\n /**\n * @param {Object} options\n * @param {string} options.baseUrl - CMS base URL (e.g. https://cms.example.com)\n * @param {string} [options.clientId] - OAuth2 application client ID\n * @param {string} [options.clientSecret] - OAuth2 application client secret\n * @param {string} [options.apiToken] - Pre-configured bearer token (skips OAuth2 flow)\n */\n constructor({ baseUrl, clientId, clientSecret, apiToken } = {}) {\n this.baseUrl = (baseUrl || '').replace(/\\/+$/, '');\n this.clientId = clientId || null;\n this.clientSecret = clientSecret || null;\n this.accessToken = apiToken || null;\n this.tokenExpiry = apiToken ? Infinity : 0;\n }\n\n // ── OAuth2 Token Management ─────────────────────────────────────\n\n /**\n * Authenticate using client_credentials grant\n * @returns {Promise<string>} Access token\n */\n async authenticate() {\n log.info('Authenticating with CMS API...');\n\n const response = await fetch(`${this.baseUrl}/api/authorize/access_token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret\n })\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`OAuth2 authentication failed (${response.status}): ${text}`);\n }\n\n const data = await response.json();\n this.accessToken = data.access_token;\n this.tokenExpiry = Date.now() + (data.expires_in || 3600) * 1000;\n\n log.info('Authenticated successfully, token expires in', data.expires_in, 's');\n return this.accessToken;\n }\n\n /**\n * Ensure we have a valid token (auto-refresh if expired)\n */\n async ensureToken() {\n if (this.accessToken && Date.now() < this.tokenExpiry - 60000) return;\n if (!this.clientId || !this.clientSecret) {\n if (this.accessToken) return; // apiToken with no expiry\n throw new CmsApiError('AUTH', '/authorize', 0, 'No valid token and no OAuth2 credentials');\n }\n await this.authenticate();\n }\n\n /**\n * Make an authenticated API request\n * @param {string} method - HTTP method\n * @param {string} path - API path (e.g. /display)\n * @param {Object} [params] - Query params (GET) or body params (POST/PUT)\n * @returns {Promise<any>} Response data\n */\n async request(method, path, params = {}) {\n await this.ensureToken();\n\n const url = new URL(`${this.baseUrl}/api${path}`);\n const options = {\n method,\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`\n }\n };\n\n if (method === 'GET') {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n url.searchParams.set(key, String(value));\n }\n }\n } else {\n options.headers['Content-Type'] = 'application/x-www-form-urlencoded';\n options.body = new URLSearchParams(params);\n }\n\n const response = await fetch(url, options);\n\n if (!response.ok) {\n await this._handleErrorResponse(response, method, path);\n }\n\n // Some endpoints return empty body (204)\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return response.json();\n }\n return null;\n }\n\n // ── Convenience methods ────────────────────────────────────────\n\n /** GET request (path relative to /api/) */\n get(path, params) { return this.request('GET', path, params); }\n /** POST request (path relative to /api/) */\n post(path, body) { return this.request('POST', path, body); }\n /** PUT request (path relative to /api/) */\n put(path, body) { return this.request('PUT', path, body); }\n /** DELETE request (path relative to /api/) */\n del(path) { return this.request('DELETE', path); }\n\n /**\n * GET a list endpoint and ensure the result is always an array.\n * @param {string} path - API path\n * @param {Object} [filters={}] - Query parameters\n * @returns {Promise<Array>}\n */\n async _listRequest(path, filters = {}) {\n const data = await this.request('GET', path, filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Parse an error response body and throw a structured error.\n * @param {Response} response - Fetch response\n * @param {string} method - HTTP method\n * @param {string} path - API path\n */\n async _handleErrorResponse(response, method, path) {\n const text = await response.text();\n let errorMsg;\n try {\n const errorData = JSON.parse(text);\n errorMsg = errorData.error?.message || errorData.message || text;\n } catch (_) {\n errorMsg = text;\n }\n throw new CmsApiError(method, path, response.status, errorMsg);\n }\n\n // ── Display Management ──────────────────────────────────────────\n\n /**\n * Find a display by hardware key\n * @param {string} hardwareKey\n * @returns {Promise<Object|null>} Display object or null if not found\n */\n async findDisplay(hardwareKey) {\n log.info('Looking up display by hardwareKey:', hardwareKey);\n const displays = await this._listRequest('/display', { hardwareKey });\n if (displays.length === 0) {\n log.info('No display found for hardwareKey:', hardwareKey);\n return null;\n }\n\n const display = displays[0];\n log.info(`Found display: ${display.display} (ID: ${display.displayId}, licensed: ${display.licensed})`);\n return display;\n }\n\n /**\n * Authorize (toggle licence) a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async authorizeDisplay(displayId) {\n log.info('Authorizing display:', displayId);\n await this.request('PUT', `/display/authorise/${displayId}`);\n log.info('Display authorized successfully');\n }\n\n /**\n * Edit display properties\n * @param {number} displayId\n * @param {Object} properties - Properties to update (display, description, defaultLayoutId, etc.)\n * @returns {Promise<Object>} Updated display\n */\n async editDisplay(displayId, properties) {\n log.info('Editing display:', displayId, properties);\n return this.request('PUT', `/display/${displayId}`, properties);\n }\n\n /**\n * List all displays (with optional filters)\n * @param {Object} [filters] - Optional filters (displayId, display, macAddress, hardwareKey, clientType)\n * @returns {Promise<Array>} Array of display objects\n */\n async listDisplays(filters = {}) {\n return this._listRequest('/display', filters);\n }\n\n /**\n * Request screenshot from a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async requestScreenshot(displayId) {\n await this.request('PUT', `/display/requestscreenshot/${displayId}`);\n }\n\n /**\n * Get display status\n * @param {number} displayId\n * @returns {Promise<Object>}\n */\n async getDisplayStatus(displayId) {\n return this.request('GET', `/display/status/${displayId}`);\n }\n\n // ── Multipart Requests (File Uploads) ─────────────────────────────\n\n /**\n * Make an authenticated multipart/form-data request (for file uploads).\n * Do NOT set Content-Type — fetch adds the multipart boundary automatically.\n * @param {string} method - HTTP method (POST/PUT)\n * @param {string} path - API path\n * @param {FormData} formData - Form data with files\n * @returns {Promise<any>} Response data\n */\n async requestMultipart(method, path, formData) {\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api${path}`;\n const response = await fetch(url, {\n method,\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`\n // No Content-Type — fetch sets multipart boundary automatically\n },\n body: formData\n });\n\n if (!response.ok) {\n await this._handleErrorResponse(response, method, path);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return response.json();\n }\n return null;\n }\n\n // ── Layout Management ─────────────────────────────────────────────\n\n /**\n * Create a new layout\n * @param {Object} params\n * @param {string} params.name - Layout name\n * @param {number} params.resolutionId - Resolution ID\n * @param {string} [params.description] - Description\n * @returns {Promise<Object>} Created layout\n */\n async createLayout({ name, resolutionId, description }) {\n const params = { name, resolutionId };\n if (description) params.description = description;\n return this.request('POST', '/layout', params);\n }\n\n /**\n * List layouts with optional filters\n * @param {Object} [filters] - Filters (layoutId, layout, userId, retired, etc.)\n * @returns {Promise<Array>}\n */\n async listLayouts(filters = {}) {\n return this._listRequest('/layout', filters);\n }\n\n /**\n * Get a single layout by ID\n * @param {number} layoutId\n * @returns {Promise<Object>}\n */\n async getLayout(layoutId) {\n return this.request('GET', `/layout/${layoutId}`);\n }\n\n /**\n * Delete a layout\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async deleteLayout(layoutId) {\n await this.request('DELETE', `/layout/${layoutId}`);\n }\n\n /**\n * Publish a draft layout (makes it available for scheduling)\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async publishLayout(layoutId) {\n await this.request('PUT', `/layout/publish/${layoutId}`, { publishNow: 1 });\n }\n\n /**\n * Checkout a published layout (creates editable draft).\n * NOTE: Not needed for newly created layouts — they already have a draft.\n * Use getDraftLayout() to find the auto-created draft instead.\n * @param {number} layoutId\n * @returns {Promise<Object>} Draft layout\n */\n async checkoutLayout(layoutId) {\n return this.request('PUT', `/layout/checkout/${layoutId}`);\n }\n\n /**\n * Get the draft (editable) layout for a given parent layout.\n * In Xibo v4, POST /layout creates a parent + hidden draft automatically.\n * The draft is the one you edit (add regions, widgets) before publishing.\n * @param {number} parentId - The parent layout ID returned by createLayout()\n * @returns {Promise<Object|null>} Draft layout or null if not found\n */\n async getDraftLayout(parentId) {\n const drafts = await this.listLayouts({ parentId });\n return drafts.length > 0 ? drafts[0] : null;\n }\n\n /**\n * Edit layout background\n * @param {number} layoutId\n * @param {Object} params\n * @param {number} [params.backgroundImageId] - Media ID for background image\n * @param {string} [params.backgroundColor] - Hex color (e.g. '#FF0000')\n * @returns {Promise<Object>}\n */\n async editLayoutBackground(layoutId, params) {\n return this.request('PUT', `/layout/background/${layoutId}`, params);\n }\n\n // ── Region Management ─────────────────────────────────────────────\n\n /**\n * Add a region to a layout\n * @param {number} layoutId - Must be the DRAFT layout ID (not the parent)\n * @param {Object} params - { width, height, top, left }\n * @returns {Promise<Object>} Created region with regionPlaylist (singular object, not array)\n */\n async addRegion(layoutId, params) {\n return this.request('POST', `/region/${layoutId}`, params);\n }\n\n /**\n * Edit a region's properties\n * @param {number} regionId\n * @param {Object} params - { width, height, top, left, zIndex }\n * @returns {Promise<Object>}\n */\n async editRegion(regionId, params) {\n return this.request('PUT', `/region/${regionId}`, params);\n }\n\n /**\n * Delete a region\n * @param {number} regionId\n * @returns {Promise<void>}\n */\n async deleteRegion(regionId) {\n await this.request('DELETE', `/region/${regionId}`);\n }\n\n // ── Widget/Playlist Management ────────────────────────────────────\n\n /**\n * Add a widget to a playlist\n *\n * Xibo CMS v4 uses a two-step process:\n * 1. POST creates the widget shell (only templateId and displayOrder are processed)\n * 2. PUT sets all widget properties (uri, duration, mute, etc.)\n *\n * @param {string} type - Widget type (text, image, video, embedded, clock, etc.)\n * @param {number} playlistId - Target playlist ID (from region.playlists[0].playlistId)\n * @param {Object} [properties] - Widget-specific properties\n * @returns {Promise<Object>} Created widget with properties applied\n */\n async addWidget(type, playlistId, properties = {}) {\n // Step 1: Create the widget (only templateId/displayOrder handled by CMS addWidget)\n const { templateId, displayOrder, ...editProps } = properties;\n const createParams = {};\n if (templateId !== undefined) createParams.templateId = templateId;\n if (displayOrder !== undefined) createParams.displayOrder = displayOrder;\n\n const widget = await this.request('POST', `/playlist/widget/${type}/${playlistId}`, createParams);\n\n // Step 2: Set widget properties via editWidget (CMS processes all module properties here)\n if (Object.keys(editProps).length > 0) {\n // useDuration=1 tells CMS to use our custom duration instead of module default\n if (editProps.duration !== undefined && editProps.useDuration === undefined) {\n editProps.useDuration = 1;\n }\n return this.request('PUT', `/playlist/widget/${widget.widgetId}`, editProps);\n }\n\n return widget;\n }\n\n /**\n * Edit a widget's properties\n * @param {number} widgetId\n * @param {Object} properties - Widget-specific properties to update\n * @returns {Promise<Object>}\n */\n async editWidget(widgetId, properties) {\n return this.request('PUT', `/playlist/widget/${widgetId}`, properties);\n }\n\n /**\n * Delete a widget\n * @param {number} widgetId\n * @returns {Promise<void>}\n */\n async deleteWidget(widgetId) {\n await this.request('DELETE', `/playlist/widget/${widgetId}`);\n }\n\n // ── Media / Library ───────────────────────────────────────────────\n\n /**\n * Upload a media file to the library\n * @param {FormData} formData - Must include 'files' field with the file(s)\n * @returns {Promise<Object>} Upload result with media info\n */\n async uploadMedia(formData) {\n return this.requestMultipart('POST', '/library', formData);\n }\n\n /**\n * List media in the library\n * @param {Object} [filters] - Filters (mediaId, media, type, ownerId, etc.)\n * @returns {Promise<Array>}\n */\n async listMedia(filters = {}) {\n return this._listRequest('/library', filters);\n }\n\n /**\n * Get a single media item by ID\n * @param {number} mediaId\n * @returns {Promise<Object>}\n */\n async getMedia(mediaId) {\n return this.request('GET', `/library/${mediaId}`);\n }\n\n /**\n * Delete a media item from the library\n * @param {number} mediaId\n * @returns {Promise<void>}\n */\n async deleteMedia(mediaId) {\n await this.request('DELETE', `/library/${mediaId}`);\n }\n\n // ── Campaign Management ───────────────────────────────────────────\n\n /**\n * Create a campaign\n * @param {string} name - Campaign name\n * @returns {Promise<Object>} Created campaign\n */\n async createCampaign(name) {\n return this.request('POST', '/campaign', { name });\n }\n\n /**\n * List campaigns\n * @param {Object} [filters] - Filters (campaignId, name, etc.)\n * @returns {Promise<Array>}\n */\n async listCampaigns(filters = {}) {\n return this._listRequest('/campaign', filters);\n }\n\n /**\n * Delete a campaign\n * @param {number} campaignId\n * @returns {Promise<void>}\n */\n async deleteCampaign(campaignId) {\n await this.request('DELETE', `/campaign/${campaignId}`);\n }\n\n /**\n * Assign a layout to a campaign\n * @param {number} campaignId\n * @param {number} layoutId\n * @param {number} [displayOrder] - Position in campaign playlist\n * @returns {Promise<void>}\n */\n async assignLayoutToCampaign(campaignId, layoutId, displayOrder) {\n const params = { layoutId };\n if (displayOrder !== undefined) params.displayOrder = displayOrder;\n await this.request('POST', `/campaign/layout/assign/${campaignId}`, params);\n }\n\n // ── Schedule Management ───────────────────────────────────────────\n\n /**\n * Create a schedule event\n * @param {Object} params\n * @param {number} params.eventTypeId - 1=Campaign, 2=Command, 3=Overlay\n * @param {number} params.campaignId - Campaign to schedule\n * @param {Array<number>} params.displayGroupIds - Target display group IDs\n * @param {string} params.fromDt - Start date (ISO 8601)\n * @param {string} params.toDt - End date (ISO 8601)\n * @param {number} [params.isPriority] - 0 or 1\n * @param {number} [params.displayOrder] - Order within schedule\n * @returns {Promise<Object>} Created schedule event\n */\n async createSchedule(params) {\n // displayGroupIds needs to be sent as displayGroupIds[] for the API\n const body = { ...params };\n if (Array.isArray(body.displayGroupIds)) {\n // Xibo API expects repeated keys: displayGroupIds[]=1&displayGroupIds[]=2\n // URLSearchParams handles this when we pass entries manually\n delete body.displayGroupIds;\n }\n\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api/schedule`;\n const urlParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(body)) {\n if (value !== undefined && value !== null) {\n urlParams.set(key, String(value));\n }\n }\n\n // Append array values as repeated keys\n if (Array.isArray(params.displayGroupIds)) {\n for (const id of params.displayGroupIds) {\n urlParams.append('displayGroupIds[]', String(id));\n }\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`CMS API POST /schedule failed (${response.status}): ${text}`);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return response.json();\n }\n return null;\n }\n\n /**\n * Delete a schedule event\n * @param {number} eventId\n * @returns {Promise<void>}\n */\n async deleteSchedule(eventId) {\n await this.request('DELETE', `/schedule/${eventId}`);\n }\n\n /**\n * List schedule events\n * @param {Object} [filters] - Filters (displayGroupIds, fromDt, toDt)\n * @returns {Promise<Array>}\n */\n async listSchedules(filters = {}) {\n const data = await this.request('GET', '/schedule/data/events', filters);\n return Array.isArray(data) ? data : (data?.events || []);\n }\n\n // ── Display Group Management ──────────────────────────────────────\n\n /**\n * List display groups\n * @param {Object} [filters] - Filters (displayGroupId, displayGroup)\n * @returns {Promise<Array>}\n */\n async listDisplayGroups(filters = {}) {\n return this._listRequest('/displaygroup', filters);\n }\n\n /**\n * Create a display group\n * @param {string} name - Display group name\n * @param {string} [description]\n * @returns {Promise<Object>} Created display group\n */\n async createDisplayGroup(name, description) {\n const params = { displayGroup: name };\n if (description) params.description = description;\n return this.request('POST', '/displaygroup', params);\n }\n\n /**\n * Delete a display group\n * @param {number} displayGroupId\n * @returns {Promise<void>}\n */\n async deleteDisplayGroup(displayGroupId) {\n await this.request('DELETE', `/displaygroup/${displayGroupId}`);\n }\n\n /**\n * Assign a display to a display group\n * @param {number} displayGroupId\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async assignDisplayToGroup(displayGroupId, displayId) {\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api/displaygroup/${displayGroupId}/display/assign`;\n const urlParams = new URLSearchParams();\n urlParams.append('displayId[]', String(displayId));\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`CMS API assign display to group failed (${response.status}): ${text}`);\n }\n }\n\n /**\n * Unassign a display from a display group\n * @param {number} displayGroupId\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async unassignDisplayFromGroup(displayGroupId, displayId) {\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api/displaygroup/${displayGroupId}/display/unassign`;\n const urlParams = new URLSearchParams();\n urlParams.append('displayId[]', String(displayId));\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`CMS API unassign display from group failed (${response.status}): ${text}`);\n }\n }\n\n // ── Resolution Management ─────────────────────────────────────────\n\n /**\n * List available resolutions\n * @returns {Promise<Array>}\n */\n async listResolutions() {\n return this._listRequest('/resolution');\n }\n\n // ── Template Management ──────────────────────────────────────────\n\n /**\n * List available layout templates\n * @param {Object} [filters] - Filters (layout, tags, etc.)\n * @returns {Promise<Array>}\n */\n async listTemplates(filters = {}) {\n return this._listRequest('/template', filters);\n }\n\n // ── Playlist Management ──────────────────────────────────────────\n\n /**\n * Assign media library items to a playlist (for file-based widgets: audio, PDF, video)\n * @param {number} playlistId\n * @param {number[]} mediaIds - Array of media IDs to assign\n * @returns {Promise<Object>}\n */\n async assignMediaToPlaylist(playlistId, mediaIds) {\n const ids = Array.isArray(mediaIds) ? mediaIds : [mediaIds];\n // Xibo API expects media[] repeated keys\n await this.ensureToken();\n const url = `${this.baseUrl}/api/playlist/library/assign/${playlistId}`;\n const urlParams = new URLSearchParams();\n for (const id of ids) {\n urlParams.append('media[]', String(id));\n }\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n if (!response.ok) {\n const text = await response.text();\n throw new CmsApiError('POST', `/playlist/library/assign/${playlistId}`, response.status, text);\n }\n const contentType = response.headers.get('Content-Type') || '';\n return contentType.includes('application/json') ? response.json() : null;\n }\n\n // ── Layout Edit ───────────────────────────────────────────────────\n\n /**\n * Edit layout properties\n * @param {number} layoutId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editLayout(layoutId, params) {\n return this.request('PUT', `/layout/${layoutId}`, params);\n }\n\n // ── Layout Copy / Discard (#25) ────────────────────────────────────\n\n /**\n * Copy a layout\n * @param {number} layoutId\n * @param {Object} [opts] - Options (name, description, copyMediaFiles)\n * @returns {Promise<Object>} Copied layout\n */\n async copyLayout(layoutId, opts = {}) {\n return this.post(`/layout/copy/${layoutId}`, opts);\n }\n\n /**\n * Discard a draft layout (revert to last published version)\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async discardLayout(layoutId) {\n await this.put(`/layout/discard/${layoutId}`);\n }\n\n // ── Campaign Edit / Unassign (#26) ─────────────────────────────────\n\n /**\n * Edit campaign properties\n * @param {number} campaignId\n * @param {Object} params - Properties to update (name, etc.)\n * @returns {Promise<Object>} Updated campaign\n */\n async editCampaign(campaignId, params) {\n return this.put(`/campaign/${campaignId}`, params);\n }\n\n /**\n * Get a single campaign by ID\n * @param {number} campaignId\n * @returns {Promise<Object>}\n */\n async getCampaign(campaignId) {\n return this.get(`/campaign/${campaignId}`);\n }\n\n /**\n * Unassign a layout from a campaign\n * @param {number} campaignId\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async unassignLayoutFromCampaign(campaignId, layoutId) {\n await this.post(`/campaign/layout/unassign/${campaignId}`, { layoutId });\n }\n\n // ── Schedule Edit (#27) ────────────────────────────────────────────\n\n /**\n * Edit a schedule event\n * @param {number} eventId\n * @param {Object} params - Properties to update (fromDt, toDt, isPriority, etc.)\n * @returns {Promise<Object>} Updated schedule event\n */\n async editSchedule(eventId, params) {\n return this.put(`/schedule/${eventId}`, params);\n }\n\n // ── Layout Retire / Status / Tag (#34) ─────────────────────────────\n\n /**\n * Retire a layout (hide from new scheduling but keep existing schedules)\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async retireLayout(layoutId) {\n await this.put(`/layout/retire/${layoutId}`);\n }\n\n /**\n * Unretire a previously retired layout\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async unretireLayout(layoutId) {\n await this.put(`/layout/unretire/${layoutId}`);\n }\n\n /**\n * Get layout status (build status, validity)\n * @param {number} layoutId\n * @returns {Promise<Object>}\n */\n async getLayoutStatus(layoutId) {\n return this.get(`/layout/status/${layoutId}`);\n }\n\n /**\n * Tag a layout\n * @param {number} layoutId\n * @param {string[]} tags - Tag names to add\n * @returns {Promise<void>}\n */\n async tagLayout(layoutId, tags) {\n await this.post(`/layout/${layoutId}/tag`, { tag: tags.join(',') });\n }\n\n /**\n * Remove tags from a layout\n * @param {number} layoutId\n * @param {string[]} tags - Tag names to remove\n * @returns {Promise<void>}\n */\n async untagLayout(layoutId, tags) {\n await this.post(`/layout/${layoutId}/untag`, { tag: tags.join(',') });\n }\n\n // ── Command CRUD (#36) ─────────────────────────────────────────────\n\n /**\n * List commands\n * @param {Object} [filters] - Filters (commandId, command)\n * @returns {Promise<Array>}\n */\n async listCommands(filters = {}) {\n return this._listRequest('/command', filters);\n }\n\n /**\n * Create a command\n * @param {Object} params - { command, description, code }\n * @returns {Promise<Object>}\n */\n async createCommand(params) {\n return this.post('/command', params);\n }\n\n /**\n * Edit a command\n * @param {number} commandId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editCommand(commandId, params) {\n return this.put(`/command/${commandId}`, params);\n }\n\n /**\n * Delete a command\n * @param {number} commandId\n * @returns {Promise<void>}\n */\n async deleteCommand(commandId) {\n await this.del(`/command/${commandId}`);\n }\n\n // ── Display Extras (#41) ───────────────────────────────────────────\n\n /**\n * Delete a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async deleteDisplay(displayId) {\n await this.del(`/display/${displayId}`);\n }\n\n /**\n * Send Wake-on-LAN to a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async wolDisplay(displayId) {\n await this.post(`/display/wol/${displayId}`);\n }\n\n /**\n * Set the default layout for a display\n * @param {number} displayId\n * @param {number} layoutId - Layout to set as default\n * @returns {Promise<Object>}\n */\n async setDefaultLayout(displayId, layoutId) {\n return this.put(`/display/${displayId}`, { defaultLayoutId: layoutId });\n }\n\n /**\n * Purge all content from a display (force re-download)\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async purgeDisplay(displayId) {\n await this.post(`/display/purge/${displayId}`);\n }\n\n // ── DayPart CRUD (#24) ─────────────────────────────────────────────\n\n /**\n * List day parts\n * @param {Object} [filters] - Filters (dayPartId, name)\n * @returns {Promise<Array>}\n */\n async listDayParts(filters = {}) {\n return this._listRequest('/daypart', filters);\n }\n\n /**\n * Create a day part\n * @param {Object} params - { name, description, startTime, endTime, exceptionDays, ... }\n * @returns {Promise<Object>}\n */\n async createDayPart(params) {\n return this.post('/daypart', params);\n }\n\n /**\n * Edit a day part\n * @param {number} dayPartId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editDayPart(dayPartId, params) {\n return this.put(`/daypart/${dayPartId}`, params);\n }\n\n /**\n * Delete a day part\n * @param {number} dayPartId\n * @returns {Promise<void>}\n */\n async deleteDayPart(dayPartId) {\n await this.del(`/daypart/${dayPartId}`);\n }\n\n // ── Library Extensions (#33) ───────────────────────────────────────\n\n /**\n * Upload media from a URL\n * @param {string} url - Remote URL to download\n * @param {string} name - Name for the media item\n * @returns {Promise<Object>}\n */\n /**\n * Upload media to the Library from a publicly reachable URL.\n *\n * The CMS fetches the file server-side via MediaFactory::queueDownload —\n * no local download or multipart upload needed. This is the ideal path\n * for importing assets from a CDN or object store (e.g. Cloudflare R2)\n * into the Xibo Library.\n *\n * Targets `POST /library/uploadUrl` (Library::uploadFromUrl in the CMS)\n * which requires form-urlencoded fields. **Not** `POST /library`, which\n * is the multipart file-upload handler and rejects URL imports with HTTP\n * 500. This bug was reported in xibo-players/xiboplayer#332.\n *\n * @param {string} url - Publicly reachable URL of the media\n * @param {string} type - Xibo module type: \"image\", \"video\", \"audio\", \"genericfile\", etc.\n * @param {Object} [options]\n * @param {string} [options.optionalName] - Library display name. If omitted,\n * Xibo derives the name from the URL's filename.\n * @param {string} [options.extension] - Override file extension (otherwise\n * auto-detected from the HTTP Content-Type header).\n * @param {number} [options.folderId] - Target library folder ID.\n * @param {string} [options.enableStat] - 'On' | 'Off' | 'Inherit'.\n * @param {string} [options.expires] - Expiry date in `Y-m-d H:i:s` format.\n * @returns {Promise<{id: number, data: Object}>} Xibo's upload response.\n * `id` is the new mediaId; `data` is the full media object.\n *\n * @example\n * const result = await api.uploadMediaUrl(\n * 'https://media.xiboplayer.org/templates/welcome-lobby/welcome-1.jpg',\n * 'image',\n * { optionalName: 'welcome-lobby · welcome-1.jpg' },\n * );\n * console.log(result.id); // → new mediaId\n */\n async uploadMediaUrl(url, type, options = {}) {\n return this.post('/library/uploadUrl', { url, type, ...options });\n }\n\n /**\n * Copy a media item\n * @param {number} mediaId\n * @returns {Promise<Object>} Copied media\n */\n async copyMedia(mediaId) {\n return this.post(`/library/copy/${mediaId}`);\n }\n\n /**\n * Download a media file (returns raw response for streaming)\n * @param {number} mediaId\n * @returns {Promise<Response>} Raw fetch response\n */\n async downloadMedia(mediaId) {\n await this.ensureToken();\n const url = `${this.baseUrl}/api/library/download/${mediaId}`;\n const response = await fetch(url, {\n headers: { 'Authorization': `Bearer ${this.accessToken}` }\n });\n if (!response.ok) {\n const text = await response.text();\n throw new CmsApiError('GET', `/library/download/${mediaId}`, response.status, text);\n }\n return response;\n }\n\n /**\n * Edit media properties\n * @param {number} mediaId\n * @param {Object} params - Properties to update (name, duration, retired, etc.)\n * @returns {Promise<Object>}\n */\n async editMedia(mediaId, params) {\n return this.put(`/library/${mediaId}`, params);\n }\n\n /**\n * Get media usage (which layouts/playlists reference this media)\n * @param {number} mediaId\n * @returns {Promise<Object>}\n */\n async getMediaUsage(mediaId) {\n return this.get(`/library/usage/${mediaId}`);\n }\n\n /**\n * Tidy the library (remove unused/old revisions)\n * @returns {Promise<void>}\n */\n async tidyLibrary() {\n await this.post('/library/tidy');\n }\n\n // ── Playlist CRUD (#35) ────────────────────────────────────────────\n\n /**\n * List playlists\n * @param {Object} [filters] - Filters (playlistId, name, etc.)\n * @returns {Promise<Array>}\n */\n async listPlaylists(filters = {}) {\n return this._listRequest('/playlist', filters);\n }\n\n /**\n * Create a playlist\n * @param {string} name\n * @returns {Promise<Object>}\n */\n async createPlaylist(name) {\n return this.post('/playlist', { name });\n }\n\n /**\n * Get a single playlist by ID\n * @param {number} playlistId\n * @returns {Promise<Object>}\n */\n async getPlaylist(playlistId) {\n return this.get(`/playlist/${playlistId}`);\n }\n\n /**\n * Edit playlist properties\n * @param {number} playlistId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editPlaylist(playlistId, params) {\n return this.put(`/playlist/${playlistId}`, params);\n }\n\n /**\n * Delete a playlist\n * @param {number} playlistId\n * @returns {Promise<void>}\n */\n async deletePlaylist(playlistId) {\n await this.del(`/playlist/${playlistId}`);\n }\n\n /**\n * Reorder widgets in a playlist\n * @param {number} playlistId\n * @param {number[]} widgetIds - Ordered widget IDs\n * @returns {Promise<void>}\n */\n async reorderPlaylist(playlistId, widgetIds) {\n await this.ensureToken();\n const url = `${this.baseUrl}/api/playlist/order/${playlistId}`;\n const urlParams = new URLSearchParams();\n for (const id of widgetIds) {\n urlParams.append('widgets[]', String(id));\n }\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n if (!response.ok) {\n const text = await response.text();\n throw new CmsApiError('POST', `/playlist/order/${playlistId}`, response.status, text);\n }\n }\n\n /**\n * Copy a playlist\n * @param {number} playlistId\n * @returns {Promise<Object>} Copied playlist\n */\n async copyPlaylist(playlistId) {\n return this.post(`/playlist/copy/${playlistId}`);\n }\n\n // ── Widget Extras (#37) ────────────────────────────────────────────\n\n /**\n * Set transition for a widget\n * @param {number} widgetId\n * @param {string} type - Transition type (e.g. 'fly', 'fade')\n * @param {Object} [config] - Transition config (duration, direction)\n * @returns {Promise<Object>}\n */\n async setWidgetTransition(widgetId, type, config = {}) {\n return this.put(`/playlist/widget/transition/${widgetId}`, { type, ...config });\n }\n\n /**\n * Set audio for a widget\n * @param {number} widgetId\n * @param {Object} params - { mediaId, volume, loop }\n * @returns {Promise<Object>}\n */\n async setWidgetAudio(widgetId, params) {\n return this.put(`/playlist/widget/${widgetId}/audio`, params);\n }\n\n /**\n * Remove audio from a widget\n * @param {number} widgetId\n * @returns {Promise<void>}\n */\n async removeWidgetAudio(widgetId) {\n await this.del(`/playlist/widget/${widgetId}/audio`);\n }\n\n /**\n * Set expiry dates for a widget\n * @param {number} widgetId\n * @param {Object} params - { fromDt, toDt, deleteOnExpiry }\n * @returns {Promise<Object>}\n */\n async setWidgetExpiry(widgetId, params) {\n return this.put(`/playlist/widget/${widgetId}/expiry`, params);\n }\n\n // ── Template Save / Manage (#39) ───────────────────────────────────\n\n /**\n * Save a layout as a template\n * @param {number} layoutId\n * @param {Object} params - { name, description, includeWidgets }\n * @returns {Promise<Object>}\n */\n async saveAsTemplate(layoutId, params) {\n return this.post(`/template/${layoutId}`, params);\n }\n\n /**\n * Get a single template by ID\n * @param {number} templateId\n * @returns {Promise<Object>}\n */\n async getTemplate(templateId) {\n return this.get(`/template/${templateId}`);\n }\n\n /**\n * Delete a template\n * @param {number} templateId\n * @returns {Promise<void>}\n */\n async deleteTemplate(templateId) {\n await this.del(`/template/${templateId}`);\n }\n\n // ── Dataset CRUD (#28) ─────────────────────────────────────────────\n\n /**\n * List datasets\n * @param {Object} [filters] - Filters (dataSetId, dataSet)\n * @returns {Promise<Array>}\n */\n async listDatasets(filters = {}) {\n return this._listRequest('/dataset', filters);\n }\n\n /**\n * Create a dataset\n * @param {Object} params - { dataSet, description }\n * @returns {Promise<Object>}\n */\n async createDataset(params) {\n return this.post('/dataset', params);\n }\n\n /**\n * Edit a dataset\n * @param {number} dataSetId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editDataset(dataSetId, params) {\n return this.put(`/dataset/${dataSetId}`, params);\n }\n\n /**\n * Delete a dataset\n * @param {number} dataSetId\n * @returns {Promise<void>}\n */\n async deleteDataset(dataSetId) {\n await this.del(`/dataset/${dataSetId}`);\n }\n\n /**\n * List columns in a dataset\n * @param {number} dataSetId\n * @returns {Promise<Array>}\n */\n async listDatasetColumns(dataSetId) {\n return this._listRequest(`/dataset/${dataSetId}/column`);\n }\n\n /**\n * Create a column in a dataset\n * @param {number} dataSetId\n * @param {Object} params - { heading, dataTypeId, dataSetColumnTypeId, listContent, ... }\n * @returns {Promise<Object>}\n */\n async createDatasetColumn(dataSetId, params) {\n return this.post(`/dataset/${dataSetId}/column`, params);\n }\n\n /**\n * Edit a dataset column\n * @param {number} dataSetId\n * @param {number} columnId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editDatasetColumn(dataSetId, columnId, params) {\n return this.put(`/dataset/${dataSetId}/column/${columnId}`, params);\n }\n\n /**\n * Delete a dataset column\n * @param {number} dataSetId\n * @param {number} columnId\n * @returns {Promise<void>}\n */\n async deleteDatasetColumn(dataSetId, columnId) {\n await this.del(`/dataset/${dataSetId}/column/${columnId}`);\n }\n\n /**\n * List rows (data) in a dataset\n * @param {number} dataSetId\n * @param {Object} [filters] - Filters (page, length)\n * @returns {Promise<Array>}\n */\n async listDatasetData(dataSetId, filters = {}) {\n return this._listRequest(`/dataset/data/${dataSetId}`, filters);\n }\n\n /**\n * Add a row to a dataset\n * @param {number} dataSetId\n * @param {Object} rowData - Column heading → value pairs\n * @returns {Promise<Object>}\n */\n async addDatasetRow(dataSetId, rowData) {\n return this.post(`/dataset/data/${dataSetId}`, rowData);\n }\n\n /**\n * Edit a dataset row\n * @param {number} dataSetId\n * @param {number} rowId\n * @param {Object} rowData - Column heading → value pairs\n * @returns {Promise<Object>}\n */\n async editDatasetRow(dataSetId, rowId, rowData) {\n return this.put(`/dataset/data/${dataSetId}/${rowId}`, rowData);\n }\n\n /**\n * Delete a dataset row\n * @param {number} dataSetId\n * @param {number} rowId\n * @returns {Promise<void>}\n */\n async deleteDatasetRow(dataSetId, rowId) {\n await this.del(`/dataset/data/${dataSetId}/${rowId}`);\n }\n\n /**\n * Import CSV data into a dataset\n * @param {number} dataSetId\n * @param {FormData} formData - Must include CSV file\n * @returns {Promise<Object>}\n */\n async importDatasetCsv(dataSetId, formData) {\n return this.requestMultipart('POST', `/dataset/import/${dataSetId}`, formData);\n }\n\n /**\n * Clear all data from a dataset\n * @param {number} dataSetId\n * @returns {Promise<void>}\n */\n async clearDataset(dataSetId) {\n await this.del(`/dataset/data/${dataSetId}`);\n }\n\n // ── Notification CRUD (#29) ────────────────────────────────────────\n\n /**\n * List notifications\n * @param {Object} [filters] - Filters (notificationId, subject)\n * @returns {Promise<Array>}\n */\n async listNotifications(filters = {}) {\n return this._listRequest('/notification', filters);\n }\n\n /**\n * Create a notification\n * @param {Object} params - { subject, body, isEmail, isInterrupt, displayGroupIds, ... }\n * @returns {Promise<Object>}\n */\n async createNotification(params) {\n return this.post('/notification', params);\n }\n\n /**\n * Edit a notification\n * @param {number} notificationId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editNotification(notificationId, params) {\n return this.put(`/notification/${notificationId}`, params);\n }\n\n /**\n * Delete a notification\n * @param {number} notificationId\n * @returns {Promise<void>}\n */\n async deleteNotification(notificationId) {\n await this.del(`/notification/${notificationId}`);\n }\n\n // ── Folder CRUD (#30) ─────────────────────────────────────────────\n\n /**\n * List folders\n * @param {Object} [filters] - Filters (folderId, text)\n * @returns {Promise<Array>}\n */\n async listFolders(filters = {}) {\n return this._listRequest('/folder', filters);\n }\n\n /**\n * Create a folder\n * @param {Object} params - { text, parentId }\n * @returns {Promise<Object>}\n */\n async createFolder(params) {\n return this.post('/folder', params);\n }\n\n /**\n * Edit a folder\n * @param {number} folderId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editFolder(folderId, params) {\n return this.put(`/folder/${folderId}`, params);\n }\n\n /**\n * Delete a folder\n * @param {number} folderId\n * @returns {Promise<void>}\n */\n async deleteFolder(folderId) {\n await this.del(`/folder/${folderId}`);\n }\n\n // ── Tag CRUD + Entity Tagging (#31) ────────────────────────────────\n\n /**\n * List tags\n * @param {Object} [filters] - Filters (tagId, tag)\n * @returns {Promise<Array>}\n */\n async listTags(filters = {}) {\n return this._listRequest('/tag', filters);\n }\n\n /**\n * Create a tag\n * @param {Object} params - { tag }\n * @returns {Promise<Object>}\n */\n async createTag(params) {\n return this.post('/tag', params);\n }\n\n /**\n * Edit a tag\n * @param {number} tagId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editTag(tagId, params) {\n return this.put(`/tag/${tagId}`, params);\n }\n\n /**\n * Delete a tag\n * @param {number} tagId\n * @returns {Promise<void>}\n */\n async deleteTag(tagId) {\n await this.del(`/tag/${tagId}`);\n }\n\n /**\n * Tag an entity (layout, media, campaign, etc.)\n * @param {string} entity - Entity type (layout, media, campaign, displaygroup, playlist)\n * @param {number} id - Entity ID\n * @param {string[]} tags - Tag names\n * @returns {Promise<void>}\n */\n async tagEntity(entity, id, tags) {\n await this.post(`/${entity}/${id}/tag`, { tag: tags.join(',') });\n }\n\n /**\n * Remove tags from an entity\n * @param {string} entity - Entity type\n * @param {number} id - Entity ID\n * @param {string[]} tags - Tag names to remove\n * @returns {Promise<void>}\n */\n async untagEntity(entity, id, tags) {\n await this.post(`/${entity}/${id}/untag`, { tag: tags.join(',') });\n }\n\n // ── DisplayGroup Actions (#32) ─────────────────────────────────────\n\n /**\n * Change the layout on a display group (immediate override)\n * @param {number} displayGroupId\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async dgChangeLayout(displayGroupId, layoutId) {\n await this.post(`/displaygroup/${displayGroupId}/action/changeLayout`, { layoutId });\n }\n\n /**\n * Overlay a layout on a display group\n * @param {number} displayGroupId\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async dgOverlayLayout(displayGroupId, layoutId) {\n await this.post(`/displaygroup/${displayGroupId}/action/overlayLayout`, { layoutId });\n }\n\n /**\n * Revert a display group to its scheduled content\n * @param {number} displayGroupId\n * @returns {Promise<void>}\n */\n async dgRevertToSchedule(displayGroupId) {\n await this.post(`/displaygroup/${displayGroupId}/action/revertToSchedule`);\n }\n\n /**\n * Trigger immediate content collection on a display group\n * @param {number} displayGroupId\n * @returns {Promise<void>}\n */\n async dgCollectNow(displayGroupId) {\n await this.post(`/displaygroup/${displayGroupId}/action/collectNow`);\n }\n\n /**\n * Send a command to a display group\n * @param {number} displayGroupId\n * @param {number} commandId\n * @returns {Promise<void>}\n */\n async dgSendCommand(displayGroupId, commandId) {\n await this.post(`/displaygroup/${displayGroupId}/action/command`, { commandId });\n }\n\n /**\n * Edit display group properties\n * @param {number} displayGroupId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editDisplayGroup(displayGroupId, params) {\n return this.put(`/displaygroup/${displayGroupId}`, params);\n }\n}\n\n/**\n * Structured error for CMS API failures\n */\nexport class CmsApiError extends Error {\n constructor(method, path, status, detail) {\n super(`CMS API ${method} ${path} → ${status}: ${detail}`);\n this.name = 'CmsApiError';\n this.method = method;\n this.path = path;\n this.status = status;\n this.detail = detail;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n// @xiboplayer/utils - Shared utilities\nimport pkg from '../package.json' with { type: 'json' };\nexport const VERSION = pkg.version;\nexport { createLogger, setLogLevel, getLogLevel, isDebug, applyCmsLogLevel, mapCmsLogLevel, registerLogSink, unregisterLogSink, LOG_LEVELS } from './logger.js';\nexport { EventEmitter } from './event-emitter.js';\nimport { config as _config } from './config.js';\nexport { config, SHELL_ONLY_KEYS, extractPwaConfig, computeCmsId, warnPlatformMismatch } from './config.js';\nexport { fetchWithRetry } from './fetch-retry.js';\nexport { openIDB, queryByIndex, deleteByIds } from './idb.js';\nexport { CmsApiClient, CmsApiError } from './cms-api.js';\n\n/**\n * CMS Player API base path — all media, dependencies, and widgets are served\n * under this prefix.\n *\n * Default: '/player/api/v2' (standalone index.php endpoint).\n * Override: set `playerApiBase` in config.json / localStorage, or call\n * setPlayerApi('/new/path') before route registration (proxy).\n *\n * Browser: reads from config.data.playerApiBase at import time.\n * Node: call setPlayerApi() before createProxyApp().\n */\nconst DEFAULT_PLAYER_API = '/player/api/v2';\nlet _playerApi = _config.data?.playerApiBase || DEFAULT_PLAYER_API;\n\n/** Current Player API base path (no trailing slash). */\nexport let PLAYER_API = _playerApi;\n\n/** Override the Player API base path at runtime (call before route registration). */\nexport function setPlayerApi(base) {\n _playerApi = base.replace(/\\/+$/, '');\n PLAYER_API = _playerApi;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * FILE_TYPES — centralized download behavior per file type.\n *\n * Each type declares retry strategy, HEAD skip, and cache TTL.\n * Used by DownloadTask/FileDownload instead of ad-hoc isGetData checks.\n */\n\nexport const FILE_TYPES = {\n media: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n layout: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n dataset: { maxRetries: 4, retryDelayMs: 0,\n retryDelays: [15_000, 30_000, 60_000, 120_000],\n maxReenqueues: 5, reenqueueDelayMs: 60_000,\n skipHead: true, cacheTtl: 300 },\n static: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n};\n\nexport function getFileTypeConfig(type) {\n return FILE_TYPES[type] || FILE_TYPES.media;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * DownloadManager - Flat queue download orchestration\n *\n * Works in both browser and Service Worker contexts.\n * Handles download queue, concurrency control, parallel chunks, and MD5 verification.\n *\n * Architecture (flat queue):\n * - DownloadTask: Single HTTP fetch unit (one GET request — full file or one chunk)\n * - FileDownload: Orchestrator that creates DownloadTasks for a file (HEAD + chunks)\n * - DownloadQueue: Flat queue where every download unit competes equally for connection slots\n * - DownloadManager: Public facade\n *\n * BEFORE: Queue[File, File, File] → each File internally spawns N chunk fetches\n * AFTER: Queue[chunk, chunk, file, chunk, chunk, file, chunk] → flat, 1 fetch per slot\n *\n * This eliminates the two-layer concurrency problem where N files × M chunks per file\n * could exceed Chromium's 6-per-host connection limit, causing head-of-line blocking.\n *\n * Per-file chunk limit (maxChunksPerFile) prevents one large file from hogging all\n * connection slots, ensuring bandwidth is shared fairly and chunk 0 arrives fast.\n *\n * Usage:\n * const dm = new DownloadManager({ concurrency: 6, chunkSize: 50MB, chunksPerFile: 2 });\n * const file = dm.enqueue({ id, type, path, md5 });\n * const blob = await file.wait();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { getFileTypeConfig } from './file-types.js';\n\nconst log = createLogger('Download');\nconst DEFAULT_CONCURRENCY = 6; // Max concurrent HTTP connections (matches Chromium per-host limit)\nconst DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; // 50MB chunks\nconst DEFAULT_MAX_CHUNKS_PER_FILE = 3; // Max parallel chunk downloads per file\nconst CHUNK_THRESHOLD = 100 * 1024 * 1024; // Files > 100MB get chunked\nconst URGENT_CONCURRENCY = 2; // Slots when urgent chunk is active (bandwidth focus)\nconst FETCH_TIMEOUT_MS = 600_000; // 10 minutes — 100MB chunk at ~2 Mbps\nconst HEAD_TIMEOUT_MS = 15_000; // 15 seconds for HEAD requests\n\n/**\n * Infer Content-Type from file path extension.\n * Used when we skip HEAD (size already known from RequiredFiles).\n */\nfunction inferContentType(fileInfo) {\n const path = fileInfo.path || fileInfo.code || '';\n const ext = path.split('.').pop()?.split('?')[0]?.toLowerCase();\n const types = {\n mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg',\n png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',\n gif: 'image/gif', svg: 'image/svg+xml', webp: 'image/webp',\n css: 'text/css', js: 'application/javascript',\n ttf: 'font/ttf', otf: 'font/otf', woff: 'font/woff', woff2: 'font/woff2',\n xml: 'application/xml', xlf: 'application/xml',\n };\n return types[ext] || 'application/octet-stream';\n}\n\n// Priority levels — higher number = starts first\nexport const PRIORITY = { normal: 0, layout: 1, high: 2, urgent: 3 };\n\n/**\n * BARRIER sentinel — hard gate in the download queue.\n *\n * When processQueue() encounters a BARRIER:\n * - If tasks are still in-flight above it → STOP (slots stay empty)\n * - If running === 0 → remove barrier, continue with tasks below\n *\n * Used by LayoutQueueBuilder to separate critical chunks (chunk-0, chunk-last)\n * from remaining bulk chunks. Ensures video playback can start before all\n * chunks finish downloading.\n */\nexport const BARRIER = Symbol('BARRIER');\n\n/**\n * Compute the expiry of an AWS signed URL from X-Amz-Date + X-Amz-Expires.\n * X-Amz-Expires is a duration in seconds (not an absolute timestamp).\n * Returns the expiry as a Unix timestamp (seconds), or Infinity if not found.\n */\nfunction getUrlExpiry(url) {\n try {\n const u = new URL(url, 'http://localhost');\n const amzDate = u.searchParams.get('X-Amz-Date');\n const amzExpires = u.searchParams.get('X-Amz-Expires');\n if (amzDate && amzExpires) {\n // X-Amz-Date is ISO-like: 20240101T000000Z\n const dateStr = amzDate.replace(/(\\d{4})(\\d{2})(\\d{2})T(\\d{2})(\\d{2})(\\d{2})Z/, '$1-$2-$3T$4:$5:$6Z');\n const signedAt = new Date(dateStr).getTime() / 1000;\n if (isNaN(signedAt)) return Infinity;\n return signedAt + parseInt(amzExpires, 10);\n }\n return Infinity;\n } catch (_) {\n return Infinity;\n }\n}\n\n/**\n * Check if a signed URL has expired (or will expire within a grace period).\n * @param {string} url - Signed URL with X-Amz-Expires parameter\n * @param {number} graceSeconds - Seconds before actual expiry to consider it expired (default: 30)\n * @returns {boolean}\n */\nexport function isUrlExpired(url, graceSeconds = 30) {\n const expiry = getUrlExpiry(url);\n if (expiry === Infinity) return false;\n return (Date.now() / 1000) >= (expiry - graceSeconds);\n}\n\n\n/**\n * DownloadTask - Single HTTP fetch unit\n *\n * Handles exactly one HTTP request: either a full small file GET or a single Range GET\n * for one chunk of a larger file. Includes retry logic with exponential backoff.\n */\nexport class DownloadTask {\n constructor(fileInfo, options = {}) {\n this.fileInfo = fileInfo;\n this.chunkIndex = options.chunkIndex ?? null;\n this.rangeStart = options.rangeStart ?? null;\n this.rangeEnd = options.rangeEnd ?? null;\n this.state = 'pending';\n this.blob = null;\n this._parentFile = null;\n this._priority = PRIORITY.normal;\n this._typeConfig = getFileTypeConfig(fileInfo.type);\n }\n\n getUrl() {\n const url = this.fileInfo.path;\n if (isUrlExpired(url)) {\n throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);\n }\n return url;\n }\n\n async start() {\n this.state = 'downloading';\n const headers = {};\n if (this.rangeStart != null) {\n headers['Range'] = `bytes=${this.rangeStart}-${this.rangeEnd}`;\n }\n // Pass chunk metadata and MD5 via custom headers for cache-through proxy\n if (this.chunkIndex != null) {\n headers['X-Store-Chunk-Index'] = String(this.chunkIndex);\n if (this._parentFile) {\n headers['X-Store-Num-Chunks'] = String(this._parentFile.totalChunks);\n headers['X-Store-Chunk-Size'] = String(this._parentFile.options.chunkSize || 104857600);\n }\n }\n if (this.fileInfo.md5) {\n headers['X-Store-MD5'] = this.fileInfo.md5;\n }\n if (this.fileInfo.updateInterval) {\n headers['X-Cache-TTL'] = String(this.fileInfo.updateInterval);\n }\n if (this.fileInfo.cmsDownloadUrl) {\n headers['X-Cms-Download-Url'] = this.fileInfo.cmsDownloadUrl;\n }\n\n const maxRetries = this._typeConfig.maxRetries;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);\n try {\n const url = this.getUrl();\n const fetchOpts = { signal: ac.signal };\n if (Object.keys(headers).length > 0) fetchOpts.headers = headers;\n const response = await fetch(url, fetchOpts);\n\n if (!response.ok && response.status !== 206) {\n throw new Error(`Fetch failed: ${response.status}`);\n }\n\n this.blob = await response.blob();\n this.state = 'complete';\n return this.blob;\n\n } catch (error) {\n const msg = ac.signal.aborted ? `Timeout after ${FETCH_TIMEOUT_MS / 1000}s` : error.message;\n if (attempt < maxRetries) {\n const delay = this._typeConfig.retryDelays?.[attempt - 1]\n ?? this._typeConfig.retryDelayMs * attempt;\n const chunkLabel = this.chunkIndex != null ? ` chunk ${this.chunkIndex}` : '';\n log.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${chunkLabel} attempt ${attempt}/${maxRetries} failed: ${msg}. Retrying in ${delay / 1000}s...`);\n await new Promise(resolve => setTimeout(resolve, delay));\n } else {\n this.state = 'failed';\n throw ac.signal.aborted ? new Error(msg) : error;\n }\n } finally {\n clearTimeout(timer);\n }\n }\n }\n}\n\n/**\n * FileDownload - Orchestrates downloading a single file\n *\n * Does the HEAD request to determine file size, then:\n * - Small file (≤ 100MB): creates 1 DownloadTask for the full file\n * - Large file (> 100MB): creates N DownloadTasks, one per chunk\n *\n * All tasks are enqueued into the flat DownloadQueue where they compete\n * equally for HTTP connection slots with tasks from other files.\n *\n * Provides wait() that resolves when ALL tasks for this file complete.\n * Supports progressive caching via onChunkDownloaded callback.\n */\nexport class FileDownload {\n constructor(fileInfo, options = {}) {\n this.fileInfo = fileInfo;\n this.options = options;\n this.state = 'pending';\n this.tasks = [];\n this.completedChunks = 0;\n this.totalChunks = 0;\n this.totalBytes = 0;\n this.downloadedBytes = 0;\n this.onChunkDownloaded = null;\n this.skipChunks = fileInfo.skipChunks || new Set();\n this._contentType = 'application/octet-stream';\n this._chunkBlobs = new Map();\n this._runningCount = 0; // Currently running tasks for this file\n this._resolve = null;\n this._reject = null;\n this._promise = new Promise((res, rej) => {\n this._resolve = res;\n this._reject = rej;\n });\n this._promise.catch(() => {});\n }\n\n getUrl() {\n const url = this.fileInfo.path;\n if (isUrlExpired(url)) {\n throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);\n }\n return url;\n }\n\n wait() {\n return this._promise;\n }\n\n /**\n * Determine file size and create DownloadTasks.\n * Uses RequiredFiles size when available (instant, no network).\n * Falls back to HEAD request only when size is unknown.\n */\n async prepare(queue) {\n try {\n this.state = 'preparing';\n const { id, type, size } = this.fileInfo;\n log.info('[FileDownload] Starting:', `${type}/${id}`);\n\n // Use declared size from RequiredFiles — no HEAD needed for queue building\n this.totalBytes = (size && size > 0) ? parseInt(size) : 0;\n this._contentType = inferContentType(this.fileInfo);\n\n // Skip HEAD for types that declare skipHead (e.g. datasets — dynamic API endpoints).\n // These generate responses server-side; HEAD triggers the full handler for nothing\n // and may fail if the CMS cache isn't warm yet. They're always small, never chunked.\n const skipHead = getFileTypeConfig(this.fileInfo.type).skipHead;\n\n if (this.totalBytes === 0 && !skipHead) {\n // No size declared — HEAD fallback (rare: only for files without CMS size)\n const url = this.getUrl();\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), HEAD_TIMEOUT_MS);\n try {\n const head = await fetch(url, { method: 'HEAD', signal: ac.signal });\n if (head.ok) {\n this.totalBytes = parseInt(head.headers.get('Content-Length') || '0');\n this._contentType = head.headers.get('Content-Type') || this._contentType;\n }\n } finally {\n clearTimeout(timer);\n }\n }\n\n log.info('[FileDownload] File size:', (this.totalBytes / 1024 / 1024).toFixed(1), 'MB');\n\n const chunkSize = this.options.chunkSize || DEFAULT_CHUNK_SIZE;\n\n if (this.totalBytes > CHUNK_THRESHOLD) {\n const ranges = [];\n for (let start = 0; start < this.totalBytes; start += chunkSize) {\n ranges.push({\n start,\n end: Math.min(start + chunkSize - 1, this.totalBytes - 1),\n index: ranges.length\n });\n }\n this.totalChunks = ranges.length;\n\n const needed = ranges.filter(r => !this.skipChunks.has(r.index));\n const skippedCount = ranges.length - needed.length;\n\n for (const r of ranges) {\n if (this.skipChunks.has(r.index)) {\n this.downloadedBytes += (r.end - r.start + 1);\n }\n }\n\n if (needed.length === 0) {\n log.info('[FileDownload] All chunks already cached, nothing to download');\n this.state = 'complete';\n this._resolve(new Blob([], { type: this._contentType }));\n return;\n }\n\n if (skippedCount > 0) {\n log.info(`[FileDownload] Resuming: ${skippedCount} chunks cached, ${needed.length} to download`);\n }\n\n const isResume = skippedCount > 0;\n\n if (isResume) {\n const sorted = needed.sort((a, b) => a.index - b.index);\n for (const r of sorted) {\n const task = new DownloadTask(this.fileInfo, {\n chunkIndex: r.index, rangeStart: r.start, rangeEnd: r.end\n });\n task._parentFile = this;\n task._priority = PRIORITY.normal;\n this.tasks.push(task);\n }\n } else {\n for (const r of needed) {\n const task = new DownloadTask(this.fileInfo, {\n chunkIndex: r.index, rangeStart: r.start, rangeEnd: r.end\n });\n task._parentFile = this;\n task._priority = (r.index === 0 || r.index === ranges.length - 1) ? PRIORITY.high : PRIORITY.normal;\n this.tasks.push(task);\n }\n }\n\n const highCount = this.tasks.filter(t => t._priority >= PRIORITY.high).length;\n log.info(`[FileDownload] ${type}/${id}: ${this.tasks.length} chunks` +\n (highCount > 0 ? ` (${highCount} priority)` : '') +\n (isResume ? ' (resume)' : ''));\n\n } else {\n this.totalChunks = 1;\n const task = new DownloadTask(this.fileInfo, {});\n task._parentFile = this;\n this.tasks.push(task);\n }\n\n queue.enqueueChunkTasks(this.tasks);\n this.state = 'downloading';\n\n } catch (error) {\n log.error('[FileDownload] Prepare failed:', `${this.fileInfo.type}/${this.fileInfo.id}`, error);\n this.state = 'failed';\n this._reject(error);\n }\n }\n\n async onTaskComplete(task) {\n this.completedChunks++;\n this.downloadedBytes += task.blob.size;\n\n if (task.chunkIndex != null) {\n this._chunkBlobs.set(task.chunkIndex, task.blob);\n }\n\n if (this.options.onProgress) {\n this.options.onProgress(this.downloadedBytes, this.totalBytes);\n }\n\n // Fire progressive chunk callback\n if (this.onChunkDownloaded && task.chunkIndex != null) {\n try {\n await this.onChunkDownloaded(task.chunkIndex, task.blob, this.totalChunks);\n } catch (e) {\n log.warn('[FileDownload] onChunkDownloaded callback error:', e);\n }\n }\n\n if (this.completedChunks === this.tasks.length && this.state !== 'complete') {\n this.state = 'complete';\n const { type, id } = this.fileInfo;\n\n if (task.chunkIndex == null) {\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(${task.blob.size} bytes)`);\n this._resolve(task.blob);\n } else if (this.onChunkDownloaded) {\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(progressive, ${this.totalChunks} chunks)`);\n this._resolve(new Blob([], { type: this._contentType }));\n } else {\n const ordered = [];\n for (let i = 0; i < this.totalChunks; i++) {\n const blob = this._chunkBlobs.get(i);\n if (blob) ordered.push(blob);\n }\n const assembled = new Blob(ordered, { type: this._contentType });\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(${assembled.size} bytes, reassembled)`);\n this._resolve(assembled);\n }\n\n this._chunkBlobs.clear();\n }\n }\n\n onTaskFailed(task, error) {\n if (this.state === 'complete' || this.state === 'failed') return;\n\n // URL expiration is transient — drop this task, don't fail the file.\n // Already-downloaded chunks are safe in cache. Next collection cycle\n // provides fresh URLs and the resume logic (skipChunks) fills the gaps.\n if (error.message?.includes('URL expired')) {\n const chunkLabel = task.chunkIndex != null ? ` chunk ${task.chunkIndex}` : '';\n log.warn(`[FileDownload] URL expired, dropping${chunkLabel}:`, `${this.fileInfo.type}/${this.fileInfo.id}`);\n this.tasks = this.tasks.filter(t => t !== task);\n // If all remaining tasks completed, resolve as partial\n if (this.tasks.length === 0 || this.completedChunks >= this.tasks.length) {\n this.state = 'complete';\n this._urlExpired = true;\n this._resolve(new Blob([], { type: this._contentType }));\n }\n return;\n }\n\n log.error('[FileDownload] Failed:', `${this.fileInfo.type}/${this.fileInfo.id}`, error);\n this.state = 'failed';\n this._reject(error);\n }\n}\n\n/**\n * LayoutTaskBuilder — Smart builder that produces a sorted, barrier-embedded\n * task list for a single layout.\n *\n * Usage:\n * const builder = new LayoutTaskBuilder(queue);\n * builder.addFile(fileInfo);\n * const orderedTasks = await builder.build();\n * queue.enqueueOrderedTasks(orderedTasks);\n *\n * The builder runs HEAD requests (throttled), collects the resulting\n * DownloadTasks, sorts them optimally, and embeds BARRIERs between\n * critical chunks (chunk-0, chunk-last) and bulk chunks.\n *\n * Duck-typing: implements enqueueChunkTasks() so FileDownload.prepare()\n * works unchanged — it just collects tasks instead of processing them.\n */\nexport class LayoutTaskBuilder {\n constructor(queue) {\n this.queue = queue; // Main DownloadQueue (for dedup via active map)\n this._filesToPrepare = []; // FileDownloads needing HEAD requests\n this._tasks = []; // Collected DownloadTasks (from prepare callbacks)\n this._maxPreparing = 2; // HEAD request throttle\n }\n\n /**\n * Register a file. Uses queue.active for dedup/URL refresh.\n * Does NOT trigger prepare — that happens in build().\n */\n addFile(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.queue.active.has(key)) {\n const existing = this.queue.active.get(key);\n // URL refresh (same logic as queue.enqueue)\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.queue.chunkSize,\n calculateMD5: this.queue.calculateMD5,\n onProgress: this.queue.onProgress\n });\n\n this.queue.active.set(key, file);\n this._filesToPrepare.push(file);\n return file;\n }\n\n /**\n * Duck-type interface for FileDownload.prepare().\n * Collects tasks instead of processing them.\n */\n enqueueChunkTasks(tasks) {\n this._tasks.push(...tasks);\n }\n\n /**\n * Run all HEAD requests (throttled) and return sorted tasks with barriers.\n */\n async build() {\n await this._prepareAll();\n return this._sortWithBarriers();\n }\n\n async _prepareAll() {\n await new Promise((resolve) => {\n let running = 0;\n let idx = 0;\n const next = () => {\n while (running < this._maxPreparing && idx < this._filesToPrepare.length) {\n const file = this._filesToPrepare[idx++];\n running++;\n file.prepare(this).finally(() => {\n running--;\n if (idx >= this._filesToPrepare.length && running === 0) {\n resolve();\n } else {\n next();\n }\n });\n }\n };\n if (this._filesToPrepare.length === 0) resolve();\n else next();\n });\n }\n\n _sortWithBarriers() {\n const nonChunked = [];\n const chunk0s = [];\n const chunkLasts = [];\n const remaining = [];\n\n for (const t of this._tasks) {\n if (t.chunkIndex == null) {\n nonChunked.push(t);\n } else if (t.chunkIndex === 0) {\n chunk0s.push(t);\n } else {\n const total = t._parentFile?.totalChunks || 0;\n if (total > 1 && t.chunkIndex === total - 1) {\n chunkLasts.push(t);\n } else {\n remaining.push(t);\n }\n }\n }\n\n nonChunked.sort((a, b) => (a._parentFile?.totalBytes || 0) - (b._parentFile?.totalBytes || 0));\n remaining.sort((a, b) => a.chunkIndex - b.chunkIndex);\n\n // Build: small files + critical chunks → BARRIER → bulk chunks\n const result = [...nonChunked, ...chunk0s, ...chunkLasts];\n if (remaining.length > 0) {\n result.push(BARRIER, ...remaining);\n }\n return result;\n }\n}\n\n/**\n * DownloadQueue - Flat queue with per-file and global concurrency limits\n *\n * Global concurrency limit (e.g., 6) controls total HTTP connections.\n * Per-file chunk limit (e.g., 2) prevents one large file from hogging all\n * connections, ensuring bandwidth per chunk is high and chunk 0 arrives fast.\n * HEAD requests are throttled to avoid flooding browser connection pool.\n */\nexport class DownloadQueue {\n constructor(options = {}) {\n this.concurrency = options.concurrency || DEFAULT_CONCURRENCY;\n this.chunkSize = options.chunkSize || DEFAULT_CHUNK_SIZE;\n this.maxChunksPerFile = options.chunksPerFile || DEFAULT_MAX_CHUNKS_PER_FILE;\n this.calculateMD5 = options.calculateMD5;\n this.onProgress = options.onProgress;\n\n this.queue = []; // DownloadTask[] — flat queue of chunk/file tasks\n this.active = new Map(); // stableKey → FileDownload\n this._activeTasks = []; // DownloadTask[] — currently in-flight tasks\n this.running = 0;\n\n // HEAD request throttling: prevents prepare() from flooding browser connections\n this._prepareQueue = [];\n this._preparingCount = 0;\n this._maxPreparing = 2; // Max concurrent HEAD requests\n\n // When paused, processQueue() is a no-op (used during barrier setup)\n this.paused = false;\n\n // Track getData re-enqueue timers so clear() can cancel them\n this._reenqueueTimers = new Set();\n }\n\n static stableKey(fileInfo) {\n return `${fileInfo.type}/${fileInfo.id}`;\n }\n\n enqueue(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.active.has(key)) {\n const existing = this.active.get(key);\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n log.info('[DownloadQueue] Refreshing URL for', key);\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.chunkSize,\n calculateMD5: this.calculateMD5,\n onProgress: this.onProgress\n });\n\n this.active.set(key, file);\n log.info('[DownloadQueue] Enqueued:', key);\n\n // Throttled prepare: HEAD requests are limited to avoid flooding connections\n this._schedulePrepare(file);\n\n return file;\n }\n\n /**\n * Schedule a FileDownload's prepare() with throttling.\n * Only N HEAD requests run concurrently to preserve connections for data transfers.\n */\n _schedulePrepare(file) {\n this._prepareQueue.push(file);\n this._processPrepareQueue();\n }\n\n _processPrepareQueue() {\n while (this._preparingCount < this._maxPreparing && this._prepareQueue.length > 0) {\n const file = this._prepareQueue.shift();\n this._preparingCount++;\n file.prepare(this).finally(() => {\n this._preparingCount--;\n this._processPrepareQueue();\n });\n }\n }\n\n enqueueChunkTasks(tasks) {\n for (const task of tasks) {\n this.queue.push(task);\n }\n this._sortQueue();\n\n log.info(`[DownloadQueue] ${tasks.length} tasks added (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /**\n * Enqueue a pre-ordered list of tasks (with optional BARRIER sentinels).\n * Preserves insertion order — no sorting. Position = priority.\n *\n * Used by LayoutQueueBuilder to push the entire download queue in layout\n * playback order with barriers separating critical chunks from bulk.\n *\n * @param {Array<DownloadTask|Symbol>} items - Tasks and BARRIERs in order\n */\n enqueueOrderedTasks(items) {\n let taskCount = 0;\n let barrierCount = 0;\n for (const item of items) {\n if (item === BARRIER) {\n this.queue.push(BARRIER);\n barrierCount++;\n } else {\n this.queue.push(item);\n taskCount++;\n }\n }\n\n log.info(`[DownloadQueue] Ordered queue: ${taskCount} tasks, ${barrierCount} barriers (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /** Sort queue by priority (highest first), stable within same priority. */\n _sortQueue() {\n this.queue.sort((a, b) => b._priority - a._priority);\n }\n\n /**\n * Boost priority for files needed by the current/next layout.\n * @param {Array} fileIds - Media IDs needed by the layout\n * @param {number} priority - Priority level (default: PRIORITY.high)\n */\n prioritizeLayoutFiles(fileIds, priority = PRIORITY.high) {\n const idSet = new Set(fileIds.map(String));\n\n let boosted = 0;\n for (const t of this.queue) {\n const matchValue = t._parentFile?.fileInfo.saveAs || String(t._parentFile?.fileInfo.id);\n if (idSet.has(matchValue) && t._priority < priority) {\n t._priority = priority;\n boosted++;\n }\n }\n for (const t of this._activeTasks) {\n const matchValue = t._parentFile?.fileInfo.saveAs || String(t._parentFile?.fileInfo.id);\n if (idSet.has(matchValue) && t._priority < priority) {\n t._priority = priority;\n }\n }\n this._sortQueue();\n\n log.info('[DownloadQueue] Layout files prioritized:', idSet.size, 'files,', boosted, 'tasks boosted to', priority);\n }\n\n /**\n * Emergency priority for a specific streaming chunk.\n * Called by the Service Worker when a video is stalled waiting for chunk N.\n * Sets urgent priority → queue re-sorts → processQueue() limits concurrency.\n */\n urgentChunk(fileType, fileId, chunkIndex) {\n const key = `${fileType}/${fileId}`;\n const file = this.active.get(key);\n\n if (!file) {\n log.info('[DownloadQueue] urgentChunk: file not active:', key, 'chunk', chunkIndex);\n return false;\n }\n\n // Already in-flight — nothing to do\n const isActive = this._activeTasks.some(\n t => t._parentFile === file && t.chunkIndex === chunkIndex && t.state === 'downloading'\n );\n if (isActive) {\n // Mark the in-flight task as urgent so processQueue() limits concurrency\n const activeTask = this._activeTasks.find(\n t => t._parentFile === file && t.chunkIndex === chunkIndex\n );\n if (activeTask && activeTask._priority < PRIORITY.urgent) {\n activeTask._priority = PRIORITY.urgent;\n log.info(`[DownloadQueue] URGENT: ${key} chunk ${chunkIndex} (already in-flight, limiting slots)`);\n // Don't call processQueue() — can't stop in-flight tasks, but next\n // processQueue() call (when any task completes) will see hasUrgent\n // and limit new starts to URGENT_CONCURRENCY.\n return true;\n }\n log.info('[DownloadQueue] urgentChunk: already urgent:', key, 'chunk', chunkIndex);\n return false;\n }\n\n // Find task in queue (may be past a barrier)\n const idx = this.queue.findIndex(\n t => t !== BARRIER && t._parentFile === file && t.chunkIndex === chunkIndex\n );\n\n if (idx === -1) {\n log.info('[DownloadQueue] urgentChunk: chunk not in queue:', key, 'chunk', chunkIndex);\n return false;\n }\n\n const task = this.queue.splice(idx, 1)[0];\n task._priority = PRIORITY.urgent;\n // Move to front of queue (past any barriers)\n this.queue.unshift(task);\n\n log.info(`[DownloadQueue] URGENT: ${key} chunk ${chunkIndex} (moved to front)`);\n this.processQueue();\n return true;\n }\n\n /**\n * Process queue — barrier-aware loop.\n *\n * Supports two modes:\n * 1. Priority-sorted (legacy): queue sorted by priority, urgent reduces concurrency\n * 2. Barrier-ordered: queue contains BARRIER sentinels that act as hard gates\n *\n * BARRIER behavior:\n * - When processQueue() hits a BARRIER and running > 0 → STOP (slots stay empty)\n * - When running === 0 → remove barrier, continue with tasks below\n * - Tasks are never reordered past a BARRIER (except urgentChunk which bypasses)\n *\n * Urgent mode: when any task has PRIORITY.urgent, concurrency drops to\n * URGENT_CONCURRENCY so the stalled chunk gets maximum bandwidth.\n */\n processQueue() {\n if (this.paused) return;\n\n // Determine effective concurrency and minimum priority to start\n const hasUrgent = this.queue.some(t => t !== BARRIER && t._priority >= PRIORITY.urgent) ||\n this._activeTasks?.some(t => t._priority >= PRIORITY.urgent && t.state === 'downloading');\n const maxSlots = hasUrgent ? URGENT_CONCURRENCY : this.concurrency;\n const minPriority = hasUrgent ? PRIORITY.urgent : 0; // Urgent = only urgent tasks run\n\n // Fill slots from front of queue\n while (this.running < maxSlots && this.queue.length > 0) {\n const next = this.queue[0];\n\n // Hit a BARRIER — hard gate\n if (next === BARRIER) {\n if (this.running > 0) {\n break; // In-flight tasks still running — slots stay empty\n }\n // All above-barrier tasks done → raise barrier, continue\n this.queue.shift();\n continue;\n }\n\n // Per-file limit: skip to next eligible task (but don't cross barrier)\n if (next._priority < minPriority || !this._canStartTask(next)) {\n let found = false;\n for (let i = 1; i < this.queue.length; i++) {\n if (this.queue[i] === BARRIER) break; // Don't look past barrier\n const task = this.queue[i];\n if (task._priority >= minPriority && this._canStartTask(task)) {\n this.queue.splice(i, 1);\n this._startTask(task);\n found = true;\n break;\n }\n }\n if (!found) break;\n continue;\n }\n\n this.queue.shift();\n this._startTask(next);\n }\n\n if (this.queue.length === 0 && this.running === 0) {\n log.info('[DownloadQueue] All downloads complete');\n }\n }\n\n /**\n * Per-file concurrency check. Priority sorting decides order,\n * this just prevents one file from hogging all connections.\n */\n _canStartTask(task) {\n return task._parentFile._runningCount < this.maxChunksPerFile;\n }\n\n _startTask(task) {\n this.running++;\n task._parentFile._runningCount++;\n this._activeTasks.push(task);\n const key = `${task.fileInfo.type}/${task.fileInfo.id}`;\n const chunkLabel = task.chunkIndex != null ? ` chunk ${task.chunkIndex}` : '';\n log.info(`[DownloadQueue] Starting: ${key}${chunkLabel} (${this.running}/${this.concurrency} active)`);\n\n task.start()\n .then(() => {\n this.running--;\n task._parentFile._runningCount--;\n this._activeTasks = this._activeTasks.filter(t => t !== task);\n log.info(`[DownloadQueue] Fetched: ${key}${chunkLabel} (${this.running} active, ${this.queue.length} pending)`);\n this.processQueue();\n return task._parentFile.onTaskComplete(task);\n })\n .catch(err => {\n this.running--;\n task._parentFile._runningCount--;\n this._activeTasks = this._activeTasks.filter(t => t !== task);\n\n // Re-enqueueable types (e.g. datasets): defer re-enqueue instead of permanent failure.\n // CMS \"cache not ready\" resolves when the XTR task runs (30-120s).\n const { maxReenqueues, reenqueueDelayMs } = task._typeConfig;\n if (maxReenqueues > 0) {\n task._reenqueueCount = (task._reenqueueCount || 0) + 1;\n if (task._reenqueueCount > maxReenqueues) {\n log.error(`[DownloadQueue] ${key} exceeded ${maxReenqueues} re-enqueues, failing permanently`);\n this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n return;\n }\n log.warn(`[DownloadQueue] ${key} failed all retries (attempt ${task._reenqueueCount}/${maxReenqueues}), scheduling re-enqueue in ${reenqueueDelayMs / 1000}s`);\n const timerId = setTimeout(() => {\n this._reenqueueTimers.delete(timerId);\n task.state = 'pending';\n task._parentFile.state = 'downloading';\n this.queue.push(task);\n log.info(`[DownloadQueue] ${key} re-enqueued for retry`);\n this.processQueue();\n }, reenqueueDelayMs);\n this._reenqueueTimers.add(timerId);\n this.processQueue();\n return;\n }\n\n this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n });\n }\n\n removeCompleted(key) {\n const file = this.active.get(key);\n if (file && (file.state === 'complete' || file.state === 'failed')) {\n this.queue = this.queue.filter(t => t === BARRIER || t._parentFile !== file);\n this.active.delete(key);\n }\n }\n\n getTask(key) {\n return this.active.get(key) || null;\n }\n\n getProgress() {\n const progress = {};\n for (const [key, file] of this.active.entries()) {\n // Skip completed/failed — they stay in active until removeCompleted() runs\n if (file.state === 'complete' || file.state === 'failed') continue;\n progress[key] = {\n downloaded: file.downloadedBytes,\n total: file.totalBytes,\n percent: file.totalBytes > 0 ? (file.downloadedBytes / file.totalBytes * 100).toFixed(1) : 0,\n state: file.state\n };\n }\n return progress;\n }\n\n clear() {\n this.queue = [];\n this.active.clear();\n this.running = 0;\n this._prepareQueue = [];\n this._preparingCount = 0;\n // Cancel any pending getData re-enqueue timers\n for (const id of this._reenqueueTimers) clearTimeout(id);\n this._reenqueueTimers.clear();\n }\n}\n\n/**\n * DownloadManager - Main API\n */\nexport class DownloadManager {\n constructor(options = {}) {\n this.queue = new DownloadQueue(options);\n }\n\n enqueue(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n getTask(key) {\n return this.queue.getTask(key);\n }\n\n getProgress() {\n return this.queue.getProgress();\n }\n\n prioritizeLayoutFiles(fileIds, priority) {\n this.queue.prioritizeLayoutFiles(fileIds, priority);\n this.queue.processQueue();\n }\n\n urgentChunk(fileType, fileId, chunkIndex) {\n return this.queue.urgentChunk(fileType, fileId, chunkIndex);\n }\n\n createTaskBuilder() {\n return new LayoutTaskBuilder(this.queue);\n }\n\n enqueueOrderedTasks(tasks) {\n this.queue.enqueueOrderedTasks(tasks);\n }\n\n removeCompleted(key) {\n this.queue.removeCompleted(key);\n }\n\n get running() {\n return this.queue.running;\n }\n\n get queued() {\n return this.queue.queue.length;\n }\n\n clear() {\n this.queue.clear();\n }\n}\n","{\n \"name\": \"@xiboplayer/cache\",\n \"version\": \"0.7.21\",\n \"description\": \"Offline caching and download management with parallel chunk downloads\",\n \"type\": \"module\",\n \"main\": \"./src/index.js\",\n \"types\": \"./src/index.d.ts\",\n \"exports\": {\n \".\": \"./src/index.js\",\n \"./cache\": \"./src/cache.js\",\n \"./store-client\": \"./src/store-client.js\",\n \"./download-manager\": \"./src/download-manager.js\",\n \"./cache-analyzer\": \"./src/cache-analyzer.js\",\n \"./widget-html\": \"./src/widget-html.js\"\n },\n \"scripts\": {\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\"\n },\n \"dependencies\": {\n \"@xiboplayer/utils\": \"workspace:*\",\n \"spark-md5\": \"^3.0.2\"\n },\n \"devDependencies\": {\n \"jsdom\": \"^29.0.2\",\n \"vitest\": \"^4.1.2\"\n },\n \"keywords\": [\n \"xibo\",\n \"digital-signage\",\n \"cache\",\n \"offline\",\n \"download\",\n \"indexeddb\"\n ],\n \"author\": \"Pau Aliagas <linuxnow@gmail.com>\",\n \"license\": \"AGPL-3.0-or-later\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/xibo-players/xiboplayer.git\",\n \"directory\": \"packages/cache\"\n },\n \"homepage\": \"https://xiboplayer.org\"\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CacheManager - Dependant tracking and cache lifecycle\n *\n * After the storage unification, all downloads and file retrieval go through\n * the proxy's ContentStore (via StoreClient/DownloadClient). This class retains:\n * - Dependant tracking (which layouts reference which media)\n * - Cache key generation\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\n\nexport class CacheManager {\n constructor() {\n // Dependants: mediaId → Set<layoutId> — tracks which layouts use each media file\n this.dependants = new Map();\n }\n\n /**\n * Track that a media file is used by a layout (dependant)\n * @param {string|number} mediaId\n * @param {string|number} layoutId\n */\n addDependant(mediaId, layoutId) {\n const key = String(mediaId);\n if (!this.dependants.has(key)) {\n this.dependants.set(key, new Set());\n }\n this.dependants.get(key).add(String(layoutId));\n }\n\n /**\n * Remove a layout from all dependant sets (layout removed from schedule)\n * @param {string|number} layoutId\n * @returns {string[]} Media IDs that are now orphaned (no layouts reference them)\n */\n removeLayoutDependants(layoutId) {\n const lid = String(layoutId);\n const orphaned = [];\n\n for (const [mediaId, layouts] of this.dependants) {\n layouts.delete(lid);\n if (layouts.size === 0) {\n this.dependants.delete(mediaId);\n orphaned.push(mediaId);\n }\n }\n\n if (orphaned.length > 0) {\n log.info(`${orphaned.length} media files orphaned after layout ${layoutId} removed:`, orphaned);\n }\n return orphaned;\n }\n\n /**\n * Check if a media file is still referenced by any layout\n * @param {string|number} mediaId\n * @returns {boolean}\n */\n isMediaReferenced(mediaId) {\n const layouts = this.dependants.get(String(mediaId));\n return layouts ? layouts.size > 0 : false;\n }\n\n /**\n * Clear all cached files via proxy\n */\n async clearAll() {\n this.dependants.clear();\n }\n}\n\nexport const cacheManager = new CacheManager();\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * StoreClient — Pure REST client for ContentStore\n *\n * Communicates with the proxy's /store/* endpoints via fetch().\n * No Service Worker dependency — works immediately after construction.\n *\n * Usage:\n * const store = new StoreClient();\n * const exists = await store.has('media', '123');\n * const blob = await store.get('media', '123');\n * await store.put('widget', 'layout/1/region/2/media/3', htmlBlob, 'text/html');\n * await store.remove([{ type: 'media', id: '456' }]);\n * const files = await store.list();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('StoreClient');\n\nexport class StoreClient {\n /**\n * Check if a file exists in the store.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @returns {Promise<boolean>}\n */\n async has(type, id) {\n try {\n const response = await fetch(`/store/${type}/${id}`, { method: 'HEAD' });\n if (response.status === 204) return false; // Not in store (no console error)\n if (response.status === 200) {\n // Incomplete chunked files return 200 with X-Store-Complete: false\n return response.headers.get('X-Store-Complete') !== 'false';\n }\n if (response.status === 404) return false;\n // Non-404 HTTP errors (500, 502, etc.) indicate proxy/store problems\n const err = new Error(`Store error: ${response.status}`);\n err.status = response.status;\n log.warn(`has(${type}/${id}): unexpected status ${response.status}`);\n throw err;\n } catch (error) {\n // Re-throw errors that are not simple network failures swallowed above\n // (includes HTTP errors we threw, AbortError, TypeError from fetch)\n if (error.status || error.name === 'AbortError' || error.name === 'TimeoutError') {\n throw error;\n }\n // Network errors (proxy unreachable) — log and re-throw so callers\n // can distinguish from \"not cached\" (which returns false)\n log.warn(`has(${type}/${id}): network error — ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Get a file from the store as a Blob.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @returns {Promise<Blob|null>}\n */\n async get(type, id) {\n try {\n const response = await fetch(`/store/${type}/${id}`);\n if (response.status === 204 || response.status === 404) {\n response.body?.cancel();\n return null;\n }\n if (!response.ok) {\n response.body?.cancel();\n throw new Error(`Failed to get file: ${response.status}`);\n }\n return await response.blob();\n } catch (error) {\n log.error('get error:', error.message);\n return null;\n }\n }\n\n /**\n * Store a file in the ContentStore.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @param {Blob|ArrayBuffer|string} body - Content to store\n * @param {string} [contentType='application/octet-stream'] - MIME type\n * @returns {Promise<boolean>} true if stored successfully\n */\n async put(type, id, body, contentType = 'application/octet-stream') {\n try {\n const response = await fetch(`/store/${type}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': contentType },\n body,\n });\n response.body?.cancel();\n return response.ok;\n } catch (error) {\n log.error('put error:', error.message);\n return false;\n }\n }\n\n /**\n * Delete files from the store.\n * @param {Array<{type: string, id: string}>} files - Files to delete\n * @returns {Promise<{deleted: number, total: number}>}\n */\n async remove(files) {\n try {\n const response = await fetch('/store/delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files }),\n });\n const result = await response.json();\n return { deleted: result.deleted || 0, total: result.total || files.length };\n } catch (error) {\n log.error('remove error:', error.message);\n return { deleted: 0, total: files.length };\n }\n }\n\n /**\n * List all files in the store.\n * @returns {Promise<Array<{id: string, type: string, size: number}>>}\n */\n async list() {\n try {\n const response = await fetch('/store/list');\n const data = await response.json();\n return data.files || [];\n } catch (error) {\n log.error('list error:', error.message);\n return [];\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CacheAnalyzer - Stale media detection and storage health monitoring\n *\n * Compares cached files against RequiredFiles from the CMS to identify\n * orphaned media that is no longer needed. Logs a summary every collection\n * cycle. Only evicts when storage pressure exceeds a configurable threshold.\n *\n * Works entirely through StoreClient (REST to proxy) — no IndexedDB,\n * no direct Cache API access.\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('CacheAnalyzer');\n\n/**\n * Format bytes into human-readable string (e.g. 1.2 GB, 350 MB)\n */\nfunction formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n if (!Number.isFinite(bytes)) return '∞';\n const units = ['B', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(1024));\n const value = bytes / 1024 ** i;\n return `${value.toFixed(i > 0 ? 1 : 0)} ${units[i]}`;\n}\n\nexport class CacheAnalyzer {\n /**\n * @param {import('./store-client.js').StoreClient} cache - StoreClient instance\n * @param {object} [options]\n * @param {number} [options.threshold=80] - Storage usage % above which eviction triggers\n */\n constructor(cache, { threshold = 80 } = {}) {\n this.cache = cache;\n this.threshold = threshold;\n }\n\n /**\n * Analyze cache health by comparing cached files against required files.\n *\n * @param {Array<{id: string, type: string}>} requiredFiles - Current RequiredFiles from CMS\n * @returns {Promise<object>} Analysis report\n */\n async analyze(requiredFiles) {\n const cachedFiles = await this.cache.list();\n const storage = await this._getStorageEstimate();\n\n // Build set of required file IDs (as strings for consistent comparison)\n const requiredIds = new Set(requiredFiles.map(f => String(f.id)));\n\n // Categorize cached files\n const required = [];\n const orphaned = [];\n\n for (const file of cachedFiles) {\n if (requiredIds.has(String(file.id))) {\n required.push(file);\n } else if (file.type === 'widget') {\n // Widget HTML IDs are \"layoutId/regionId/widgetId\" — check parent layout\n const parentLayoutId = String(file.id).split('/')[0];\n if (requiredIds.has(parentLayoutId)) {\n required.push(file);\n } else {\n orphaned.push(file);\n }\n } else if (file.type === 'static') {\n // Static files (bundle.min.js, fonts.css, fonts, images) are shared widget\n // dependencies — never orphan them, they're referenced from widget HTML\n required.push(file);\n } else {\n orphaned.push(file);\n }\n }\n\n // Sort orphaned by cachedAt ascending (oldest first — evict these first)\n orphaned.sort((a, b) => (a.cachedAt || 0) - (b.cachedAt || 0));\n\n const orphanedSize = orphaned.reduce((sum, f) => sum + (f.size || 0), 0);\n\n const report = {\n timestamp: Date.now(),\n storage: {\n usage: storage.usage,\n quota: storage.quota,\n percent: storage.quota > 0 ? Math.round((storage.usage / storage.quota) * 100) : 0,\n },\n files: {\n required: required.length,\n orphaned: orphaned.length,\n total: cachedFiles.length,\n },\n orphaned: orphaned.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n })),\n orphanedSize,\n evicted: [],\n threshold: this.threshold,\n };\n\n // Log summary\n log.info(`Storage: ${formatBytes(storage.usage)} / ${formatBytes(storage.quota)} (${report.storage.percent}%)`);\n log.info(`Cache: ${required.length} required, ${orphaned.length} orphaned (${formatBytes(orphanedSize)} reclaimable)`);\n\n if (orphaned.length > 0) {\n for (const f of orphaned) {\n const age = Date.now() - (f.cachedAt || 0);\n const days = Math.floor(age / 86400000);\n const hours = Math.floor((age % 86400000) / 3600000);\n const ageStr = days > 0 ? `${days}d ago` : `${hours}h ago`;\n log.info(` Orphaned: ${f.type}/${f.id} (${formatBytes(f.size || 0)}, cached ${ageStr})`);\n }\n }\n\n // Evict only when storage exceeds threshold\n if (report.storage.percent > this.threshold && orphaned.length > 0) {\n log.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);\n const targetBytes = storage.usage - (storage.quota * this.threshold / 100);\n report.evicted = await this._evict(orphaned, targetBytes);\n } else {\n log.info(`No eviction needed (threshold: ${this.threshold}%)`);\n }\n\n return report;\n }\n\n /**\n * Get storage estimate from the browser.\n * Falls back to { usage: 0, quota: Infinity } in environments without the API.\n */\n async _getStorageEstimate() {\n try {\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n const { usage, quota } = await navigator.storage.estimate();\n return { usage: usage || 0, quota: quota || Infinity };\n }\n } catch (e) {\n log.warn('Storage estimate unavailable:', e.message);\n }\n return { usage: 0, quota: Infinity };\n }\n\n /**\n * Evict orphaned files (oldest first) until targetBytes are freed.\n * Delegates deletion to StoreClient.remove() which routes to proxy.\n *\n * @param {Array} orphanedFiles - Files to evict, sorted oldest-first\n * @param {number} targetBytes - Bytes to free\n * @returns {Promise<Array>} Evicted file records\n */\n async _evict(orphanedFiles, targetBytes) {\n const toEvict = [];\n let plannedBytes = 0;\n\n for (const file of orphanedFiles) {\n if (plannedBytes >= targetBytes) break;\n toEvict.push(file);\n plannedBytes += file.size || 0;\n }\n\n if (toEvict.length === 0) return [];\n\n try {\n const filesToDelete = toEvict.map(f => ({ type: f.type, id: f.id }));\n await this.cache.remove(filesToDelete);\n\n for (const f of toEvict) {\n log.info(` Evicted: ${f.type}/${f.id} (${formatBytes(f.size || 0)})`);\n }\n log.info(`Evicted ${toEvict.length} files, freed ${formatBytes(plannedBytes)}`);\n } catch (err) {\n log.warn('Eviction failed:', err.message);\n return [];\n }\n\n return toEvict.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n }));\n }\n}\n\nexport { formatBytes };\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Widget HTML processing — preprocesses widget HTML and stores via REST\n *\n * Handles:\n * - <base> tag injection for relative path resolution (CMS mirror paths)\n * - Interactive Control hostAddress rewriting\n * - CSS object-position fix for CMS template alignment\n *\n * URL rewriting is no longer needed — the CMS serves CSS with relative paths\n * (${PLAYER_API}/dependencies/font.otf), and the <base> tag resolves widget\n * media references via mirror routes. Zero translation, zero regex.\n *\n * Runs on the main thread (needs window.location for URL construction).\n * Stores content via PUT /store/... — no Cache API needed.\n */\n\nimport { createLogger, PLAYER_API } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\n\n// Dynamic base path for multi-variant deployment (pwa, pwa-xmds, pwa-xlr)\nconst BASE = (typeof window !== 'undefined')\n ? window.location.pathname.replace(/\\/[^/]*$/, '').replace(/\\/$/, '') || '/player/pwa'\n : '/player/pwa';\n\n/**\n * Store widget HTML in ContentStore for iframe loading.\n * Stored at mirror path ${PLAYER_API}/widgets/{L}/{R}/{M} — same URL the\n * CMS serves from, so iframes load directly from Express mirror routes.\n *\n * @param {string} layoutId - Layout ID\n * @param {string} regionId - Region ID\n * @param {string} mediaId - Media ID\n * @param {string} html - Widget HTML content\n * @returns {Promise<string>} Cache key URL (absolute path for iframe src)\n */\nexport async function cacheWidgetHtml(layoutId, regionId, mediaId, html) {\n const cacheKey = `${PLAYER_API}/widgets/${layoutId}/${regionId}/${mediaId}`;\n\n // Inject <base> tag — resolves relative media refs (e.g. \"42\") to mirror route\n const baseTag = `<base href=\"${PLAYER_API}/media/file/\">`;\n let modifiedHtml = html;\n\n // Insert base tag after <head> opening tag (skip if already present)\n if (!html.includes('<base ')) {\n if (html.includes('<head>')) {\n modifiedHtml = html.replace('<head>', '<head>' + baseTag);\n } else if (html.includes('<HEAD>')) {\n modifiedHtml = html.replace('<HEAD>', '<HEAD>' + baseTag);\n } else {\n modifiedHtml = baseTag + html;\n }\n }\n\n // Inject CSS default for object-position to suppress CMS template warning\n const cssFixTag = '<style>img,video{object-position:center center}</style>';\n if (!modifiedHtml.includes('object-position:center center')) {\n if (modifiedHtml.includes('</head>')) {\n modifiedHtml = modifiedHtml.replace('</head>', cssFixTag + '</head>');\n } else if (modifiedHtml.includes('</HEAD>')) {\n modifiedHtml = modifiedHtml.replace('</HEAD>', cssFixTag + '</HEAD>');\n }\n }\n\n // Replace CMS placeholders left for \"client-side SDK handling\"\n modifiedHtml = modifiedHtml.replace(/\\[\\[ViewPortWidth]]/g, 'device-width');\n\n // Route HLS streams through local proxy (adds CORS headers, rewrites segments)\n modifiedHtml = modifiedHtml.replace(\n /https?:\\/\\/[^\\s\"')<]+\\.m3u8\\b/gi,\n (url) => '/stream-proxy?url=' + encodeURIComponent(url)\n );\n\n // Rewrite dependency URLs to absolute local paths. CMS SOAP GetResource sends\n // bare filenames (e.g. src=\"bundle.min.js\") which resolve against <base> to the\n // wrong /media/file/ path. Normalize all dependency references to absolute paths.\n const depsPattern = new RegExp(\n `https?://[^\"'\\\\s)]+?(${PLAYER_API.replace(/\\//g, '\\\\/')}/dependencies/[^\"'\\\\s?)]+)(\\\\?[^\"'\\\\s)]*)?`,\n 'g'\n );\n modifiedHtml = modifiedHtml.replace(depsPattern, (_, path) => path);\n modifiedHtml = modifiedHtml.replace(\n /(<(?:script|link)\\b[^>]*(?:src|href)=\")(?!\\/|https?:\\/\\/)(bundle\\.min\\.js|fonts\\.css)(\")/g,\n `$1${PLAYER_API}/dependencies/$2$3`\n );\n\n // Inject xiboICTargetId — XIC library reads this global before its IIFE runs\n // to set _lib.targetId, which is included in every IC HTTP request as {id: ...}\n if (!modifiedHtml.includes('xiboICTargetId')) {\n const targetIdScript = `<script>var xiboICTargetId = '${mediaId}';</script>`;\n if (modifiedHtml.includes(baseTag)) {\n modifiedHtml = modifiedHtml.replace(baseTag, baseTag + targetIdScript);\n } else if (modifiedHtml.includes('<head>')) {\n modifiedHtml = modifiedHtml.replace('<head>', '<head>' + targetIdScript);\n } else {\n modifiedHtml = targetIdScript + modifiedHtml;\n }\n }\n\n // Rewrite Interactive Control hostAddress to SW-interceptable path\n modifiedHtml = modifiedHtml.replace(\n /hostAddress\\s*:\\s*[\"']https?:\\/\\/[^\"']+[\"']/g,\n `hostAddress: \"${BASE}/ic\"`\n );\n\n log.info('Injected base tag in widget HTML');\n\n // Store widget HTML — deps are already downloaded by the pipeline\n const putResp = await fetch(`/store${PLAYER_API}/widgets/${layoutId}/${regionId}/${mediaId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\n body: modifiedHtml,\n });\n putResp.body?.cancel();\n log.info(`Stored widget HTML at ${cacheKey} (${modifiedHtml.length} bytes)`);\n\n return { cacheKey, html: modifiedHtml };\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n// @xiboplayer/cache - Offline caching and downloads\nimport pkg from '../package.json' with { type: 'json' };\nexport const VERSION = pkg.version;\nexport { CacheManager, cacheManager } from './cache.js';\nexport { StoreClient } from './store-client.js';\nexport { DownloadManager, FileDownload, LayoutTaskBuilder, BARRIER, isUrlExpired } from './download-manager.js';\nexport { CacheAnalyzer } from './cache-analyzer.js';\nexport { cacheWidgetHtml } from './widget-html.js';\nexport { FILE_TYPES, getFileTypeConfig } from './file-types.js';\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Service Worker Utility Functions\n * Shared helpers to eliminate code duplication and improve maintainability\n */\n\n/**\n * Dynamic base path derived from the Service Worker's registration scope.\n * Allows the same build to serve /player/pwa/, /player/pwa-xmds/, /player/pwa-xlr/.\n */\nexport const BASE = (() => {\n if (typeof self !== 'undefined' && self.registration?.scope) {\n return new URL(self.registration.scope).pathname.replace(/\\/$/, '');\n }\n return '/player/pwa'; // fallback\n})();\n\n/**\n * Format byte size to human-readable string\n * @param {number} bytes - Size in bytes\n * @param {number} decimals - Decimal places (default: 1)\n * @returns {string} Formatted size (e.g., \"1.5 MB\", \"512.0 KB\")\n */\nexport function formatBytes(bytes, decimals = 1) {\n if (bytes === 0) return '0 Bytes';\n if (bytes < 1024) return `${bytes} Bytes`;\n\n const kb = bytes / 1024;\n if (kb < 1024) return `${kb.toFixed(decimals)} KB`;\n\n const mb = kb / 1024;\n if (mb < 1024) return `${mb.toFixed(decimals)} MB`;\n\n const gb = mb / 1024;\n return `${gb.toFixed(decimals)} GB`;\n}\n\n/**\n * Parse HTTP Range header\n * @param {string} rangeHeader - Range header value (e.g., \"bytes=0-1000\")\n * @param {number} totalSize - Total file size\n * @returns {{ start: number, end: number }} Byte range\n */\nexport function parseRangeHeader(rangeHeader, totalSize) {\n const parts = rangeHeader.replace(/bytes=/, '').split('-');\n const start = parseInt(parts[0], 10);\n const end = parts[1] ? parseInt(parts[1], 10) : totalSize - 1;\n\n return { start, end };\n}\n\n/**\n * Create standardized response headers for media files\n * @param {Object} options - Header options\n * @param {string} options.contentType - Content-Type header\n * @param {number|string} options.contentLength - Content-Length header\n * @param {boolean} options.includeCache - Include Cache-Control header\n * @param {string} options.contentRange - Content-Range for 206 responses\n * @returns {Object} Response headers\n */\nexport function createMediaHeaders({\n contentType = 'application/octet-stream',\n contentLength = null,\n includeCache = false,\n contentRange = null\n}) {\n const headers = {\n 'Content-Type': contentType,\n 'Accept-Ranges': 'bytes',\n 'Access-Control-Allow-Origin': '*'\n };\n\n if (contentLength !== null) {\n headers['Content-Length'] = String(contentLength);\n }\n\n if (includeCache) {\n headers['Cache-Control'] = 'public, max-age=31536000';\n }\n\n if (contentRange) {\n headers['Content-Range'] = contentRange;\n }\n\n return headers;\n}\n\n/**\n * Create error response with consistent format\n * @param {string} message - Error message\n * @param {number} status - HTTP status code\n * @returns {Response}\n */\nexport function createErrorResponse(message, status = 500) {\n const statusTexts = {\n 404: 'Not Found',\n 500: 'Internal Server Error',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable'\n };\n\n return new Response(message, {\n status,\n statusText: statusTexts[status] || 'Error',\n headers: { 'Content-Type': 'text/plain' }\n });\n}\n\n/**\n * HTTP Status Codes\n */\nexport const HTTP_STATUS = {\n OK: 200,\n PARTIAL_CONTENT: 206,\n NOT_FOUND: 404,\n INTERNAL_ERROR: 500,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503\n};\n\n/**\n * Timeouts (milliseconds)\n */\nexport const TIMEOUTS = {\n SW_CLAIM_WAIT: 100, // Wait for SW to claim page\n SW_FETCH_READY: 200, // Wait for SW fetch handler\n SW_READY_MAX: 10000, // Max wait for SW ready\n DOWNLOAD_CHECK: 1000 // Download progress check interval\n};\n\n/**\n * Calculate chunk boundaries\n * @param {number} chunkIndex - Chunk index\n * @param {number} chunkSize - Size per chunk\n * @param {number} totalSize - Total file size\n * @returns {{ start: number, end: number, size: number }}\n */\nexport function getChunkBoundaries(chunkIndex, chunkSize, totalSize) {\n const start = chunkIndex * chunkSize;\n const end = Math.min(start + chunkSize, totalSize);\n return { start, end, size: end - start };\n}\n\n/**\n * Calculate which chunks contain a byte range\n * @param {number} rangeStart - Range start byte\n * @param {number} rangeEnd - Range end byte\n * @param {number} chunkSize - Size per chunk\n * @returns {{ startChunk: number, endChunk: number, count: number }}\n */\nexport function getChunksForRange(rangeStart, rangeEnd, chunkSize) {\n const startChunk = Math.floor(rangeStart / chunkSize);\n const endChunk = Math.floor(rangeEnd / chunkSize);\n return {\n startChunk,\n endChunk,\n count: endChunk - startChunk + 1\n };\n}\n\n/**\n * Extract byte range from chunk blobs\n * @param {Blob[]} chunkBlobs - Array of chunk blobs\n * @param {number} rangeStart - Desired start byte (absolute position in file)\n * @param {number} rangeEnd - Desired end byte (absolute position in file)\n * @param {number} chunkSize - Size per chunk\n * @param {string} contentType - Content type for result blob\n * @returns {Blob} Extracted range\n */\nexport function extractRangeFromChunks(chunkBlobs, rangeStart, rangeEnd, chunkSize, contentType) {\n if (chunkBlobs.length === 1) {\n // Single chunk - simple slice\n const offset = rangeStart % chunkSize;\n const length = rangeEnd - rangeStart + 1;\n return chunkBlobs[0].slice(offset, offset + length);\n }\n\n // Multiple chunks - concatenate parts\n const parts = [];\n const firstChunkOffset = rangeStart % chunkSize;\n const lastChunkEnd = rangeEnd % chunkSize;\n\n // First chunk (partial from offset to end)\n parts.push(chunkBlobs[0].slice(firstChunkOffset));\n\n // Middle chunks (complete - use as-is)\n for (let i = 1; i < chunkBlobs.length - 1; i++) {\n parts.push(chunkBlobs[i]);\n }\n\n // Last chunk (partial from start to lastChunkEnd)\n if (chunkBlobs.length > 1) {\n parts.push(chunkBlobs[chunkBlobs.length - 1].slice(0, lastChunkEnd + 1));\n }\n\n return new Blob(parts, { type: contentType });\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * RequestHandler - Handles fetch events for cached content\n *\n * With CMS mirror routes on the proxy, the SW's role is minimal:\n * - ${PLAYER_API}/* requests pass through to Express (mirror routes serve them)\n * - Static pages pass through to network\n *\n * No URL translation needed — the proxy serves at CMS paths directly.\n * Widget HTML is served by the Express mirror route at ${PLAYER_API}/widgets/{L}/{R}/{M}.\n */\n\nimport { BASE } from './sw-utils.js';\nimport { createLogger, PLAYER_API } from '@xiboplayer/utils';\n\nexport class RequestHandler {\n /**\n * @param {Object} downloadManager - DownloadManager instance\n */\n constructor(downloadManager) {\n this.downloadManager = downloadManager;\n this.log = createLogger('SW');\n }\n\n /**\n * Handle fetch request\n */\n async handleRequest(event) {\n const url = new URL(event.request.url);\n\n // Static pages — pass through to Express\n if (url.pathname === BASE + '/' ||\n url.pathname === BASE + '/index.html' ||\n url.pathname === BASE + '/setup.html') {\n return fetch(event.request);\n }\n\n // Player API — pass through to Express mirror routes\n if (url.pathname.startsWith(PLAYER_API + '/')) {\n return fetch(event.request);\n }\n\n // XMDS file downloads — route through Express cache-through\n if (url.pathname.includes('xmds.php') && url.searchParams.has('file')) {\n return this._handleXmdsFile(event, url);\n }\n\n // Not a cache request — pass through to network\n return fetch(event.request);\n }\n\n /**\n * Route XMDS file downloads to the local Express cache-through proxy.\n *\n * XMDS RequiredFiles returns cross-origin signed URLs like:\n * https://cms/xmds.php?file=42.mp4&type=M&X-Amz-Signature=...\n *\n * We rewrite these to local proxy mirror paths so the download goes through\n * ContentStore caching, avoiding CORS issues and enabling chunked downloads.\n */\n _handleXmdsFile(event, url) {\n const filename = url.searchParams.get('file');\n const fileType = url.searchParams.get('type'); // L=layout, M=media, P=resource/font\n const itemId = url.searchParams.get('itemId');\n\n let proxyPath;\n if (fileType === 'L') {\n proxyPath = `${PLAYER_API}/layouts/${itemId}`;\n } else if (fileType === 'P') {\n proxyPath = `${PLAYER_API}/dependencies/${filename}`;\n } else {\n proxyPath = `${PLAYER_API}/media/file/${filename}`;\n }\n\n this.log.info(`XMDS redirect: ${fileType}/${filename} → ${proxyPath}`);\n\n // Pass original XMDS URL so proxy can fetch from CMS on cache miss\n const headers = new Headers(event.request.headers);\n headers.set('X-Cms-Download-Url', url.href);\n\n return fetch(proxyPath, { headers });\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * MessageHandler - Handles postMessage from client\n *\n * Lightweight SW message handler for lifecycle and file management.\n * Download orchestration has moved to the main thread (PwaPlayer).\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\n/** Store key = URL path without leading / and query params */\nconst storeKeyFrom = (f) => (f.path || '').split('?')[0].replace(/^\\/+/, '') || `${f.type || 'media'}/${f.id}`;\n\nexport class MessageHandler {\n /**\n * @param {Object} downloadManager - DownloadManager instance (kept for future SW-only mode)\n * @param {Object} config\n */\n constructor(downloadManager, config) {\n this.downloadManager = downloadManager;\n this.config = config;\n this.log = createLogger('SW Message');\n }\n\n /**\n * Handle message from client\n */\n async handleMessage(event) {\n const { type, data } = event.data;\n this.log.info('Received:', type);\n\n switch (type) {\n case 'PING': {\n this.log.info('PING received, broadcasting SW_READY');\n const clients = await self.clients.matchAll();\n clients.forEach(client => {\n client.postMessage({ type: 'SW_READY' });\n });\n return { success: true };\n }\n\n case 'DELETE_FILES':\n return await this.handleDeleteFiles(data.files);\n\n case 'GET_ALL_FILES':\n return await this.handleGetAllFiles();\n\n case 'CLEAR_CACHE':\n return { success: true };\n\n default:\n this.log.warn('Unknown message type:', type);\n return { success: false, error: 'Unknown message type' };\n }\n }\n\n /**\n * Handle DELETE_FILES message - purge obsolete files from ContentStore via proxy\n */\n async handleDeleteFiles(files) {\n if (!files || !Array.isArray(files)) {\n return { success: false, error: 'No files provided' };\n }\n\n try {\n const deleteFiles = files.map(f => ({\n ...f,\n key: storeKeyFrom(f),\n }));\n const resp = await fetch('/store/delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files: deleteFiles }),\n });\n const result = await resp.json();\n this.log.info(`Purge complete: ${result.deleted}/${result.total} files deleted`);\n return { success: true, deleted: result.deleted, total: result.total };\n } catch (err) {\n this.log.error('Delete failed:', err.message);\n return { success: false, error: err.message };\n }\n }\n\n /**\n * Handle GET_ALL_FILES — list files from ContentStore via proxy\n */\n async handleGetAllFiles() {\n try {\n const resp = await fetch('/store/list');\n const data = await resp.json();\n return { success: true, files: data.files || [] };\n } catch (err) {\n this.log.error('Failed to list files:', err.message);\n return { success: true, files: [] };\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Chunk configuration for Service Worker downloads\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\n/**\n * Calculate optimal chunk size based on available device memory.\n * Returns configuration for chunk streaming, blob caching, and download concurrency.\n *\n * @param {{ info: Function }} [log] - Optional logger (created internally if not provided)\n * @returns {{ chunkSize: number, blobCacheSize: number, threshold: number, concurrency: number }}\n */\nexport function calculateChunkConfig(log) {\n if (!log) log = createLogger('ChunkConfig');\n\n // Try to detect device memory (Chrome only for now)\n const deviceMemoryGB = (typeof navigator !== 'undefined' && navigator.deviceMemory) || null;\n\n // Fallback: estimate from user agent\n let estimatedRAM_GB = 4; // Default assumption\n\n if (deviceMemoryGB) {\n estimatedRAM_GB = deviceMemoryGB;\n log.info('Detected device memory:', deviceMemoryGB, 'GB');\n } else if (typeof navigator !== 'undefined') {\n // Parse user agent for hints\n const ua = navigator.userAgent.toLowerCase();\n if (ua.includes('raspberry pi') || ua.includes('armv6')) {\n estimatedRAM_GB = 0.5; // Pi Zero\n log.info('Detected Pi Zero (512 MB RAM estimated)');\n } else if (ua.includes('armv7')) {\n estimatedRAM_GB = 1; // Pi 3/4\n log.info('Detected ARM device (1 GB RAM estimated)');\n } else {\n log.info('Using default RAM estimate:', estimatedRAM_GB, 'GB');\n }\n }\n\n // Configure based on RAM - chunk size, cache, threshold, AND concurrency\n let chunkSize, blobCacheSize, threshold, concurrency;\n\n if (estimatedRAM_GB <= 0.5) {\n // Pi Zero (512 MB) - very conservative\n chunkSize = 10 * 1024 * 1024;\n blobCacheSize = 25;\n threshold = 25 * 1024 * 1024;\n concurrency = 1;\n log.info('Low-memory config: 10 MB chunks, 25 MB cache, 1 concurrent download');\n } else if (estimatedRAM_GB <= 1) {\n // 1 GB RAM (Pi 3) - conservative\n chunkSize = 20 * 1024 * 1024;\n blobCacheSize = 50;\n threshold = 50 * 1024 * 1024;\n concurrency = 2;\n log.info('1GB-RAM config: 20 MB chunks, 50 MB cache, 2 concurrent downloads');\n } else if (estimatedRAM_GB <= 2) {\n // 2 GB RAM - moderate\n chunkSize = 30 * 1024 * 1024;\n blobCacheSize = 100;\n threshold = 75 * 1024 * 1024;\n concurrency = 2;\n log.info('2GB-RAM config: 30 MB chunks, 100 MB cache, 2 concurrent downloads');\n } else if (estimatedRAM_GB <= 4) {\n // 4 GB RAM - default\n chunkSize = 50 * 1024 * 1024;\n blobCacheSize = 200;\n threshold = 100 * 1024 * 1024;\n concurrency = 4;\n log.info('4GB-RAM config: 50 MB chunks, 200 MB cache, 4 concurrent downloads');\n } else {\n // 8+ GB RAM - generous but heap-safe (100 MB × 4 = 400 MB peak, within 768 MB V8 heap)\n chunkSize = 100 * 1024 * 1024;\n blobCacheSize = 500;\n threshold = 200 * 1024 * 1024;\n concurrency = 4;\n log.info('High-RAM config: 100 MB chunks, 500 MB cache, 4 concurrent downloads');\n }\n\n return { chunkSize, blobCacheSize, threshold, concurrency };\n}\n","/**\n * Standalone Service Worker for Xibo PWA Player\n * Thin entry point — all reusable logic lives in @xiboplayer/sw\n *\n * Architecture:\n * - @xiboplayer/sw: RequestHandler, MessageHandler\n * - @xiboplayer/cache: DownloadManager, LayoutTaskBuilder\n * - @xiboplayer/proxy: ContentStore (filesystem storage — runs server-side)\n * - This file: PWA-specific wiring (lifecycle events, Interactive Control)\n *\n * Media storage flow:\n * CMS → proxy cache-through → ContentStore (filesystem) → proxy /store → renderer\n * Download orchestration lives in the main thread (PwaPlayer).\n */\n\nimport { DownloadManager } from '@xiboplayer/cache/download-manager';\nimport { VERSION as CACHE_VERSION } from '@xiboplayer/cache';\nimport {\n RequestHandler,\n MessageHandler,\n calculateChunkConfig\n} from '@xiboplayer/sw';\nimport { createLogger } from '@xiboplayer/utils';\nimport { BASE } from '@xiboplayer/sw/utils';\n\n// ── Configuration ──────────────────────────────────────────────────────────\nconst SW_VERSION = __BUILD_DATE__;\n\nconst log = createLogger('SW');\n\n// ── Device-adaptive chunk config ───────────────────────────────────────────\nconst CHUNK_CONFIG = calculateChunkConfig(log);\nconst CHUNK_SIZE = CHUNK_CONFIG.chunkSize;\nconst CHUNK_STORAGE_THRESHOLD = CHUNK_CONFIG.threshold;\nconst CONCURRENT_DOWNLOADS = CHUNK_CONFIG.concurrency;\n\nlog.info('Loading modular Service Worker:', SW_VERSION);\n\n// ── Initialize shared instances ────────────────────────────────────────────\nconst downloadManager = new DownloadManager({\n concurrency: CONCURRENT_DOWNLOADS,\n chunkSize: CHUNK_SIZE,\n chunksPerFile: 2\n});\n\nconst requestHandler = new RequestHandler(downloadManager);\n\nconst messageHandler = new MessageHandler(downloadManager, {\n chunkSize: CHUNK_SIZE,\n chunkStorageThreshold: CHUNK_STORAGE_THRESHOLD\n});\n\n// ── PWA-specific: Interactive Control handler ──────────────────────────────\n\n/**\n * Handle Interactive Control requests from widget iframes.\n * Forwards to main thread via MessageChannel and returns the response.\n * IC library in widgets uses XHR to /player/pwa/ic/{route}.\n */\nasync function handleInteractiveControl(event) {\n const url = new URL(event.request.url);\n const icPath = url.pathname.replace(BASE + '/ic', '');\n const method = event.request.method;\n\n log.info('Interactive Control request:', method, icPath);\n\n let body = null;\n if (method === 'POST' || method === 'PUT') {\n try {\n body = await event.request.text();\n } catch (_) {}\n }\n\n // Forward to main thread via MessageChannel\n const clients = await self.clients.matchAll({ type: 'window' });\n if (clients.length === 0) {\n return new Response(JSON.stringify({ error: 'No active player' }), {\n status: 503,\n headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }\n });\n }\n\n const client = clients[0];\n\n try {\n const response = await new Promise((resolve, reject) => {\n const channel = new MessageChannel();\n const timer = setTimeout(() => reject(new Error('IC timeout')), 5000);\n\n channel.port1.onmessage = (msg) => {\n clearTimeout(timer);\n resolve(msg.data);\n };\n\n client.postMessage({\n type: 'INTERACTIVE_CONTROL',\n method,\n path: icPath,\n search: url.search,\n body\n }, [channel.port2]);\n });\n\n return new Response(response.body || '', {\n status: response.status || 200,\n headers: {\n 'Content-Type': response.contentType || 'application/json',\n 'Access-Control-Allow-Origin': '*'\n }\n });\n } catch (error) {\n log.error('IC handler error:', error);\n return new Response(JSON.stringify({ error: error.message }), {\n status: 500,\n headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }\n });\n }\n}\n\n// ── Lifecycle: Install ─────────────────────────────────────────────────────\nself.addEventListener('install', (event) => {\n log.info('Installing... Version:', SW_VERSION);\n event.waitUntil(\n (async () => {\n // Check if same version is already active — skip activation to preserve streams\n if (self.registration.active) {\n try {\n const versionCache = await caches.open('xibo-sw-version');\n const stored = await versionCache.match('version');\n if (stored) {\n const activeVersion = await stored.text();\n if (activeVersion === SW_VERSION) {\n log.info('Same version already active, skipping activation to preserve streams');\n return;\n }\n log.info('Version changed:', activeVersion, '→', SW_VERSION);\n }\n } catch (_) {}\n }\n log.info('New version, activating immediately');\n return self.skipWaiting();\n })()\n );\n});\n\n// ── Lifecycle: Activate ────────────────────────────────────────────────────\nself.addEventListener('activate', (event) => {\n log.info('Activating... Version:', SW_VERSION, '| @xiboplayer/cache:', CACHE_VERSION);\n event.waitUntil(\n // Clean up legacy Cache API caches (migration from pre-ContentStore)\n caches.keys().then((cacheNames) => {\n return Promise.all(\n cacheNames\n .filter((name) => name.startsWith('xibo-') && name !== 'xibo-sw-version')\n .map((name) => {\n log.info('Deleting legacy cache:', name);\n return caches.delete(name);\n })\n );\n }).then(async () => {\n const versionCache = await caches.open('xibo-sw-version');\n await versionCache.put('version', new Response(SW_VERSION));\n log.info('Taking control of all clients immediately');\n return self.clients.claim();\n }).then(async () => {\n log.info('Notifying all clients that fetch handler is ready');\n const clients = await self.clients.matchAll();\n clients.forEach(client => {\n client.postMessage({ type: 'SW_READY' });\n });\n })\n );\n});\n\n// ── Fetch handler ──────────────────────────────────────────────────────────\nself.addEventListener('fetch', (event) => {\n const url = new URL(event.request.url);\n\n const shouldIntercept =\n url.pathname.startsWith(BASE + '/ic/') ||\n url.pathname.startsWith('/player/') && (url.pathname.endsWith('.html') || url.pathname === '/player/') ||\n (url.pathname.includes('xmds.php') && url.searchParams.has('file') && event.request.method === 'GET');\n\n if (shouldIntercept) {\n if (url.pathname.startsWith(BASE + '/ic/')) {\n event.respondWith(handleInteractiveControl(event));\n return;\n }\n event.respondWith(requestHandler.handleRequest(event));\n }\n});\n\n// ── Message handler ────────────────────────────────────────────────────────\nself.addEventListener('message', (event) => {\n event.waitUntil(\n messageHandler.handleMessage(event).then((result) => {\n event.ports[0]?.postMessage(result);\n })\n );\n});\n\nlog.info('Modular Service Worker ready');\n"],"mappings":"qvBCoBM,EAAa,CACjB,MAAO,EACP,KAAM,EACN,QAAS,EACT,MAAO,EACP,KAAM,EACP,CAGK,EAAW,EAAE,CAEb,EAAN,KAAa,CAKX,YAAY,EAAM,EAAQ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AkB,EACtC,IAAI,UAAW,IAAI,SAAS,EAAW,CAAC,CAC3D,EAAI,KAAK,4CAA4C,CAC9C,KAAK,QAAQ,OAAO,EAC3B,CAAC,KAAK,SAAY,CAClB,EAAI,KAAK,oDAAoD,EAC7C,MAAM,KAAK,QAAQ,UAAU,EACrC,QAAQ,GAAU,CACxB,EAAO,YAAY,CAAE,KAAM,WAAY,CAAC,EACxC,EACF,CACH,EACD,CAGF,KAAK,iBAAiB,QAAU,GAAU,CACxC,IAAM,EAAM,IAAI,IAAI,EAAM,QAAQ,IAAI,CAOtC,GAJE,EAAI,SAAS,WAAW,EAAO,OAAO,EACtC,EAAI,SAAS,WAAW,WAAW,GAAK,EAAI,SAAS,SAAS,QAAQ,EAAI,EAAI,WAAa,aAC1F,EAAI,SAAS,SAAS,WAAW,EAAI,EAAI,aAAa,IAAI,OAAO,EAAI,EAAM,QAAQ,SAAW,MAE5E,CACnB,GAAI,EAAI,SAAS,WAAW,EAAO,OAAO,CAAE,CAC1C,EAAM,YAAY,GAAyB,EAAM,CAAC,CAClD,OAEF,EAAM,YAAY,GAAe,cAAc,EAAM,CAAC,GAExD,CAGF,KAAK,iBAAiB,UAAY,GAAU,CAC1C,EAAM,UACJ,GAAe,cAAc,EAAM,CAAC,KAAM,GAAW,CACnD,EAAM,MAAM,IAAI,YAAY,EAAO,EACnC,CACH,EACD,CAEF,EAAI,KAAK,+BAA+B"}
1
+ {"version":3,"file":"sw-pwa.js","names":["log","log","log","VERSION","pkg","_config","log","log","log","log","log","BASE","pkg","CACHE_VERSION"],"sources":["../../utils/package.json","../../utils/src/logger.js","../../crypto/src/rsa.js","../../utils/src/idb.js","../../utils/src/config.js","../../utils/src/fetch-retry.js","../../utils/src/cms-api.js","../../utils/src/index.js","../../cache/src/file-types.js","../../cache/src/download-manager.js","../../cache/package.json","../../cache/src/cache.js","../../cache/src/store-client.js","../../cache/src/cache-analyzer.js","../../cache/src/widget-html.js","../../cache/src/index.js","../../sw/src/sw-utils.js","../../sw/src/request-handler.js","../../sw/src/message-handler.js","../../sw/src/chunk-config.js","../public/sw-pwa.js"],"sourcesContent":["{\n \"name\": \"@xiboplayer/utils\",\n \"version\": \"0.7.23\",\n \"description\": \"Shared utilities for xiboplayer packages\",\n \"type\": \"module\",\n \"main\": \"./src/index.js\",\n \"types\": \"./src/index.d.ts\",\n \"exports\": {\n \".\": \"./src/index.js\",\n \"./logger\": \"./src/logger.js\",\n \"./event-emitter\": \"./src/event-emitter.js\",\n \"./config\": \"./src/config.js\"\n },\n \"scripts\": {\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\"\n },\n \"dependencies\": {\n \"@xiboplayer/crypto\": \"workspace:*\"\n },\n \"devDependencies\": {\n \"vitest\": \"^4.1.2\"\n },\n \"keywords\": [\n \"xibo\",\n \"digital-signage\",\n \"utilities\",\n \"logger\",\n \"event-emitter\"\n ],\n \"author\": \"Pau Aliagas <linuxnow@gmail.com>\",\n \"license\": \"AGPL-3.0-or-later\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/xibo-players/xiboplayer.git\",\n \"directory\": \"packages/utils\"\n },\n \"homepage\": \"https://xiboplayer.org\"\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Configurable Logger for xiboplayers\n *\n * Supports log levels: DEBUG, INFO, WARNING, ERROR, NONE\n *\n * Level precedence (highest wins):\n * 1. URL param ?logLevel=DEBUG\n * 2. localStorage xibo_log_level\n * 3. CMS setting via RegisterDisplay (call applyCmsLogLevel())\n * 4. Default: WARNING (production-safe)\n *\n * For development, pass ?logLevel=DEBUG in the URL.\n * Electron's --dev flag does this automatically.\n *\n * Loggers created without an explicit level are REACTIVE — they follow\n * the global level at call time, so setLogLevel() affects all of them.\n */\n\nconst LOG_LEVELS = {\n DEBUG: 0,\n INFO: 1,\n WARNING: 2,\n ERROR: 3,\n NONE: 4\n};\n\n// Log sink system — external consumers (e.g., LogReporter) can intercept all log output\nconst logSinks = [];\n\nclass Logger {\n /**\n * @param {string} name - Logger name (shown in prefix)\n * @param {string|null} level - Explicit level string, or null to follow global\n */\n constructor(name, level = null) {\n this.name = name;\n this.useGlobal = (level === null);\n if (!this.useGlobal) {\n this.setLevel(level);\n }\n }\n\n /** HH:MM:SS.mmm timestamp for log lines */\n _ts() {\n const d = new Date();\n return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}.${String(d.getMilliseconds()).padStart(3, '0')}`;\n }\n\n setLevel(level) {\n this.useGlobal = false;\n if (typeof level === 'string') {\n this.level = LOG_LEVELS[level.toUpperCase()] ?? LOG_LEVELS.INFO;\n } else {\n this.level = level;\n }\n }\n\n /** Effective level: own override or global */\n getEffectiveLevel() {\n return this.useGlobal ? globalConfig.level : this.level;\n }\n\n debug(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.DEBUG) {\n console.log(`${this._ts()} [${this.name}] DEBUG:`, ...args);\n }\n _dispatchToSinks('debug', this.name, args);\n }\n\n info(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.INFO) {\n console.log(`${this._ts()} [${this.name}]`, ...args);\n }\n _dispatchToSinks('info', this.name, args);\n }\n\n warn(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.WARNING) {\n console.warn(`${this._ts()} [${this.name}]`, ...args);\n }\n _dispatchToSinks('warning', this.name, args);\n }\n\n error(...args) {\n if (this.getEffectiveLevel() <= LOG_LEVELS.ERROR) {\n console.error(`${this._ts()} [${this.name}]`, ...args);\n }\n _dispatchToSinks('error', this.name, args);\n }\n\n // Convenience method for conditional logging\n log(level, ...args) {\n switch (level.toUpperCase()) {\n case 'DEBUG': return this.debug(...args);\n case 'INFO': return this.info(...args);\n case 'WARNING':\n case 'WARN': return this.warn(...args);\n case 'ERROR': return this.error(...args);\n }\n }\n}\n\n// Global log level configuration\nconst globalConfig = {\n level: LOG_LEVELS.WARNING, // Default: WARNING (production-safe)\n\n setGlobalLevel(level) {\n if (typeof level === 'string') {\n this.level = LOG_LEVELS[level.toUpperCase()] ?? LOG_LEVELS.INFO;\n } else {\n this.level = level;\n }\n\n console.log(`[Logger] Global log level set to: ${this.getLevelName(this.level)}`);\n },\n\n getLevelName(level) {\n return Object.keys(LOG_LEVELS).find(key => LOG_LEVELS[key] === level) || 'UNKNOWN';\n }\n};\n\n// Track whether the level was set by a local override (URL param / localStorage)\nlet hasLocalOverride = false;\n\n// Set global level from environment or localStorage\n// Default: WARNING (production-safe). Use ?logLevel=DEBUG for development,\n// or let the CMS override via applyCmsLogLevel().\nif (typeof window !== 'undefined') {\n const urlParams = new URLSearchParams(window.location.search);\n const urlLevel = urlParams.get('logLevel');\n const storageLevel = localStorage.getItem('xibo_log_level');\n\n // Also check config-injected logLevel (proxy writes xibo_config to localStorage)\n let configLevel = null;\n try {\n const cfg = JSON.parse(localStorage.getItem('xibo_config') || '{}');\n configLevel = cfg.logLevel || null;\n } catch (_) {}\n\n if (urlLevel) {\n globalConfig.setGlobalLevel(urlLevel);\n hasLocalOverride = true;\n } else if (storageLevel) {\n globalConfig.setGlobalLevel(storageLevel);\n hasLocalOverride = true;\n } else if (configLevel) {\n globalConfig.setGlobalLevel(configLevel);\n hasLocalOverride = true;\n } else {\n globalConfig.setGlobalLevel('WARNING');\n }\n} else if (typeof self !== 'undefined' && self.swLogLevel) {\n // Service Worker context: use self.swLogLevel (set before importing this module)\n globalConfig.setGlobalLevel(self.swLogLevel);\n}\n\n// Factory function — loggers follow global level by default (reactive)\nexport function createLogger(name, level = null) {\n return new Logger(name, level);\n}\n\n// Set global log level (and persist to localStorage)\nexport function setLogLevel(level) {\n globalConfig.setGlobalLevel(level);\n\n // Save to localStorage\n if (typeof window !== 'undefined') {\n localStorage.setItem('xibo_log_level', level.toUpperCase());\n }\n}\n\n// Get current log level name\nexport function getLogLevel() {\n return globalConfig.getLevelName(globalConfig.level);\n}\n\n/**\n * Returns true when the effective global level is DEBUG.\n * Use this for conditional debug features (video controls, overlays, etc.)\n */\nexport function isDebug() {\n return globalConfig.level <= LOG_LEVELS.DEBUG;\n}\n\n/**\n * Apply CMS logLevel setting — only if no local override (URL/localStorage) exists.\n * @param {string} cmsLevel - CMS level string: 'error', 'audit', 'info', 'debug'\n * @returns {boolean} true if the level was applied\n */\nexport function applyCmsLogLevel(cmsLevel) {\n if (hasLocalOverride) return false;\n if (!cmsLevel) return false;\n\n const mapped = mapCmsLogLevel(cmsLevel);\n globalConfig.setGlobalLevel(mapped);\n return true;\n}\n\n/**\n * Map CMS logLevel strings to internal level names.\n * CMS uses: 'emergency','alert','critical','error','warning','notice','info','debug','audit'\n * We collapse them to our 4 levels.\n */\nexport function mapCmsLogLevel(cmsLevel) {\n switch ((cmsLevel || '').toLowerCase()) {\n case 'debug':\n return 'DEBUG';\n case 'info':\n case 'notice':\n case 'audit':\n return 'INFO';\n case 'warning':\n return 'WARNING';\n case 'error':\n case 'critical':\n case 'alert':\n case 'emergency':\n return 'ERROR';\n default:\n return 'INFO';\n }\n}\n\n/**\n * Dispatch log entry to all registered sinks.\n * Sinks receive { level, name, args } and should not throw.\n * @private\n */\nfunction _dispatchToSinks(level, name, args) {\n if (logSinks.length === 0) return;\n for (const fn of logSinks) {\n try {\n fn({ level, name, args });\n } catch (_) {\n // Sink errors must never break logging\n }\n }\n}\n\n/**\n * Register a log sink — receives all log output regardless of level filtering.\n * @param {function} fn - Callback: ({ level, name, args }) => void\n */\nexport function registerLogSink(fn) {\n logSinks.push(fn);\n}\n\n/**\n * Unregister a previously registered log sink.\n * @param {function} fn - The same function reference passed to registerLogSink\n */\nexport function unregisterLogSink(fn) {\n const idx = logSinks.indexOf(fn);\n if (idx >= 0) logSinks.splice(idx, 1);\n}\n\nexport { LOG_LEVELS };\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * RSA key pair generation via Web Crypto API.\n *\n * Generates RSA-1024 keys compatible with the upstream .NET player.\n * The SPKI PEM public key works with PHP's openssl_get_publickey().\n *\n * No runtime dependencies — uses only the Web Crypto API available\n * in browsers, Electron, and Node.js 16+.\n */\n\n/**\n * Convert an ArrayBuffer (DER-encoded key) to PEM format.\n * @param {ArrayBuffer} buffer - DER-encoded key data\n * @param {string} type - Key type label ('PUBLIC KEY' or 'PRIVATE KEY')\n * @returns {string} PEM-formatted key string\n */\nexport function arrayBufferToPem(buffer, type) {\n const bytes = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n const base64 = btoa(binary);\n\n // Split into 64-character lines per PEM spec\n const lines = [];\n for (let i = 0; i < base64.length; i += 64) {\n lines.push(base64.substring(i, i + 64));\n }\n\n return `-----BEGIN ${type}-----\\n${lines.join('\\n')}\\n-----END ${type}-----`;\n}\n\n/**\n * Generate an RSA key pair for XMR registration.\n *\n * Uses RSA-OAEP with SHA-256 and a 1024-bit modulus to match\n * the upstream .NET player's key format.\n *\n * @returns {Promise<{publicKeyPem: string, privateKeyPem: string}>}\n */\nexport async function generateRsaKeyPair() {\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'RSA-OAEP',\n modulusLength: 1024,\n publicExponent: new Uint8Array([1, 0, 1]), // 65537\n hash: 'SHA-256',\n },\n true, // extractable\n ['encrypt', 'decrypt']\n );\n\n const publicKeyDer = await crypto.subtle.exportKey('spki', keyPair.publicKey);\n const privateKeyDer = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey);\n\n return {\n publicKeyPem: arrayBufferToPem(publicKeyDer, 'PUBLIC KEY'),\n privateKeyPem: arrayBufferToPem(privateKeyDer, 'PRIVATE KEY'),\n };\n}\n\n/**\n * Validate that a string looks like a valid PEM key.\n * Checks for proper BEGIN/END headers and base64 content.\n *\n * @param {string} pem - String to validate\n * @returns {boolean} true if the string appears to be valid PEM\n */\nexport function isValidPemKey(pem) {\n if (!pem || typeof pem !== 'string') return false;\n\n const pemRegex = /^-----BEGIN (PUBLIC KEY|PRIVATE KEY)-----\\n[A-Za-z0-9+/=\\n]+\\n-----END \\1-----$/;\n return pemRegex.test(pem.trim());\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Shared IndexedDB open helper — avoids duplicating the open/upgrade\n * boilerplate across stats, core, and config packages.\n *\n * @param {string} dbName - Database name\n * @param {number} version - Schema version\n * @param {string} storeName - Object store to create on upgrade\n * @param {Object} [options]\n * @param {string} [options.keyPath] - Key path for the store (auto-increment if set)\n * @param {string} [options.indexName] - Index to create on the store\n * @param {string} [options.indexKey] - Key for the index\n * @returns {Promise<IDBDatabase>}\n */\nexport function openIDB(dbName, version, storeName, options = {}) {\n if (typeof indexedDB === 'undefined') {\n return Promise.reject(new Error('IndexedDB not available'));\n }\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(dbName, version);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(storeName)) {\n const storeOpts = options.keyPath\n ? { keyPath: options.keyPath, autoIncrement: true }\n : undefined;\n const store = db.createObjectStore(storeName, storeOpts);\n if (options.indexName && options.indexKey) {\n store.createIndex(options.indexName, options.indexKey, { unique: false });\n }\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\n/**\n * Query records from an IndexedDB index with a cursor, up to a limit.\n * @param {IDBDatabase} db - IndexedDB database instance\n * @param {string} storeName - Object store name\n * @param {string} indexName - Index name\n * @param {any} value - Key to query (passed to openCursor)\n * @param {number} limit - Maximum records to return\n * @returns {Promise<Array>}\n */\nexport function queryByIndex(db, storeName, indexName, value, limit) {\n return new Promise((resolve, reject) => {\n const tx = db.transaction([storeName], 'readonly');\n const index = tx.objectStore(storeName).index(indexName);\n const request = index.openCursor(value);\n const results = [];\n\n request.onsuccess = (event) => {\n const cursor = event.target.result;\n if (cursor && results.length < limit) {\n results.push(cursor.value);\n cursor.continue();\n } else {\n resolve(results);\n }\n };\n request.onerror = () => reject(new Error(`Index query failed: ${request.error}`));\n });\n}\n\n/**\n * Delete records by ID from an IndexedDB object store.\n * @param {IDBDatabase} db - IndexedDB database instance\n * @param {string} storeName - Object store name\n * @param {Array} ids - Array of record IDs to delete\n * @returns {Promise<number>} Number of deleted records\n */\nexport function deleteByIds(db, storeName, ids) {\n return new Promise((resolve, reject) => {\n const tx = db.transaction([storeName], 'readwrite');\n const store = tx.objectStore(storeName);\n let deleted = 0;\n\n for (const id of ids) {\n if (id) {\n const req = store.delete(id);\n req.onsuccess = () => { deleted++; };\n req.onerror = () => { /* individual delete failed — tx.onerror handles fatal */ };\n }\n }\n\n tx.oncomplete = () => resolve(deleted);\n tx.onerror = () => reject(new Error(`Delete failed: ${tx.error}`));\n });\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Configuration management with priority: env vars → localStorage → defaults\n *\n * Storage layout (per-CMS namespacing):\n * xibo_global — device identity: hardwareKey, xmrPubKey, xmrPrivKey\n * xibo_cms:{cmsId} — CMS-scoped: cmsUrl, cmsKey, displayName, xmrChannel, ...\n * xibo_active_cms — string cmsId of the currently active CMS\n * xibo_config — legacy flat key (written for rollback compatibility)\n *\n * In Node.js (tests, CLI): environment variables are the only source.\n * In browser (PWA player): localStorage is primary, env vars override if set.\n */\nimport { generateRsaKeyPair, isValidPemKey } from '@xiboplayer/crypto';\nimport { openIDB } from './idb.js';\nimport { createLogger } from './logger.js';\n\nconst log = createLogger('Config');\n\nconst GLOBAL_KEY = 'xibo_global'; // Device identity (all CMSes)\nconst CMS_PREFIX = 'xibo_cms:'; // Per-CMS config prefix\nconst ACTIVE_CMS_KEY = 'xibo_active_cms'; // Active CMS ID\nconst HW_DB_NAME = 'xibo-hw-backup';\nconst HW_DB_VERSION = 1;\n\n// Keys that belong to device identity (global, not CMS-scoped)\nconst GLOBAL_KEYS = new Set(['hardwareKey', 'xmrPubKey', 'xmrPrivKey']);\n\n/**\n * FNV-1a hash producing a 12-character hex string.\n * Deterministic: same input always produces same output.\n * @param {string} str - Input string to hash\n * @returns {string} 12-character lowercase hex string\n */\nexport function fnvHash(str) {\n let hash = 2166136261; // FNV offset basis\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n hash = hash >>> 0;\n\n // Extend to 12 chars with a second round using a different seed\n let hash2 = hash + 1234567;\n for (let i = 0; i < str.length; i++) {\n hash2 ^= str.charCodeAt(i) + 1;\n hash2 += (hash2 << 1) + (hash2 << 4) + (hash2 << 7) + (hash2 << 8) + (hash2 << 24);\n }\n hash2 = hash2 >>> 0;\n\n return (hash.toString(16).padStart(8, '0') + hash2.toString(16).padStart(8, '0')).substring(0, 12);\n}\n\n/**\n * Compute a deterministic CMS ID from a CMS URL.\n * Format: {hostname}-{fnvHash12}\n *\n * @param {string} cmsUrl - Full CMS URL (e.g. \"https://displays.superpantalles.com\")\n * @returns {string} CMS ID (e.g. \"displays.superpantalles.com-a1b2c3d4e5f6\")\n */\nexport function computeCmsId(cmsUrl) {\n if (!cmsUrl) return null;\n try {\n const url = new URL(cmsUrl);\n const origin = url.origin;\n return `${url.hostname}-${fnvHash(origin)}`;\n } catch (e) {\n // Invalid URL — hash the raw string\n return `unknown-${fnvHash(cmsUrl)}`;\n }\n}\n\n/**\n * Check for environment variable config (highest priority).\n * Env vars: CMS_URL, CMS_KEY, DISPLAY_NAME, HARDWARE_KEY, XMR_CHANNEL\n * Returns config object if any env vars are set, null otherwise.\n */\nfunction loadFromEnv() {\n // Check if process.env is available (Node.js or bundler injection)\n const env = typeof process !== 'undefined' && process.env ? process.env : {};\n\n const envConfig = {\n cmsUrl: env.CMS_URL || '',\n cmsKey: env.CMS_KEY || '',\n displayName: env.DISPLAY_NAME || '',\n hardwareKey: env.HARDWARE_KEY || '',\n xmrChannel: env.XMR_CHANNEL || '',\n googleGeoApiKey: env.GOOGLE_GEO_API_KEY || '',\n };\n\n // Return env config if any value is set\n const hasEnvValues = Object.values(envConfig).some(v => v !== '');\n return hasEnvValues ? envConfig : null;\n}\n\nexport class Config {\n constructor() {\n this._activeCmsId = null;\n this.data = this.load();\n // Async: try to restore hardware key from IndexedDB if localStorage lost it\n // (only when not running from env vars)\n if (!this._fromEnv) {\n this._restoreHardwareKeyFromBackup();\n }\n }\n\n load() {\n // Priority 1: Environment variables (Node.js, tests, CI)\n const envConfig = loadFromEnv();\n if (envConfig) {\n this._fromEnv = true;\n return envConfig;\n }\n\n // Priority 2: localStorage (browser)\n if (typeof localStorage === 'undefined') {\n return { cmsUrl: '', cmsKey: '', displayName: '', hardwareKey: '', xmrChannel: '' };\n }\n\n // Load from split storage (or fresh install)\n const globalJson = localStorage.getItem(GLOBAL_KEY);\n\n if (globalJson) {\n return this._loadSplit();\n }\n\n // Fresh install — no config at all\n return this._loadFresh();\n }\n\n /**\n * Load from split storage (new format).\n * Merges xibo_global + xibo_cms:{activeCmsId} into a single data object.\n */\n _loadSplit() {\n let global = {};\n try {\n global = JSON.parse(localStorage.getItem(GLOBAL_KEY) || '{}');\n } catch (e) {\n log.error('Failed to parse xibo_global:', e);\n }\n\n // Determine active CMS\n const activeCmsId = localStorage.getItem(ACTIVE_CMS_KEY) || null;\n this._activeCmsId = activeCmsId;\n\n let cmsConfig = {};\n if (activeCmsId) {\n try {\n const cmsJson = localStorage.getItem(CMS_PREFIX + activeCmsId);\n if (cmsJson) cmsConfig = JSON.parse(cmsJson);\n } catch (e) {\n log.error('Failed to parse CMS config:', e);\n }\n }\n\n // Merge global + CMS-scoped\n const config = { ...global, ...cmsConfig };\n\n // Validate and generate missing keys\n return this._validateConfig(config);\n }\n\n /**\n * Fresh install — no existing config.\n */\n _loadFresh() {\n const config = {};\n return this._validateConfig(config);\n }\n\n /**\n * Validate config, generate missing hardwareKey/xmrChannel.\n * Shared by all load paths.\n */\n _validateConfig(config) {\n let changed = false;\n\n if (!config.hardwareKey || config.hardwareKey.length < 10) {\n log.warn('Missing/invalid hardwareKey — generating');\n config.hardwareKey = this.generateStableHardwareKey();\n this._backupHardwareKey(config.hardwareKey);\n changed = true;\n } else {\n log.info('✓ Loaded existing hardwareKey:', config.hardwareKey);\n }\n\n if (!config.xmrChannel) {\n log.warn('Missing xmrChannel — generating');\n config.xmrChannel = this.generateXmrChannel();\n changed = true;\n }\n\n // Ensure optional fields have defaults\n config.cmsUrl = config.cmsUrl || '';\n config.cmsKey = config.cmsKey || '';\n config.displayName = config.displayName || '';\n\n if (changed && typeof localStorage !== 'undefined') {\n // Save via split storage\n this._saveSplit(config);\n }\n\n return config;\n }\n\n save() {\n if (typeof localStorage === 'undefined') return;\n this._saveSplit(this.data);\n }\n\n /**\n * Write data to split storage: xibo_global + xibo_cms:{id} + legacy xibo_config.\n */\n _saveSplit(data) {\n if (typeof localStorage === 'undefined') return;\n\n // Split into global and CMS-scoped\n const global = {};\n const cmsScoped = {};\n for (const [key, value] of Object.entries(data)) {\n if (GLOBAL_KEYS.has(key)) {\n global[key] = value;\n } else {\n cmsScoped[key] = value;\n }\n }\n\n localStorage.setItem(GLOBAL_KEY, JSON.stringify(global));\n\n // Compute CMS ID (may update if cmsUrl changed)\n const cmsId = computeCmsId(data.cmsUrl);\n if (cmsId) {\n localStorage.setItem(CMS_PREFIX + cmsId, JSON.stringify(cmsScoped));\n localStorage.setItem(ACTIVE_CMS_KEY, cmsId);\n this._activeCmsId = cmsId;\n }\n\n // Legacy flat key for rollback compatibility (index.html gate, tests, etc.)\n localStorage.setItem('xibo_config', JSON.stringify(data));\n }\n\n /**\n * Switch to a different CMS. Saves the current CMS profile,\n * loads (or creates) the target CMS profile.\n *\n * @param {string} cmsUrl - New CMS URL to switch to\n * @returns {{ cmsId: string, isNew: boolean }} The new CMS ID and whether it was newly created\n */\n switchCms(cmsUrl) {\n if (typeof localStorage === 'undefined') {\n throw new Error('switchCms requires localStorage (browser only)');\n }\n\n // Save current state\n this.save();\n\n const newCmsId = computeCmsId(cmsUrl);\n if (!newCmsId) throw new Error('Invalid CMS URL');\n\n // Try to load existing CMS profile\n const existingJson = localStorage.getItem(CMS_PREFIX + newCmsId);\n let cmsConfig = {};\n let isNew = true;\n\n if (existingJson) {\n try {\n cmsConfig = JSON.parse(existingJson);\n isNew = false;\n log.info(`Switching to existing CMS profile: ${newCmsId}`);\n } catch (e) {\n log.error('Failed to parse target CMS config:', e);\n }\n } else {\n log.info(`Creating new CMS profile: ${newCmsId}`);\n cmsConfig = {\n cmsUrl,\n cmsKey: '',\n displayName: '',\n xmrChannel: this.generateXmrChannel(),\n };\n localStorage.setItem(CMS_PREFIX + newCmsId, JSON.stringify(cmsConfig));\n }\n\n // Update active CMS\n localStorage.setItem(ACTIVE_CMS_KEY, newCmsId);\n this._activeCmsId = newCmsId;\n\n // Merge global + new CMS config into data\n let global = {};\n try {\n global = JSON.parse(localStorage.getItem(GLOBAL_KEY) || '{}');\n } catch (_) {}\n\n this.data = { ...global, ...cmsConfig };\n\n // Ensure cmsUrl is set (in case the profile was pre-existing without it)\n if (!this.data.cmsUrl) {\n this.data.cmsUrl = cmsUrl;\n }\n\n return { cmsId: newCmsId, isNew };\n }\n\n /**\n * List all CMS profiles stored in localStorage.\n * @returns {Array<{ cmsId: string, cmsUrl: string, displayName: string, isActive: boolean }>}\n */\n listCmsProfiles() {\n if (typeof localStorage === 'undefined') return [];\n\n const profiles = [];\n const activeCmsId = localStorage.getItem(ACTIVE_CMS_KEY) || null;\n\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (!key.startsWith(CMS_PREFIX)) continue;\n\n const cmsId = key.slice(CMS_PREFIX.length);\n try {\n const data = JSON.parse(localStorage.getItem(key));\n profiles.push({\n cmsId,\n cmsUrl: data.cmsUrl || '',\n displayName: data.displayName || '',\n isActive: cmsId === activeCmsId,\n });\n } catch (_) {}\n }\n\n return profiles;\n }\n\n /**\n * Get the active CMS ID (deterministic hash of the CMS URL origin).\n * Returns null if no CMS is configured.\n * @returns {string|null}\n */\n get activeCmsId() {\n // Return cached value if available\n if (this._activeCmsId) return this._activeCmsId;\n // Compute from current cmsUrl\n const id = computeCmsId(this.data?.cmsUrl);\n this._activeCmsId = id;\n return id;\n }\n\n isConfigured() {\n return !!(this.data.cmsUrl && this.data.cmsKey && this.data.displayName);\n }\n\n /**\n * Backup keys to IndexedDB (more persistent than localStorage).\n * IndexedDB survives \"Clear site data\" in some browsers where localStorage doesn't.\n * @param {Object} keys - Key-value pairs to store (e.g. { hardwareKey: '...', xmrPubKey: '...' })\n */\n async _backupKeys(keys) {\n try {\n const db = await openIDB(HW_DB_NAME, HW_DB_VERSION, 'keys');\n const tx = db.transaction('keys', 'readwrite');\n const store = tx.objectStore('keys');\n for (const [k, v] of Object.entries(keys)) {\n store.put(v, k);\n }\n tx.oncomplete = () => {\n log.info('Keys backed up to IndexedDB:', Object.keys(keys).join(', '));\n db.close();\n };\n } catch (e) {\n // IndexedDB not available — localStorage-only mode\n }\n }\n\n /**\n * Backup hardware key to IndexedDB (convenience wrapper).\n */\n _backupHardwareKey(key) {\n this._backupKeys({ hardwareKey: key });\n }\n\n /**\n * Restore hardware key from IndexedDB if localStorage was cleared.\n * Runs async after construction — if a backed-up key is found and\n * differs from the current one, it restores the original key.\n */\n async _restoreHardwareKeyFromBackup() {\n try {\n const db = await openIDB(HW_DB_NAME, HW_DB_VERSION, 'keys');\n\n const tx = db.transaction('keys', 'readonly');\n const store = tx.objectStore('keys');\n const backedUpKey = await new Promise((resolve) => {\n const req = store.get('hardwareKey');\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => resolve(null);\n });\n db.close();\n\n if (backedUpKey && backedUpKey !== this.data.hardwareKey) {\n log.info('Restoring hardware key from IndexedDB backup:', backedUpKey);\n log.info('(was:', this.data.hardwareKey, ')');\n this.data.hardwareKey = backedUpKey;\n this.save();\n } else if (!backedUpKey && this.data.hardwareKey) {\n // No backup yet — save current key as backup\n this._backupHardwareKey(this.data.hardwareKey);\n }\n } catch (e) {\n // IndexedDB not available — that's fine\n }\n }\n\n generateStableHardwareKey() {\n // Generate a stable UUID-based hardware key\n // CRITICAL: This is generated ONCE and saved to localStorage\n // It NEVER changes unless localStorage is cleared manually\n\n // Use crypto.randomUUID if available (best randomness)\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n const uuid = crypto.randomUUID().replace(/-/g, ''); // Remove dashes\n const hardwareKey = 'pwa-' + uuid.substring(0, 28);\n log.info('Generated new UUID-based hardware key:', hardwareKey);\n return hardwareKey;\n }\n\n // Fallback: Generate random hex string\n const randomHex = Array.from({ length: 28 }, () =>\n Math.floor(Math.random() * 16).toString(16)\n ).join('');\n\n const hardwareKey = 'pwa-' + randomHex;\n log.info('Generated new random hardware key:', hardwareKey);\n return hardwareKey;\n }\n\n generateXmrChannel() {\n // Generate UUID for XMR channel\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n }\n\n /**\n * Ensure an RSA key pair exists for XMR registration.\n * If keys are missing or invalid, generates a new pair and persists them.\n * Idempotent — safe to call multiple times.\n */\n async ensureXmrKeyPair() {\n if (this.data.xmrPubKey && isValidPemKey(this.data.xmrPubKey)) {\n return;\n }\n\n log.info('Generating RSA key pair for XMR registration...');\n const { publicKeyPem, privateKeyPem } = await generateRsaKeyPair();\n\n this.data.xmrPubKey = publicKeyPem;\n this.data.xmrPrivKey = privateKeyPem;\n this.save();\n\n // Backup RSA keys to IndexedDB alongside hardware key\n if (typeof indexedDB !== 'undefined') {\n this._backupKeys({ xmrPubKey: publicKeyPem, xmrPrivKey: privateKeyPem });\n }\n\n log.info('RSA key pair generated and saved');\n }\n\n get cmsUrl() { return this.data.cmsUrl; }\n set cmsUrl(val) { this.data.cmsUrl = val; this.save(); }\n\n get cmsKey() { return this.data.cmsKey; }\n set cmsKey(val) { this.data.cmsKey = val; this.save(); }\n\n get displayName() { return this.data.displayName; }\n set displayName(val) { this.data.displayName = val; this.save(); }\n\n get hardwareKey() {\n // CRITICAL: Ensure hardware key never becomes undefined\n if (!this.data.hardwareKey) {\n log.error('CRITICAL: hardwareKey missing! Generating emergency key.');\n this.data.hardwareKey = this.generateStableHardwareKey();\n this.save();\n }\n return this.data.hardwareKey;\n }\n get xmrChannel() {\n if (!this.data.xmrChannel) {\n log.warn('xmrChannel missing at access time — generating');\n this.data.xmrChannel = this.generateXmrChannel();\n this.save();\n }\n return this.data.xmrChannel;\n }\n get xmrPubKey() { return this.data.xmrPubKey || ''; }\n get xmrPrivKey() { return this.data.xmrPrivKey || ''; }\n\n get googleGeoApiKey() { return this.data.googleGeoApiKey || ''; }\n set googleGeoApiKey(val) { this.data.googleGeoApiKey = val; this.save(); }\n\n get controls() { return this.data.controls || {}; }\n get transport() { return this.data.transport || 'auto'; }\n get debug() { return this.data.debug || {}; }\n}\n\nexport const config = new Config();\n\n/**\n * Shell-only config keys common to ALL player shells (Electron, Chromium, etc.).\n * These control the native shell window/process and must NOT be forwarded to the PWA.\n *\n * Each shell may have additional shell-specific keys — pass them as extraShellKeys\n * to extractPwaConfig().\n *\n * Electron extras: autoLaunch\n * Chromium extras: browser, extraBrowserFlags\n */\n/**\n * Keys that are specific to a particular shell platform.\n * Used by warnPlatformMismatch() to detect config.json mistakes.\n */\nconst PLATFORM_KEYS = {\n kioskMode: ['electron', 'chromium'],\n autoLaunch: ['electron'],\n allowShellCommands: ['electron', 'chromium'],\n browser: ['chromium'],\n extraBrowserFlags: ['chromium'],\n};\n\n/**\n * Log warnings for config keys that don't belong to the current platform.\n * Informational only — does not prevent startup.\n *\n * @param {Object} configObj - The full config.json object\n * @param {string} platform - Current platform: 'electron' or 'chromium'\n */\nexport function warnPlatformMismatch(configObj, platform) {\n if (!configObj || !platform) return;\n const p = platform.toLowerCase();\n for (const [key, platforms] of Object.entries(PLATFORM_KEYS)) {\n if (key in configObj && !platforms.includes(p)) {\n log.warn(\n `Key \"${key}\" is only supported on ${platforms.join('/')}, ` +\n `but current platform is ${p} — this key will be ignored`\n );\n }\n }\n}\n\nexport const SHELL_ONLY_KEYS = new Set([\n 'serverPort',\n 'kioskMode',\n 'fullscreen',\n 'hideMouseCursor',\n 'preventSleep',\n 'allowShellCommands',\n 'width',\n 'height',\n 'relaxSslCerts',\n]);\n\n/**\n * Extract PWA config from a full shell config.json.\n *\n * Uses a deny-list approach: filters out shell-only keys, passes everything else.\n * This is future-proof — new config.json fields automatically reach the PWA\n * without code changes in each shell.\n *\n * @param {Object} config - Full config object from config.json\n * @param {Iterable<string>} [extraShellKeys] - Additional shell-specific keys to exclude\n * @returns {Object} Config to pass to the PWA (via proxy pwaConfig)\n */\nexport function extractPwaConfig(config, extraShellKeys) {\n const exclude = new Set([...SHELL_ONLY_KEYS, ...(extraShellKeys || [])]);\n const pwaConfig = {};\n for (const [key, value] of Object.entries(config)) {\n if (!exclude.has(key)) {\n pwaConfig[key] = value;\n }\n }\n return Object.keys(pwaConfig).length > 0 ? pwaConfig : undefined;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Fetch with retry and exponential backoff\n *\n * Wraps native fetch() with configurable retry logic for transient failures.\n * Only retries on network errors and 5xx server errors (not 4xx client errors).\n * On final attempt, returns the response as-is so the caller can handle errors.\n */\n\nimport { createLogger } from './logger.js';\n\nconst log = createLogger('FetchRetry');\n\nconst DEFAULT_429_DELAY_MS = 30000;\nconst MAX_429_DELAY_MS = 120000;\n\n/**\n * Parse a Retry-After header value into milliseconds.\n * Supports both delta-seconds (\"120\") and HTTP-date (\"Fri, 21 Feb 2026 12:00:00 GMT\").\n * Returns a sensible default if the header is missing or unparseable.\n * The returned delay is NOT capped by maxDelayMs — the server's rate-limit\n * instruction takes priority over our backoff ceiling.\n * @param {string|null} headerValue\n * @returns {number} delay in milliseconds (clamped to MAX_429_DELAY_MS)\n */\nfunction parseRetryAfter(headerValue) {\n if (!headerValue) return DEFAULT_429_DELAY_MS;\n\n // Try delta-seconds first (most common)\n const seconds = Number(headerValue);\n if (!isNaN(seconds) && seconds >= 0) {\n return Math.min(seconds * 1000, MAX_429_DELAY_MS);\n }\n\n // Try HTTP-date format (RFC 7231 §7.1.3)\n const date = new Date(headerValue);\n if (!isNaN(date.getTime())) {\n const delayMs = date.getTime() - Date.now();\n return Math.min(Math.max(delayMs, 0), MAX_429_DELAY_MS);\n }\n\n return DEFAULT_429_DELAY_MS;\n}\n\n/**\n * Fetch with automatic retry on failure\n * @param {string|URL} url - URL to fetch\n * @param {RequestInit} [options] - Fetch options\n * @param {Object} [retryOptions] - Retry configuration\n * @param {number} [retryOptions.maxRetries=3] - Maximum retry attempts\n * @param {number} [retryOptions.baseDelayMs=1000] - Base delay between retries (doubles each time)\n * @param {number} [retryOptions.maxDelayMs=30000] - Maximum delay between retries\n * @returns {Promise<Response>}\n */\nexport async function fetchWithRetry(url, options = {}, retryOptions = {}) {\n const { maxRetries = 3, baseDelayMs = 1000, maxDelayMs = 30000 } = retryOptions;\n\n let lastError;\n let lastResponse;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n\n // HTTP 429 Too Many Requests — respect Retry-After header\n if (response.status === 429) {\n const delayMs = parseRetryAfter(response.headers.get('Retry-After'));\n log.debug(`429 Rate limited, waiting ${delayMs}ms (Retry-After: ${response.headers.get('Retry-After')})`);\n lastResponse = response;\n lastError = new Error(`HTTP 429: Too Many Requests`);\n lastError.status = 429;\n if (attempt < maxRetries) {\n await new Promise(resolve => setTimeout(resolve, delayMs));\n continue; // Skip the normal backoff delay below\n }\n break; // Exhausted retries\n }\n\n // Don't retry anything below 500 — only 5xx server errors are retryable.\n // This covers 2xx (success), 3xx (redirects including 304 Not Modified),\n // and 4xx (client errors that won't change with retries).\n if (response.status < 500) {\n return response;\n }\n\n // Server error (5xx) — retryable, but return on last attempt\n lastResponse = response;\n lastError = new Error(`HTTP ${response.status}: ${response.statusText}`);\n lastError.status = response.status;\n\n // Respect Retry-After on 503 Service Unavailable (e.g. CMS cache warming)\n if (response.status === 503 && attempt < maxRetries) {\n const retryAfter = response.headers.get('Retry-After');\n if (retryAfter) {\n const delayMs = parseRetryAfter(retryAfter);\n log.debug(`503 Service Unavailable, Retry-After: ${retryAfter} (${delayMs}ms)`);\n await new Promise(resolve => setTimeout(resolve, delayMs));\n continue;\n }\n }\n } catch (error) {\n // Network error — retryable\n log.warn(`Fetch error (attempt ${attempt + 1}/${maxRetries + 1}):`, error.message || error, String(url).slice(0, 80));\n lastError = error;\n lastResponse = null;\n }\n\n if (attempt < maxRetries) {\n const delay = Math.min(baseDelayMs * 2 ** attempt, maxDelayMs);\n const jitter = delay * (0.5 + Math.random() * 0.5); // 50-100% of delay\n log.debug(`Retry ${attempt + 1}/${maxRetries} in ${Math.round(jitter)}ms:`, String(url).slice(0, 80));\n await new Promise(resolve => setTimeout(resolve, jitter));\n }\n }\n\n // On exhausted retries: return response if we have one (let caller handle),\n // throw if we only have network errors\n if (lastResponse) {\n return lastResponse;\n }\n throw lastError;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CMS API Client — OAuth2-authenticated REST client for Xibo CMS\n *\n * Full CRUD client for all Xibo CMS REST API entities: displays, layouts,\n * regions, widgets, media, campaigns, schedules, display groups, resolutions,\n * commands, dayparts, playlists, datasets, notifications, folders, and tags.\n * Implements OAuth2 client_credentials flow (machine-to-machine).\n *\n * Usage:\n * const api = new CmsApiClient({ baseUrl: 'https://cms.example.com', clientId, clientSecret });\n * await api.authenticate();\n * const layout = await api.createLayout({ name: 'Test', resolutionId: 9 });\n * const region = await api.addRegion(layout.layoutId, { width: 1920, height: 1080 });\n * await api.addWidget('text', region.playlists[0].playlistId, { text: 'Hello' });\n * await api.publishLayout(layout.layoutId);\n */\n\nimport { createLogger } from './logger.js';\n\nconst log = createLogger('CmsApi');\n\nexport class CmsApiClient {\n /**\n * @param {Object} options\n * @param {string} options.baseUrl - CMS base URL (e.g. https://cms.example.com)\n * @param {string} [options.clientId] - OAuth2 application client ID\n * @param {string} [options.clientSecret] - OAuth2 application client secret\n * @param {string} [options.apiToken] - Pre-configured bearer token (skips OAuth2 flow)\n */\n constructor({ baseUrl, clientId, clientSecret, apiToken } = {}) {\n this.baseUrl = (baseUrl || '').replace(/\\/+$/, '');\n this.clientId = clientId || null;\n this.clientSecret = clientSecret || null;\n this.accessToken = apiToken || null;\n this.tokenExpiry = apiToken ? Infinity : 0;\n }\n\n // ── OAuth2 Token Management ─────────────────────────────────────\n\n /**\n * Authenticate using client_credentials grant\n * @returns {Promise<string>} Access token\n */\n async authenticate() {\n log.info('Authenticating with CMS API...');\n\n const response = await fetch(`${this.baseUrl}/api/authorize/access_token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.clientId,\n client_secret: this.clientSecret\n })\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`OAuth2 authentication failed (${response.status}): ${text}`);\n }\n\n const data = await response.json();\n this.accessToken = data.access_token;\n this.tokenExpiry = Date.now() + (data.expires_in || 3600) * 1000;\n\n log.info('Authenticated successfully, token expires in', data.expires_in, 's');\n return this.accessToken;\n }\n\n /**\n * Ensure we have a valid token (auto-refresh if expired)\n */\n async ensureToken() {\n if (this.accessToken && Date.now() < this.tokenExpiry - 60000) return;\n if (!this.clientId || !this.clientSecret) {\n if (this.accessToken) return; // apiToken with no expiry\n throw new CmsApiError('AUTH', '/authorize', 0, 'No valid token and no OAuth2 credentials');\n }\n await this.authenticate();\n }\n\n /**\n * Make an authenticated API request\n * @param {string} method - HTTP method\n * @param {string} path - API path (e.g. /display)\n * @param {Object} [params] - Query params (GET) or body params (POST/PUT)\n * @returns {Promise<any>} Response data\n */\n async request(method, path, params = {}) {\n await this.ensureToken();\n\n const url = new URL(`${this.baseUrl}/api${path}`);\n const options = {\n method,\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`\n }\n };\n\n if (method === 'GET') {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n url.searchParams.set(key, String(value));\n }\n }\n } else {\n options.headers['Content-Type'] = 'application/x-www-form-urlencoded';\n options.body = new URLSearchParams(params);\n }\n\n const response = await fetch(url, options);\n\n if (!response.ok) {\n await this._handleErrorResponse(response, method, path);\n }\n\n // Some endpoints return empty body (204)\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return response.json();\n }\n return null;\n }\n\n // ── Convenience methods ────────────────────────────────────────\n\n /** GET request (path relative to /api/) */\n get(path, params) { return this.request('GET', path, params); }\n /** POST request (path relative to /api/) */\n post(path, body) { return this.request('POST', path, body); }\n /** PUT request (path relative to /api/) */\n put(path, body) { return this.request('PUT', path, body); }\n /** DELETE request (path relative to /api/) */\n del(path) { return this.request('DELETE', path); }\n\n /**\n * GET a list endpoint and ensure the result is always an array.\n * @param {string} path - API path\n * @param {Object} [filters={}] - Query parameters\n * @returns {Promise<Array>}\n */\n async _listRequest(path, filters = {}) {\n const data = await this.request('GET', path, filters);\n return Array.isArray(data) ? data : [];\n }\n\n /**\n * Parse an error response body and throw a structured error.\n * @param {Response} response - Fetch response\n * @param {string} method - HTTP method\n * @param {string} path - API path\n */\n async _handleErrorResponse(response, method, path) {\n const text = await response.text();\n let errorMsg;\n try {\n const errorData = JSON.parse(text);\n errorMsg = errorData.error?.message || errorData.message || text;\n } catch (_) {\n errorMsg = text;\n }\n throw new CmsApiError(method, path, response.status, errorMsg);\n }\n\n // ── Display Management ──────────────────────────────────────────\n\n /**\n * Find a display by hardware key\n * @param {string} hardwareKey\n * @returns {Promise<Object|null>} Display object or null if not found\n */\n async findDisplay(hardwareKey) {\n log.info('Looking up display by hardwareKey:', hardwareKey);\n const displays = await this._listRequest('/display', { hardwareKey });\n if (displays.length === 0) {\n log.info('No display found for hardwareKey:', hardwareKey);\n return null;\n }\n\n const display = displays[0];\n log.info(`Found display: ${display.display} (ID: ${display.displayId}, licensed: ${display.licensed})`);\n return display;\n }\n\n /**\n * Authorize (toggle licence) a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async authorizeDisplay(displayId) {\n log.info('Authorizing display:', displayId);\n await this.request('PUT', `/display/authorise/${displayId}`);\n log.info('Display authorized successfully');\n }\n\n /**\n * Edit display properties\n * @param {number} displayId\n * @param {Object} properties - Properties to update (display, description, defaultLayoutId, etc.)\n * @returns {Promise<Object>} Updated display\n */\n async editDisplay(displayId, properties) {\n log.info('Editing display:', displayId, properties);\n return this.request('PUT', `/display/${displayId}`, properties);\n }\n\n /**\n * List all displays (with optional filters)\n * @param {Object} [filters] - Optional filters (displayId, display, macAddress, hardwareKey, clientType)\n * @returns {Promise<Array>} Array of display objects\n */\n async listDisplays(filters = {}) {\n return this._listRequest('/display', filters);\n }\n\n /**\n * Request screenshot from a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async requestScreenshot(displayId) {\n await this.request('PUT', `/display/requestscreenshot/${displayId}`);\n }\n\n /**\n * Get display status\n * @param {number} displayId\n * @returns {Promise<Object>}\n */\n async getDisplayStatus(displayId) {\n return this.request('GET', `/display/status/${displayId}`);\n }\n\n // ── Multipart Requests (File Uploads) ─────────────────────────────\n\n /**\n * Make an authenticated multipart/form-data request (for file uploads).\n * Do NOT set Content-Type — fetch adds the multipart boundary automatically.\n * @param {string} method - HTTP method (POST/PUT)\n * @param {string} path - API path\n * @param {FormData} formData - Form data with files\n * @returns {Promise<any>} Response data\n */\n async requestMultipart(method, path, formData) {\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api${path}`;\n const response = await fetch(url, {\n method,\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`\n // No Content-Type — fetch sets multipart boundary automatically\n },\n body: formData\n });\n\n if (!response.ok) {\n await this._handleErrorResponse(response, method, path);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return response.json();\n }\n return null;\n }\n\n // ── Layout Management ─────────────────────────────────────────────\n\n /**\n * Create a new layout\n * @param {Object} params\n * @param {string} params.name - Layout name\n * @param {number} params.resolutionId - Resolution ID\n * @param {string} [params.description] - Description\n * @returns {Promise<Object>} Created layout\n */\n async createLayout({ name, resolutionId, description }) {\n const params = { name, resolutionId };\n if (description) params.description = description;\n return this.request('POST', '/layout', params);\n }\n\n /**\n * List layouts with optional filters\n * @param {Object} [filters] - Filters (layoutId, layout, userId, retired, etc.)\n * @returns {Promise<Array>}\n */\n async listLayouts(filters = {}) {\n return this._listRequest('/layout', filters);\n }\n\n /**\n * Get a single layout by ID\n * @param {number} layoutId\n * @returns {Promise<Object>}\n */\n async getLayout(layoutId) {\n return this.request('GET', `/layout/${layoutId}`);\n }\n\n /**\n * Delete a layout\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async deleteLayout(layoutId) {\n await this.request('DELETE', `/layout/${layoutId}`);\n }\n\n /**\n * Publish a draft layout (makes it available for scheduling)\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async publishLayout(layoutId) {\n await this.request('PUT', `/layout/publish/${layoutId}`, { publishNow: 1 });\n }\n\n /**\n * Checkout a published layout (creates editable draft).\n * NOTE: Not needed for newly created layouts — they already have a draft.\n * Use getDraftLayout() to find the auto-created draft instead.\n * @param {number} layoutId\n * @returns {Promise<Object>} Draft layout\n */\n async checkoutLayout(layoutId) {\n return this.request('PUT', `/layout/checkout/${layoutId}`);\n }\n\n /**\n * Get the draft (editable) layout for a given parent layout.\n * In Xibo v4, POST /layout creates a parent + hidden draft automatically.\n * The draft is the one you edit (add regions, widgets) before publishing.\n * @param {number} parentId - The parent layout ID returned by createLayout()\n * @returns {Promise<Object|null>} Draft layout or null if not found\n */\n async getDraftLayout(parentId) {\n const drafts = await this.listLayouts({ parentId });\n return drafts.length > 0 ? drafts[0] : null;\n }\n\n /**\n * Edit layout background\n * @param {number} layoutId\n * @param {Object} params\n * @param {number} [params.backgroundImageId] - Media ID for background image\n * @param {string} [params.backgroundColor] - Hex color (e.g. '#FF0000')\n * @returns {Promise<Object>}\n */\n async editLayoutBackground(layoutId, params) {\n return this.request('PUT', `/layout/background/${layoutId}`, params);\n }\n\n // ── Region Management ─────────────────────────────────────────────\n\n /**\n * Add a region to a layout\n * @param {number} layoutId - Must be the DRAFT layout ID (not the parent)\n * @param {Object} params - { width, height, top, left }\n * @returns {Promise<Object>} Created region with regionPlaylist (singular object, not array)\n */\n async addRegion(layoutId, params) {\n return this.request('POST', `/region/${layoutId}`, params);\n }\n\n /**\n * Edit a region's properties\n * @param {number} regionId\n * @param {Object} params - { width, height, top, left, zIndex }\n * @returns {Promise<Object>}\n */\n async editRegion(regionId, params) {\n return this.request('PUT', `/region/${regionId}`, params);\n }\n\n /**\n * Delete a region\n * @param {number} regionId\n * @returns {Promise<void>}\n */\n async deleteRegion(regionId) {\n await this.request('DELETE', `/region/${regionId}`);\n }\n\n // ── Widget/Playlist Management ────────────────────────────────────\n\n /**\n * Add a widget to a playlist\n *\n * Xibo CMS v4 uses a two-step process:\n * 1. POST creates the widget shell (only templateId and displayOrder are processed)\n * 2. PUT sets all widget properties (uri, duration, mute, etc.)\n *\n * @param {string} type - Widget type (text, image, video, embedded, clock, etc.)\n * @param {number} playlistId - Target playlist ID (from region.playlists[0].playlistId)\n * @param {Object} [properties] - Widget-specific properties\n * @returns {Promise<Object>} Created widget with properties applied\n */\n async addWidget(type, playlistId, properties = {}) {\n // Step 1: Create the widget (only templateId/displayOrder handled by CMS addWidget)\n const { templateId, displayOrder, ...editProps } = properties;\n const createParams = {};\n if (templateId !== undefined) createParams.templateId = templateId;\n if (displayOrder !== undefined) createParams.displayOrder = displayOrder;\n\n const widget = await this.request('POST', `/playlist/widget/${type}/${playlistId}`, createParams);\n\n // Step 2: Set widget properties via editWidget (CMS processes all module properties here)\n if (Object.keys(editProps).length > 0) {\n // useDuration=1 tells CMS to use our custom duration instead of module default\n if (editProps.duration !== undefined && editProps.useDuration === undefined) {\n editProps.useDuration = 1;\n }\n return this.request('PUT', `/playlist/widget/${widget.widgetId}`, editProps);\n }\n\n return widget;\n }\n\n /**\n * Edit a widget's properties\n * @param {number} widgetId\n * @param {Object} properties - Widget-specific properties to update\n * @returns {Promise<Object>}\n */\n async editWidget(widgetId, properties) {\n return this.request('PUT', `/playlist/widget/${widgetId}`, properties);\n }\n\n /**\n * Delete a widget\n * @param {number} widgetId\n * @returns {Promise<void>}\n */\n async deleteWidget(widgetId) {\n await this.request('DELETE', `/playlist/widget/${widgetId}`);\n }\n\n // ── Media / Library ───────────────────────────────────────────────\n\n /**\n * Upload a media file to the library\n * @param {FormData} formData - Must include 'files' field with the file(s)\n * @returns {Promise<Object>} Upload result with media info\n */\n async uploadMedia(formData) {\n return this.requestMultipart('POST', '/library', formData);\n }\n\n /**\n * List media in the library\n * @param {Object} [filters] - Filters (mediaId, media, type, ownerId, etc.)\n * @returns {Promise<Array>}\n */\n async listMedia(filters = {}) {\n return this._listRequest('/library', filters);\n }\n\n /**\n * Get a single media item by ID\n * @param {number} mediaId\n * @returns {Promise<Object>}\n */\n async getMedia(mediaId) {\n return this.request('GET', `/library/${mediaId}`);\n }\n\n /**\n * Delete a media item from the library\n * @param {number} mediaId\n * @returns {Promise<void>}\n */\n async deleteMedia(mediaId) {\n await this.request('DELETE', `/library/${mediaId}`);\n }\n\n // ── Campaign Management ───────────────────────────────────────────\n\n /**\n * Create a campaign\n * @param {string} name - Campaign name\n * @returns {Promise<Object>} Created campaign\n */\n async createCampaign(name) {\n return this.request('POST', '/campaign', { name });\n }\n\n /**\n * List campaigns\n * @param {Object} [filters] - Filters (campaignId, name, etc.)\n * @returns {Promise<Array>}\n */\n async listCampaigns(filters = {}) {\n return this._listRequest('/campaign', filters);\n }\n\n /**\n * Delete a campaign\n * @param {number} campaignId\n * @returns {Promise<void>}\n */\n async deleteCampaign(campaignId) {\n await this.request('DELETE', `/campaign/${campaignId}`);\n }\n\n /**\n * Assign a layout to a campaign\n * @param {number} campaignId\n * @param {number} layoutId\n * @param {number} [displayOrder] - Position in campaign playlist\n * @returns {Promise<void>}\n */\n async assignLayoutToCampaign(campaignId, layoutId, displayOrder) {\n const params = { layoutId };\n if (displayOrder !== undefined) params.displayOrder = displayOrder;\n await this.request('POST', `/campaign/layout/assign/${campaignId}`, params);\n }\n\n // ── Schedule Management ───────────────────────────────────────────\n\n /**\n * Create a schedule event\n * @param {Object} params\n * @param {number} params.eventTypeId - 1=Campaign, 2=Command, 3=Overlay\n * @param {number} params.campaignId - Campaign to schedule\n * @param {Array<number>} params.displayGroupIds - Target display group IDs\n * @param {string} params.fromDt - Start date (ISO 8601)\n * @param {string} params.toDt - End date (ISO 8601)\n * @param {number} [params.isPriority] - 0 or 1\n * @param {number} [params.displayOrder] - Order within schedule\n * @returns {Promise<Object>} Created schedule event\n */\n async createSchedule(params) {\n // displayGroupIds needs to be sent as displayGroupIds[] for the API\n const body = { ...params };\n if (Array.isArray(body.displayGroupIds)) {\n // Xibo API expects repeated keys: displayGroupIds[]=1&displayGroupIds[]=2\n // URLSearchParams handles this when we pass entries manually\n delete body.displayGroupIds;\n }\n\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api/schedule`;\n const urlParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(body)) {\n if (value !== undefined && value !== null) {\n urlParams.set(key, String(value));\n }\n }\n\n // Append array values as repeated keys\n if (Array.isArray(params.displayGroupIds)) {\n for (const id of params.displayGroupIds) {\n urlParams.append('displayGroupIds[]', String(id));\n }\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`CMS API POST /schedule failed (${response.status}): ${text}`);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return response.json();\n }\n return null;\n }\n\n /**\n * Delete a schedule event\n * @param {number} eventId\n * @returns {Promise<void>}\n */\n async deleteSchedule(eventId) {\n await this.request('DELETE', `/schedule/${eventId}`);\n }\n\n /**\n * List schedule events\n * @param {Object} [filters] - Filters (displayGroupIds, fromDt, toDt)\n * @returns {Promise<Array>}\n */\n async listSchedules(filters = {}) {\n const data = await this.request('GET', '/schedule/data/events', filters);\n return Array.isArray(data) ? data : (data?.events || []);\n }\n\n // ── Display Group Management ──────────────────────────────────────\n\n /**\n * List display groups\n * @param {Object} [filters] - Filters (displayGroupId, displayGroup)\n * @returns {Promise<Array>}\n */\n async listDisplayGroups(filters = {}) {\n return this._listRequest('/displaygroup', filters);\n }\n\n /**\n * Create a display group\n * @param {string} name - Display group name\n * @param {string} [description]\n * @returns {Promise<Object>} Created display group\n */\n async createDisplayGroup(name, description) {\n const params = { displayGroup: name };\n if (description) params.description = description;\n return this.request('POST', '/displaygroup', params);\n }\n\n /**\n * Delete a display group\n * @param {number} displayGroupId\n * @returns {Promise<void>}\n */\n async deleteDisplayGroup(displayGroupId) {\n await this.request('DELETE', `/displaygroup/${displayGroupId}`);\n }\n\n /**\n * Assign a display to a display group\n * @param {number} displayGroupId\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async assignDisplayToGroup(displayGroupId, displayId) {\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api/displaygroup/${displayGroupId}/display/assign`;\n const urlParams = new URLSearchParams();\n urlParams.append('displayId[]', String(displayId));\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`CMS API assign display to group failed (${response.status}): ${text}`);\n }\n }\n\n /**\n * Unassign a display from a display group\n * @param {number} displayGroupId\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async unassignDisplayFromGroup(displayGroupId, displayId) {\n await this.ensureToken();\n\n const url = `${this.baseUrl}/api/displaygroup/${displayGroupId}/display/unassign`;\n const urlParams = new URLSearchParams();\n urlParams.append('displayId[]', String(displayId));\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`CMS API unassign display from group failed (${response.status}): ${text}`);\n }\n }\n\n // ── Resolution Management ─────────────────────────────────────────\n\n /**\n * List available resolutions\n * @returns {Promise<Array>}\n */\n async listResolutions() {\n return this._listRequest('/resolution');\n }\n\n // ── Template Management ──────────────────────────────────────────\n\n /**\n * List available layout templates\n * @param {Object} [filters] - Filters (layout, tags, etc.)\n * @returns {Promise<Array>}\n */\n async listTemplates(filters = {}) {\n return this._listRequest('/template', filters);\n }\n\n // ── Playlist Management ──────────────────────────────────────────\n\n /**\n * Assign media library items to a playlist (for file-based widgets: audio, PDF, video)\n * @param {number} playlistId\n * @param {number[]} mediaIds - Array of media IDs to assign\n * @returns {Promise<Object>}\n */\n async assignMediaToPlaylist(playlistId, mediaIds) {\n const ids = Array.isArray(mediaIds) ? mediaIds : [mediaIds];\n // Xibo API expects media[] repeated keys\n await this.ensureToken();\n const url = `${this.baseUrl}/api/playlist/library/assign/${playlistId}`;\n const urlParams = new URLSearchParams();\n for (const id of ids) {\n urlParams.append('media[]', String(id));\n }\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n if (!response.ok) {\n const text = await response.text();\n throw new CmsApiError('POST', `/playlist/library/assign/${playlistId}`, response.status, text);\n }\n const contentType = response.headers.get('Content-Type') || '';\n return contentType.includes('application/json') ? response.json() : null;\n }\n\n // ── Layout Edit ───────────────────────────────────────────────────\n\n /**\n * Edit layout properties\n * @param {number} layoutId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editLayout(layoutId, params) {\n return this.request('PUT', `/layout/${layoutId}`, params);\n }\n\n // ── Layout Copy / Discard (#25) ────────────────────────────────────\n\n /**\n * Copy a layout\n * @param {number} layoutId\n * @param {Object} [opts] - Options (name, description, copyMediaFiles)\n * @returns {Promise<Object>} Copied layout\n */\n async copyLayout(layoutId, opts = {}) {\n return this.post(`/layout/copy/${layoutId}`, opts);\n }\n\n /**\n * Discard a draft layout (revert to last published version)\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async discardLayout(layoutId) {\n await this.put(`/layout/discard/${layoutId}`);\n }\n\n // ── Campaign Edit / Unassign (#26) ─────────────────────────────────\n\n /**\n * Edit campaign properties\n * @param {number} campaignId\n * @param {Object} params - Properties to update (name, etc.)\n * @returns {Promise<Object>} Updated campaign\n */\n async editCampaign(campaignId, params) {\n return this.put(`/campaign/${campaignId}`, params);\n }\n\n /**\n * Get a single campaign by ID\n * @param {number} campaignId\n * @returns {Promise<Object>}\n */\n async getCampaign(campaignId) {\n return this.get(`/campaign/${campaignId}`);\n }\n\n /**\n * Unassign a layout from a campaign\n * @param {number} campaignId\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async unassignLayoutFromCampaign(campaignId, layoutId) {\n await this.post(`/campaign/layout/unassign/${campaignId}`, { layoutId });\n }\n\n // ── Schedule Edit (#27) ────────────────────────────────────────────\n\n /**\n * Edit a schedule event\n * @param {number} eventId\n * @param {Object} params - Properties to update (fromDt, toDt, isPriority, etc.)\n * @returns {Promise<Object>} Updated schedule event\n */\n async editSchedule(eventId, params) {\n return this.put(`/schedule/${eventId}`, params);\n }\n\n // ── Layout Retire / Status / Tag (#34) ─────────────────────────────\n\n /**\n * Retire a layout (hide from new scheduling but keep existing schedules)\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async retireLayout(layoutId) {\n await this.put(`/layout/retire/${layoutId}`);\n }\n\n /**\n * Unretire a previously retired layout\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async unretireLayout(layoutId) {\n await this.put(`/layout/unretire/${layoutId}`);\n }\n\n /**\n * Get layout status (build status, validity)\n * @param {number} layoutId\n * @returns {Promise<Object>}\n */\n async getLayoutStatus(layoutId) {\n return this.get(`/layout/status/${layoutId}`);\n }\n\n /**\n * Tag a layout\n * @param {number} layoutId\n * @param {string[]} tags - Tag names to add\n * @returns {Promise<void>}\n */\n async tagLayout(layoutId, tags) {\n await this.post(`/layout/${layoutId}/tag`, { tag: tags.join(',') });\n }\n\n /**\n * Remove tags from a layout\n * @param {number} layoutId\n * @param {string[]} tags - Tag names to remove\n * @returns {Promise<void>}\n */\n async untagLayout(layoutId, tags) {\n await this.post(`/layout/${layoutId}/untag`, { tag: tags.join(',') });\n }\n\n // ── Command CRUD (#36) ─────────────────────────────────────────────\n\n /**\n * List commands\n * @param {Object} [filters] - Filters (commandId, command)\n * @returns {Promise<Array>}\n */\n async listCommands(filters = {}) {\n return this._listRequest('/command', filters);\n }\n\n /**\n * Create a command\n * @param {Object} params - { command, description, code }\n * @returns {Promise<Object>}\n */\n async createCommand(params) {\n return this.post('/command', params);\n }\n\n /**\n * Edit a command\n * @param {number} commandId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editCommand(commandId, params) {\n return this.put(`/command/${commandId}`, params);\n }\n\n /**\n * Delete a command\n * @param {number} commandId\n * @returns {Promise<void>}\n */\n async deleteCommand(commandId) {\n await this.del(`/command/${commandId}`);\n }\n\n // ── Display Extras (#41) ───────────────────────────────────────────\n\n /**\n * Delete a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async deleteDisplay(displayId) {\n await this.del(`/display/${displayId}`);\n }\n\n /**\n * Send Wake-on-LAN to a display\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async wolDisplay(displayId) {\n await this.post(`/display/wol/${displayId}`);\n }\n\n /**\n * Set the default layout for a display\n * @param {number} displayId\n * @param {number} layoutId - Layout to set as default\n * @returns {Promise<Object>}\n */\n async setDefaultLayout(displayId, layoutId) {\n return this.put(`/display/${displayId}`, { defaultLayoutId: layoutId });\n }\n\n /**\n * Purge all content from a display (force re-download)\n * @param {number} displayId\n * @returns {Promise<void>}\n */\n async purgeDisplay(displayId) {\n await this.post(`/display/purge/${displayId}`);\n }\n\n // ── DayPart CRUD (#24) ─────────────────────────────────────────────\n\n /**\n * List day parts\n * @param {Object} [filters] - Filters (dayPartId, name)\n * @returns {Promise<Array>}\n */\n async listDayParts(filters = {}) {\n return this._listRequest('/daypart', filters);\n }\n\n /**\n * Create a day part\n * @param {Object} params - { name, description, startTime, endTime, exceptionDays, ... }\n * @returns {Promise<Object>}\n */\n async createDayPart(params) {\n return this.post('/daypart', params);\n }\n\n /**\n * Edit a day part\n * @param {number} dayPartId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editDayPart(dayPartId, params) {\n return this.put(`/daypart/${dayPartId}`, params);\n }\n\n /**\n * Delete a day part\n * @param {number} dayPartId\n * @returns {Promise<void>}\n */\n async deleteDayPart(dayPartId) {\n await this.del(`/daypart/${dayPartId}`);\n }\n\n // ── Library Extensions (#33) ───────────────────────────────────────\n\n /**\n * Upload media from a URL\n * @param {string} url - Remote URL to download\n * @param {string} name - Name for the media item\n * @returns {Promise<Object>}\n */\n /**\n * Upload media to the Library from a publicly reachable URL.\n *\n * The CMS fetches the file server-side via MediaFactory::queueDownload —\n * no local download or multipart upload needed. This is the ideal path\n * for importing assets from a CDN or object store (e.g. Cloudflare R2)\n * into the Xibo Library.\n *\n * Targets `POST /library/uploadUrl` (Library::uploadFromUrl in the CMS)\n * which requires form-urlencoded fields. **Not** `POST /library`, which\n * is the multipart file-upload handler and rejects URL imports with HTTP\n * 500. This bug was reported in xibo-players/xiboplayer#332.\n *\n * @param {string} url - Publicly reachable URL of the media\n * @param {string} type - Xibo module type: \"image\", \"video\", \"audio\", \"genericfile\", etc.\n * @param {Object} [options]\n * @param {string} [options.optionalName] - Library display name. If omitted,\n * Xibo derives the name from the URL's filename.\n * @param {string} [options.extension] - Override file extension (otherwise\n * auto-detected from the HTTP Content-Type header).\n * @param {number} [options.folderId] - Target library folder ID.\n * @param {string} [options.enableStat] - 'On' | 'Off' | 'Inherit'.\n * @param {string} [options.expires] - Expiry date in `Y-m-d H:i:s` format.\n * @returns {Promise<{id: number, data: Object}>} Xibo's upload response.\n * `id` is the new mediaId; `data` is the full media object.\n *\n * @example\n * const result = await api.uploadMediaUrl(\n * 'https://media.xiboplayer.org/templates/welcome-lobby/welcome-1.jpg',\n * 'image',\n * { optionalName: 'welcome-lobby · welcome-1.jpg' },\n * );\n * console.log(result.id); // → new mediaId\n */\n async uploadMediaUrl(url, type, options = {}) {\n return this.post('/library/uploadUrl', { url, type, ...options });\n }\n\n /**\n * Copy a media item\n * @param {number} mediaId\n * @returns {Promise<Object>} Copied media\n */\n async copyMedia(mediaId) {\n return this.post(`/library/copy/${mediaId}`);\n }\n\n /**\n * Download a media file (returns raw response for streaming)\n * @param {number} mediaId\n * @returns {Promise<Response>} Raw fetch response\n */\n async downloadMedia(mediaId) {\n await this.ensureToken();\n const url = `${this.baseUrl}/api/library/download/${mediaId}`;\n const response = await fetch(url, {\n headers: { 'Authorization': `Bearer ${this.accessToken}` }\n });\n if (!response.ok) {\n const text = await response.text();\n throw new CmsApiError('GET', `/library/download/${mediaId}`, response.status, text);\n }\n return response;\n }\n\n /**\n * Edit media properties\n * @param {number} mediaId\n * @param {Object} params - Properties to update (name, duration, retired, etc.)\n * @returns {Promise<Object>}\n */\n async editMedia(mediaId, params) {\n return this.put(`/library/${mediaId}`, params);\n }\n\n /**\n * Get media usage (which layouts/playlists reference this media)\n * @param {number} mediaId\n * @returns {Promise<Object>}\n */\n async getMediaUsage(mediaId) {\n return this.get(`/library/usage/${mediaId}`);\n }\n\n /**\n * Tidy the library (remove unused/old revisions)\n * @returns {Promise<void>}\n */\n async tidyLibrary() {\n await this.post('/library/tidy');\n }\n\n // ── Playlist CRUD (#35) ────────────────────────────────────────────\n\n /**\n * List playlists\n * @param {Object} [filters] - Filters (playlistId, name, etc.)\n * @returns {Promise<Array>}\n */\n async listPlaylists(filters = {}) {\n return this._listRequest('/playlist', filters);\n }\n\n /**\n * Create a playlist\n * @param {string} name\n * @returns {Promise<Object>}\n */\n async createPlaylist(name) {\n return this.post('/playlist', { name });\n }\n\n /**\n * Get a single playlist by ID\n * @param {number} playlistId\n * @returns {Promise<Object>}\n */\n async getPlaylist(playlistId) {\n return this.get(`/playlist/${playlistId}`);\n }\n\n /**\n * Edit playlist properties\n * @param {number} playlistId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editPlaylist(playlistId, params) {\n return this.put(`/playlist/${playlistId}`, params);\n }\n\n /**\n * Delete a playlist\n * @param {number} playlistId\n * @returns {Promise<void>}\n */\n async deletePlaylist(playlistId) {\n await this.del(`/playlist/${playlistId}`);\n }\n\n /**\n * Reorder widgets in a playlist\n * @param {number} playlistId\n * @param {number[]} widgetIds - Ordered widget IDs\n * @returns {Promise<void>}\n */\n async reorderPlaylist(playlistId, widgetIds) {\n await this.ensureToken();\n const url = `${this.baseUrl}/api/playlist/order/${playlistId}`;\n const urlParams = new URLSearchParams();\n for (const id of widgetIds) {\n urlParams.append('widgets[]', String(id));\n }\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n body: urlParams\n });\n if (!response.ok) {\n const text = await response.text();\n throw new CmsApiError('POST', `/playlist/order/${playlistId}`, response.status, text);\n }\n }\n\n /**\n * Copy a playlist\n * @param {number} playlistId\n * @returns {Promise<Object>} Copied playlist\n */\n async copyPlaylist(playlistId) {\n return this.post(`/playlist/copy/${playlistId}`);\n }\n\n // ── Widget Extras (#37) ────────────────────────────────────────────\n\n /**\n * Set transition for a widget\n * @param {number} widgetId\n * @param {string} type - Transition type (e.g. 'fly', 'fade')\n * @param {Object} [config] - Transition config (duration, direction)\n * @returns {Promise<Object>}\n */\n async setWidgetTransition(widgetId, type, config = {}) {\n return this.put(`/playlist/widget/transition/${widgetId}`, { type, ...config });\n }\n\n /**\n * Set audio for a widget\n * @param {number} widgetId\n * @param {Object} params - { mediaId, volume, loop }\n * @returns {Promise<Object>}\n */\n async setWidgetAudio(widgetId, params) {\n return this.put(`/playlist/widget/${widgetId}/audio`, params);\n }\n\n /**\n * Remove audio from a widget\n * @param {number} widgetId\n * @returns {Promise<void>}\n */\n async removeWidgetAudio(widgetId) {\n await this.del(`/playlist/widget/${widgetId}/audio`);\n }\n\n /**\n * Set expiry dates for a widget\n * @param {number} widgetId\n * @param {Object} params - { fromDt, toDt, deleteOnExpiry }\n * @returns {Promise<Object>}\n */\n async setWidgetExpiry(widgetId, params) {\n return this.put(`/playlist/widget/${widgetId}/expiry`, params);\n }\n\n // ── Template Save / Manage (#39) ───────────────────────────────────\n\n /**\n * Save a layout as a template\n * @param {number} layoutId\n * @param {Object} params - { name, description, includeWidgets }\n * @returns {Promise<Object>}\n */\n async saveAsTemplate(layoutId, params) {\n return this.post(`/template/${layoutId}`, params);\n }\n\n /**\n * Get a single template by ID\n * @param {number} templateId\n * @returns {Promise<Object>}\n */\n async getTemplate(templateId) {\n return this.get(`/template/${templateId}`);\n }\n\n /**\n * Delete a template\n * @param {number} templateId\n * @returns {Promise<void>}\n */\n async deleteTemplate(templateId) {\n await this.del(`/template/${templateId}`);\n }\n\n // ── Dataset CRUD (#28) ─────────────────────────────────────────────\n\n /**\n * List datasets\n * @param {Object} [filters] - Filters (dataSetId, dataSet)\n * @returns {Promise<Array>}\n */\n async listDatasets(filters = {}) {\n return this._listRequest('/dataset', filters);\n }\n\n /**\n * Create a dataset\n * @param {Object} params - { dataSet, description }\n * @returns {Promise<Object>}\n */\n async createDataset(params) {\n return this.post('/dataset', params);\n }\n\n /**\n * Edit a dataset\n * @param {number} dataSetId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editDataset(dataSetId, params) {\n return this.put(`/dataset/${dataSetId}`, params);\n }\n\n /**\n * Delete a dataset\n * @param {number} dataSetId\n * @returns {Promise<void>}\n */\n async deleteDataset(dataSetId) {\n await this.del(`/dataset/${dataSetId}`);\n }\n\n /**\n * List columns in a dataset\n * @param {number} dataSetId\n * @returns {Promise<Array>}\n */\n async listDatasetColumns(dataSetId) {\n return this._listRequest(`/dataset/${dataSetId}/column`);\n }\n\n /**\n * Create a column in a dataset\n * @param {number} dataSetId\n * @param {Object} params - { heading, dataTypeId, dataSetColumnTypeId, listContent, ... }\n * @returns {Promise<Object>}\n */\n async createDatasetColumn(dataSetId, params) {\n return this.post(`/dataset/${dataSetId}/column`, params);\n }\n\n /**\n * Edit a dataset column\n * @param {number} dataSetId\n * @param {number} columnId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editDatasetColumn(dataSetId, columnId, params) {\n return this.put(`/dataset/${dataSetId}/column/${columnId}`, params);\n }\n\n /**\n * Delete a dataset column\n * @param {number} dataSetId\n * @param {number} columnId\n * @returns {Promise<void>}\n */\n async deleteDatasetColumn(dataSetId, columnId) {\n await this.del(`/dataset/${dataSetId}/column/${columnId}`);\n }\n\n /**\n * List rows (data) in a dataset\n * @param {number} dataSetId\n * @param {Object} [filters] - Filters (page, length)\n * @returns {Promise<Array>}\n */\n async listDatasetData(dataSetId, filters = {}) {\n return this._listRequest(`/dataset/data/${dataSetId}`, filters);\n }\n\n /**\n * Add a row to a dataset\n * @param {number} dataSetId\n * @param {Object} rowData - Column heading → value pairs\n * @returns {Promise<Object>}\n */\n async addDatasetRow(dataSetId, rowData) {\n return this.post(`/dataset/data/${dataSetId}`, rowData);\n }\n\n /**\n * Edit a dataset row\n * @param {number} dataSetId\n * @param {number} rowId\n * @param {Object} rowData - Column heading → value pairs\n * @returns {Promise<Object>}\n */\n async editDatasetRow(dataSetId, rowId, rowData) {\n return this.put(`/dataset/data/${dataSetId}/${rowId}`, rowData);\n }\n\n /**\n * Delete a dataset row\n * @param {number} dataSetId\n * @param {number} rowId\n * @returns {Promise<void>}\n */\n async deleteDatasetRow(dataSetId, rowId) {\n await this.del(`/dataset/data/${dataSetId}/${rowId}`);\n }\n\n /**\n * Import CSV data into a dataset\n * @param {number} dataSetId\n * @param {FormData} formData - Must include CSV file\n * @returns {Promise<Object>}\n */\n async importDatasetCsv(dataSetId, formData) {\n return this.requestMultipart('POST', `/dataset/import/${dataSetId}`, formData);\n }\n\n /**\n * Clear all data from a dataset\n * @param {number} dataSetId\n * @returns {Promise<void>}\n */\n async clearDataset(dataSetId) {\n await this.del(`/dataset/data/${dataSetId}`);\n }\n\n // ── Notification CRUD (#29) ────────────────────────────────────────\n\n /**\n * List notifications\n * @param {Object} [filters] - Filters (notificationId, subject)\n * @returns {Promise<Array>}\n */\n async listNotifications(filters = {}) {\n return this._listRequest('/notification', filters);\n }\n\n /**\n * Create a notification\n * @param {Object} params - { subject, body, isEmail, isInterrupt, displayGroupIds, ... }\n * @returns {Promise<Object>}\n */\n async createNotification(params) {\n return this.post('/notification', params);\n }\n\n /**\n * Edit a notification\n * @param {number} notificationId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editNotification(notificationId, params) {\n return this.put(`/notification/${notificationId}`, params);\n }\n\n /**\n * Delete a notification\n * @param {number} notificationId\n * @returns {Promise<void>}\n */\n async deleteNotification(notificationId) {\n await this.del(`/notification/${notificationId}`);\n }\n\n // ── Folder CRUD (#30) ─────────────────────────────────────────────\n\n /**\n * List folders\n * @param {Object} [filters] - Filters (folderId, text)\n * @returns {Promise<Array>}\n */\n async listFolders(filters = {}) {\n return this._listRequest('/folder', filters);\n }\n\n /**\n * Create a folder\n * @param {Object} params - { text, parentId }\n * @returns {Promise<Object>}\n */\n async createFolder(params) {\n return this.post('/folder', params);\n }\n\n /**\n * Edit a folder\n * @param {number} folderId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editFolder(folderId, params) {\n return this.put(`/folder/${folderId}`, params);\n }\n\n /**\n * Delete a folder\n * @param {number} folderId\n * @returns {Promise<void>}\n */\n async deleteFolder(folderId) {\n await this.del(`/folder/${folderId}`);\n }\n\n // ── Tag CRUD + Entity Tagging (#31) ────────────────────────────────\n\n /**\n * List tags\n * @param {Object} [filters] - Filters (tagId, tag)\n * @returns {Promise<Array>}\n */\n async listTags(filters = {}) {\n return this._listRequest('/tag', filters);\n }\n\n /**\n * Create a tag\n * @param {Object} params - { tag }\n * @returns {Promise<Object>}\n */\n async createTag(params) {\n return this.post('/tag', params);\n }\n\n /**\n * Edit a tag\n * @param {number} tagId\n * @param {Object} params\n * @returns {Promise<Object>}\n */\n async editTag(tagId, params) {\n return this.put(`/tag/${tagId}`, params);\n }\n\n /**\n * Delete a tag\n * @param {number} tagId\n * @returns {Promise<void>}\n */\n async deleteTag(tagId) {\n await this.del(`/tag/${tagId}`);\n }\n\n /**\n * Tag an entity (layout, media, campaign, etc.)\n * @param {string} entity - Entity type (layout, media, campaign, displaygroup, playlist)\n * @param {number} id - Entity ID\n * @param {string[]} tags - Tag names\n * @returns {Promise<void>}\n */\n async tagEntity(entity, id, tags) {\n await this.post(`/${entity}/${id}/tag`, { tag: tags.join(',') });\n }\n\n /**\n * Remove tags from an entity\n * @param {string} entity - Entity type\n * @param {number} id - Entity ID\n * @param {string[]} tags - Tag names to remove\n * @returns {Promise<void>}\n */\n async untagEntity(entity, id, tags) {\n await this.post(`/${entity}/${id}/untag`, { tag: tags.join(',') });\n }\n\n // ── DisplayGroup Actions (#32) ─────────────────────────────────────\n\n /**\n * Change the layout on a display group (immediate override)\n * @param {number} displayGroupId\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async dgChangeLayout(displayGroupId, layoutId) {\n await this.post(`/displaygroup/${displayGroupId}/action/changeLayout`, { layoutId });\n }\n\n /**\n * Overlay a layout on a display group\n * @param {number} displayGroupId\n * @param {number} layoutId\n * @returns {Promise<void>}\n */\n async dgOverlayLayout(displayGroupId, layoutId) {\n await this.post(`/displaygroup/${displayGroupId}/action/overlayLayout`, { layoutId });\n }\n\n /**\n * Revert a display group to its scheduled content\n * @param {number} displayGroupId\n * @returns {Promise<void>}\n */\n async dgRevertToSchedule(displayGroupId) {\n await this.post(`/displaygroup/${displayGroupId}/action/revertToSchedule`);\n }\n\n /**\n * Trigger immediate content collection on a display group\n * @param {number} displayGroupId\n * @returns {Promise<void>}\n */\n async dgCollectNow(displayGroupId) {\n await this.post(`/displaygroup/${displayGroupId}/action/collectNow`);\n }\n\n /**\n * Send a command to a display group\n * @param {number} displayGroupId\n * @param {number} commandId\n * @returns {Promise<void>}\n */\n async dgSendCommand(displayGroupId, commandId) {\n await this.post(`/displaygroup/${displayGroupId}/action/command`, { commandId });\n }\n\n /**\n * Edit display group properties\n * @param {number} displayGroupId\n * @param {Object} params - Properties to update\n * @returns {Promise<Object>}\n */\n async editDisplayGroup(displayGroupId, params) {\n return this.put(`/displaygroup/${displayGroupId}`, params);\n }\n}\n\n/**\n * Structured error for CMS API failures\n */\nexport class CmsApiError extends Error {\n constructor(method, path, status, detail) {\n super(`CMS API ${method} ${path} → ${status}: ${detail}`);\n this.name = 'CmsApiError';\n this.method = method;\n this.path = path;\n this.status = status;\n this.detail = detail;\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n// @xiboplayer/utils - Shared utilities\nimport pkg from '../package.json' with { type: 'json' };\nexport const VERSION = pkg.version;\nexport { createLogger, setLogLevel, getLogLevel, isDebug, applyCmsLogLevel, mapCmsLogLevel, registerLogSink, unregisterLogSink, LOG_LEVELS } from './logger.js';\nexport { EventEmitter } from './event-emitter.js';\nimport { config as _config } from './config.js';\nexport { config, SHELL_ONLY_KEYS, extractPwaConfig, computeCmsId, warnPlatformMismatch } from './config.js';\nexport { fetchWithRetry } from './fetch-retry.js';\nexport { openIDB, queryByIndex, deleteByIds } from './idb.js';\nexport { CmsApiClient, CmsApiError } from './cms-api.js';\n\n/**\n * CMS Player API base path — all media, dependencies, and widgets are served\n * under this prefix.\n *\n * Default: '/player/api/v2' (standalone index.php endpoint).\n * Override: set `playerApiBase` in config.json / localStorage, or call\n * setPlayerApi('/new/path') before route registration (proxy).\n *\n * Browser: reads from config.data.playerApiBase at import time.\n * Node: call setPlayerApi() before createProxyApp().\n */\nconst DEFAULT_PLAYER_API = '/player/api/v2';\nlet _playerApi = _config.data?.playerApiBase || DEFAULT_PLAYER_API;\n\n/** Current Player API base path (no trailing slash). */\nexport let PLAYER_API = _playerApi;\n\n/** Override the Player API base path at runtime (call before route registration). */\nexport function setPlayerApi(base) {\n _playerApi = base.replace(/\\/+$/, '');\n PLAYER_API = _playerApi;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * FILE_TYPES — centralized download behavior per file type.\n *\n * Each type declares retry strategy, HEAD skip, and cache TTL.\n * Used by DownloadTask/FileDownload instead of ad-hoc isGetData checks.\n */\n\nexport const FILE_TYPES = {\n media: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n layout: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n dataset: { maxRetries: 4, retryDelayMs: 0,\n retryDelays: [15_000, 30_000, 60_000, 120_000],\n maxReenqueues: 5, reenqueueDelayMs: 60_000,\n skipHead: true, cacheTtl: 300 },\n static: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n};\n\nexport function getFileTypeConfig(type) {\n return FILE_TYPES[type] || FILE_TYPES.media;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * DownloadManager - Flat queue download orchestration\n *\n * Works in both browser and Service Worker contexts.\n * Handles download queue, concurrency control, parallel chunks, and MD5 verification.\n *\n * Architecture (flat queue):\n * - DownloadTask: Single HTTP fetch unit (one GET request — full file or one chunk)\n * - FileDownload: Orchestrator that creates DownloadTasks for a file (HEAD + chunks)\n * - DownloadQueue: Flat queue where every download unit competes equally for connection slots\n * - DownloadManager: Public facade\n *\n * BEFORE: Queue[File, File, File] → each File internally spawns N chunk fetches\n * AFTER: Queue[chunk, chunk, file, chunk, chunk, file, chunk] → flat, 1 fetch per slot\n *\n * This eliminates the two-layer concurrency problem where N files × M chunks per file\n * could exceed Chromium's 6-per-host connection limit, causing head-of-line blocking.\n *\n * Per-file chunk limit (maxChunksPerFile) prevents one large file from hogging all\n * connection slots, ensuring bandwidth is shared fairly and chunk 0 arrives fast.\n *\n * Usage:\n * const dm = new DownloadManager({ concurrency: 6, chunkSize: 50MB, chunksPerFile: 2 });\n * const file = dm.enqueue({ id, type, path, md5 });\n * const blob = await file.wait();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { getFileTypeConfig } from './file-types.js';\n\nconst log = createLogger('Download');\nconst DEFAULT_CONCURRENCY = 6; // Max concurrent HTTP connections (matches Chromium per-host limit)\nconst DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; // 50MB chunks\nconst DEFAULT_MAX_CHUNKS_PER_FILE = 3; // Max parallel chunk downloads per file\nconst CHUNK_THRESHOLD = 100 * 1024 * 1024; // Files > 100MB get chunked\nconst URGENT_CONCURRENCY = 2; // Slots when urgent chunk is active (bandwidth focus)\nconst FETCH_TIMEOUT_MS = 600_000; // 10 minutes — 100MB chunk at ~2 Mbps\nconst HEAD_TIMEOUT_MS = 15_000; // 15 seconds for HEAD requests\n\n/**\n * Infer Content-Type from file path extension.\n * Used when we skip HEAD (size already known from RequiredFiles).\n */\nfunction inferContentType(fileInfo) {\n const path = fileInfo.path || fileInfo.code || '';\n const ext = path.split('.').pop()?.split('?')[0]?.toLowerCase();\n const types = {\n mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg',\n png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',\n gif: 'image/gif', svg: 'image/svg+xml', webp: 'image/webp',\n css: 'text/css', js: 'application/javascript',\n ttf: 'font/ttf', otf: 'font/otf', woff: 'font/woff', woff2: 'font/woff2',\n xml: 'application/xml', xlf: 'application/xml',\n };\n return types[ext] || 'application/octet-stream';\n}\n\n// Priority levels — higher number = starts first\nexport const PRIORITY = { normal: 0, layout: 1, high: 2, urgent: 3 };\n\n/**\n * BARRIER sentinel — hard gate in the download queue.\n *\n * When processQueue() encounters a BARRIER:\n * - If tasks are still in-flight above it → STOP (slots stay empty)\n * - If running === 0 → remove barrier, continue with tasks below\n *\n * Used by LayoutQueueBuilder to separate critical chunks (chunk-0, chunk-last)\n * from remaining bulk chunks. Ensures video playback can start before all\n * chunks finish downloading.\n */\nexport const BARRIER = Symbol('BARRIER');\n\n/**\n * Compute the expiry of an AWS signed URL from X-Amz-Date + X-Amz-Expires.\n * X-Amz-Expires is a duration in seconds (not an absolute timestamp).\n * Returns the expiry as a Unix timestamp (seconds), or Infinity if not found.\n */\nfunction getUrlExpiry(url) {\n try {\n const u = new URL(url, 'http://localhost');\n const amzDate = u.searchParams.get('X-Amz-Date');\n const amzExpires = u.searchParams.get('X-Amz-Expires');\n if (amzDate && amzExpires) {\n // X-Amz-Date is ISO-like: 20240101T000000Z\n const dateStr = amzDate.replace(/(\\d{4})(\\d{2})(\\d{2})T(\\d{2})(\\d{2})(\\d{2})Z/, '$1-$2-$3T$4:$5:$6Z');\n const signedAt = new Date(dateStr).getTime() / 1000;\n if (isNaN(signedAt)) return Infinity;\n return signedAt + parseInt(amzExpires, 10);\n }\n return Infinity;\n } catch (_) {\n return Infinity;\n }\n}\n\n/**\n * Check if a signed URL has expired (or will expire within a grace period).\n * @param {string} url - Signed URL with X-Amz-Expires parameter\n * @param {number} graceSeconds - Seconds before actual expiry to consider it expired (default: 30)\n * @returns {boolean}\n */\nexport function isUrlExpired(url, graceSeconds = 30) {\n const expiry = getUrlExpiry(url);\n if (expiry === Infinity) return false;\n return (Date.now() / 1000) >= (expiry - graceSeconds);\n}\n\n\n/**\n * DownloadTask - Single HTTP fetch unit\n *\n * Handles exactly one HTTP request: either a full small file GET or a single Range GET\n * for one chunk of a larger file. Includes retry logic with exponential backoff.\n */\nexport class DownloadTask {\n constructor(fileInfo, options = {}) {\n this.fileInfo = fileInfo;\n this.chunkIndex = options.chunkIndex ?? null;\n this.rangeStart = options.rangeStart ?? null;\n this.rangeEnd = options.rangeEnd ?? null;\n this.state = 'pending';\n this.blob = null;\n this._parentFile = null;\n this._priority = PRIORITY.normal;\n this._typeConfig = getFileTypeConfig(fileInfo.type);\n }\n\n getUrl() {\n const url = this.fileInfo.path;\n if (isUrlExpired(url)) {\n throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);\n }\n return url;\n }\n\n async start() {\n this.state = 'downloading';\n const headers = {};\n if (this.rangeStart != null) {\n headers['Range'] = `bytes=${this.rangeStart}-${this.rangeEnd}`;\n }\n // Pass chunk metadata and MD5 via custom headers for cache-through proxy\n if (this.chunkIndex != null) {\n headers['X-Store-Chunk-Index'] = String(this.chunkIndex);\n if (this._parentFile) {\n headers['X-Store-Num-Chunks'] = String(this._parentFile.totalChunks);\n headers['X-Store-Chunk-Size'] = String(this._parentFile.options.chunkSize || 104857600);\n }\n }\n if (this.fileInfo.md5) {\n headers['X-Store-MD5'] = this.fileInfo.md5;\n }\n if (this.fileInfo.updateInterval) {\n headers['X-Cache-TTL'] = String(this.fileInfo.updateInterval);\n }\n if (this.fileInfo.cmsDownloadUrl) {\n headers['X-Cms-Download-Url'] = this.fileInfo.cmsDownloadUrl;\n }\n\n const maxRetries = this._typeConfig.maxRetries;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);\n try {\n const url = this.getUrl();\n const fetchOpts = { signal: ac.signal };\n if (Object.keys(headers).length > 0) fetchOpts.headers = headers;\n const response = await fetch(url, fetchOpts);\n\n if (!response.ok && response.status !== 206) {\n throw new Error(`Fetch failed: ${response.status}`);\n }\n\n this.blob = await response.blob();\n this.state = 'complete';\n return this.blob;\n\n } catch (error) {\n const msg = ac.signal.aborted ? `Timeout after ${FETCH_TIMEOUT_MS / 1000}s` : error.message;\n if (attempt < maxRetries) {\n const delay = this._typeConfig.retryDelays?.[attempt - 1]\n ?? this._typeConfig.retryDelayMs * attempt;\n const chunkLabel = this.chunkIndex != null ? ` chunk ${this.chunkIndex}` : '';\n log.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${chunkLabel} attempt ${attempt}/${maxRetries} failed: ${msg}. Retrying in ${delay / 1000}s...`);\n await new Promise(resolve => setTimeout(resolve, delay));\n } else {\n this.state = 'failed';\n throw ac.signal.aborted ? new Error(msg) : error;\n }\n } finally {\n clearTimeout(timer);\n }\n }\n }\n}\n\n/**\n * FileDownload - Orchestrates downloading a single file\n *\n * Does the HEAD request to determine file size, then:\n * - Small file (≤ 100MB): creates 1 DownloadTask for the full file\n * - Large file (> 100MB): creates N DownloadTasks, one per chunk\n *\n * All tasks are enqueued into the flat DownloadQueue where they compete\n * equally for HTTP connection slots with tasks from other files.\n *\n * Provides wait() that resolves when ALL tasks for this file complete.\n * Supports progressive caching via onChunkDownloaded callback.\n */\nexport class FileDownload {\n constructor(fileInfo, options = {}) {\n this.fileInfo = fileInfo;\n this.options = options;\n this.state = 'pending';\n this.tasks = [];\n this.completedChunks = 0;\n this.totalChunks = 0;\n this.totalBytes = 0;\n this.downloadedBytes = 0;\n this.onChunkDownloaded = null;\n this.skipChunks = fileInfo.skipChunks || new Set();\n this._contentType = 'application/octet-stream';\n this._chunkBlobs = new Map();\n this._runningCount = 0; // Currently running tasks for this file\n this._resolve = null;\n this._reject = null;\n this._promise = new Promise((res, rej) => {\n this._resolve = res;\n this._reject = rej;\n });\n this._promise.catch(() => {});\n }\n\n getUrl() {\n const url = this.fileInfo.path;\n if (isUrlExpired(url)) {\n throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);\n }\n return url;\n }\n\n wait() {\n return this._promise;\n }\n\n /**\n * Determine file size and create DownloadTasks.\n * Uses RequiredFiles size when available (instant, no network).\n * Falls back to HEAD request only when size is unknown.\n */\n async prepare(queue) {\n try {\n this.state = 'preparing';\n const { id, type, size } = this.fileInfo;\n log.info('[FileDownload] Starting:', `${type}/${id}`);\n\n // Use declared size from RequiredFiles — no HEAD needed for queue building\n this.totalBytes = (size && size > 0) ? parseInt(size) : 0;\n this._contentType = inferContentType(this.fileInfo);\n\n // Skip HEAD for types that declare skipHead (e.g. datasets — dynamic API endpoints).\n // These generate responses server-side; HEAD triggers the full handler for nothing\n // and may fail if the CMS cache isn't warm yet. They're always small, never chunked.\n const skipHead = getFileTypeConfig(this.fileInfo.type).skipHead;\n\n if (this.totalBytes === 0 && !skipHead) {\n // No size declared — HEAD fallback (rare: only for files without CMS size)\n const url = this.getUrl();\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), HEAD_TIMEOUT_MS);\n try {\n const head = await fetch(url, { method: 'HEAD', signal: ac.signal });\n if (head.ok) {\n this.totalBytes = parseInt(head.headers.get('Content-Length') || '0');\n this._contentType = head.headers.get('Content-Type') || this._contentType;\n }\n } finally {\n clearTimeout(timer);\n }\n }\n\n log.info('[FileDownload] File size:', (this.totalBytes / 1024 / 1024).toFixed(1), 'MB');\n\n const chunkSize = this.options.chunkSize || DEFAULT_CHUNK_SIZE;\n\n if (this.totalBytes > CHUNK_THRESHOLD) {\n const ranges = [];\n for (let start = 0; start < this.totalBytes; start += chunkSize) {\n ranges.push({\n start,\n end: Math.min(start + chunkSize - 1, this.totalBytes - 1),\n index: ranges.length\n });\n }\n this.totalChunks = ranges.length;\n\n const needed = ranges.filter(r => !this.skipChunks.has(r.index));\n const skippedCount = ranges.length - needed.length;\n\n for (const r of ranges) {\n if (this.skipChunks.has(r.index)) {\n this.downloadedBytes += (r.end - r.start + 1);\n }\n }\n\n if (needed.length === 0) {\n log.info('[FileDownload] All chunks already cached, nothing to download');\n this.state = 'complete';\n this._resolve(new Blob([], { type: this._contentType }));\n return;\n }\n\n if (skippedCount > 0) {\n log.info(`[FileDownload] Resuming: ${skippedCount} chunks cached, ${needed.length} to download`);\n }\n\n const isResume = skippedCount > 0;\n\n if (isResume) {\n const sorted = needed.sort((a, b) => a.index - b.index);\n for (const r of sorted) {\n const task = new DownloadTask(this.fileInfo, {\n chunkIndex: r.index, rangeStart: r.start, rangeEnd: r.end\n });\n task._parentFile = this;\n task._priority = PRIORITY.normal;\n this.tasks.push(task);\n }\n } else {\n for (const r of needed) {\n const task = new DownloadTask(this.fileInfo, {\n chunkIndex: r.index, rangeStart: r.start, rangeEnd: r.end\n });\n task._parentFile = this;\n task._priority = (r.index === 0 || r.index === ranges.length - 1) ? PRIORITY.high : PRIORITY.normal;\n this.tasks.push(task);\n }\n }\n\n const highCount = this.tasks.filter(t => t._priority >= PRIORITY.high).length;\n log.info(`[FileDownload] ${type}/${id}: ${this.tasks.length} chunks` +\n (highCount > 0 ? ` (${highCount} priority)` : '') +\n (isResume ? ' (resume)' : ''));\n\n } else {\n this.totalChunks = 1;\n const task = new DownloadTask(this.fileInfo, {});\n task._parentFile = this;\n this.tasks.push(task);\n }\n\n queue.enqueueChunkTasks(this.tasks);\n this.state = 'downloading';\n\n } catch (error) {\n log.error('[FileDownload] Prepare failed:', `${this.fileInfo.type}/${this.fileInfo.id}`, error);\n this.state = 'failed';\n this._reject(error);\n }\n }\n\n async onTaskComplete(task) {\n this.completedChunks++;\n this.downloadedBytes += task.blob.size;\n\n if (task.chunkIndex != null) {\n this._chunkBlobs.set(task.chunkIndex, task.blob);\n }\n\n if (this.options.onProgress) {\n this.options.onProgress(this.downloadedBytes, this.totalBytes);\n }\n\n // Fire progressive chunk callback\n if (this.onChunkDownloaded && task.chunkIndex != null) {\n try {\n await this.onChunkDownloaded(task.chunkIndex, task.blob, this.totalChunks);\n } catch (e) {\n log.warn('[FileDownload] onChunkDownloaded callback error:', e);\n }\n }\n\n if (this.completedChunks === this.tasks.length && this.state !== 'complete') {\n this.state = 'complete';\n const { type, id } = this.fileInfo;\n\n if (task.chunkIndex == null) {\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(${task.blob.size} bytes)`);\n this._resolve(task.blob);\n } else if (this.onChunkDownloaded) {\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(progressive, ${this.totalChunks} chunks)`);\n this._resolve(new Blob([], { type: this._contentType }));\n } else {\n const ordered = [];\n for (let i = 0; i < this.totalChunks; i++) {\n const blob = this._chunkBlobs.get(i);\n if (blob) ordered.push(blob);\n }\n const assembled = new Blob(ordered, { type: this._contentType });\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(${assembled.size} bytes, reassembled)`);\n this._resolve(assembled);\n }\n\n this._chunkBlobs.clear();\n }\n }\n\n onTaskFailed(task, error) {\n if (this.state === 'complete' || this.state === 'failed') return;\n\n // URL expiration is transient — drop this task, don't fail the file.\n // Already-downloaded chunks are safe in cache. Next collection cycle\n // provides fresh URLs and the resume logic (skipChunks) fills the gaps.\n if (error.message?.includes('URL expired')) {\n const chunkLabel = task.chunkIndex != null ? ` chunk ${task.chunkIndex}` : '';\n log.warn(`[FileDownload] URL expired, dropping${chunkLabel}:`, `${this.fileInfo.type}/${this.fileInfo.id}`);\n this.tasks = this.tasks.filter(t => t !== task);\n // If all remaining tasks completed, resolve as partial\n if (this.tasks.length === 0 || this.completedChunks >= this.tasks.length) {\n this.state = 'complete';\n this._urlExpired = true;\n this._resolve(new Blob([], { type: this._contentType }));\n }\n return;\n }\n\n log.error('[FileDownload] Failed:', `${this.fileInfo.type}/${this.fileInfo.id}`, error);\n this.state = 'failed';\n this._reject(error);\n }\n}\n\n/**\n * LayoutTaskBuilder — Smart builder that produces a sorted, barrier-embedded\n * task list for a single layout.\n *\n * Usage:\n * const builder = new LayoutTaskBuilder(queue);\n * builder.addFile(fileInfo);\n * const orderedTasks = await builder.build();\n * queue.enqueueOrderedTasks(orderedTasks);\n *\n * The builder runs HEAD requests (throttled), collects the resulting\n * DownloadTasks, sorts them optimally, and embeds BARRIERs between\n * critical chunks (chunk-0, chunk-last) and bulk chunks.\n *\n * Duck-typing: implements enqueueChunkTasks() so FileDownload.prepare()\n * works unchanged — it just collects tasks instead of processing them.\n */\nexport class LayoutTaskBuilder {\n constructor(queue) {\n this.queue = queue; // Main DownloadQueue (for dedup via active map)\n this._filesToPrepare = []; // FileDownloads needing HEAD requests\n this._tasks = []; // Collected DownloadTasks (from prepare callbacks)\n this._maxPreparing = 2; // HEAD request throttle\n }\n\n /**\n * Register a file. Uses queue.active for dedup/URL refresh.\n * Does NOT trigger prepare — that happens in build().\n */\n addFile(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.queue.active.has(key)) {\n const existing = this.queue.active.get(key);\n // URL refresh (same logic as queue.enqueue)\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.queue.chunkSize,\n calculateMD5: this.queue.calculateMD5,\n onProgress: this.queue.onProgress\n });\n\n this.queue.active.set(key, file);\n this._filesToPrepare.push(file);\n return file;\n }\n\n /**\n * Duck-type interface for FileDownload.prepare().\n * Collects tasks instead of processing them.\n */\n enqueueChunkTasks(tasks) {\n this._tasks.push(...tasks);\n }\n\n /**\n * Run all HEAD requests (throttled) and return sorted tasks with barriers.\n */\n async build() {\n await this._prepareAll();\n return this._sortWithBarriers();\n }\n\n async _prepareAll() {\n await new Promise((resolve) => {\n let running = 0;\n let idx = 0;\n const next = () => {\n while (running < this._maxPreparing && idx < this._filesToPrepare.length) {\n const file = this._filesToPrepare[idx++];\n running++;\n file.prepare(this).finally(() => {\n running--;\n if (idx >= this._filesToPrepare.length && running === 0) {\n resolve();\n } else {\n next();\n }\n });\n }\n };\n if (this._filesToPrepare.length === 0) resolve();\n else next();\n });\n }\n\n _sortWithBarriers() {\n const nonChunked = [];\n const chunk0s = [];\n const chunkLasts = [];\n const remaining = [];\n\n for (const t of this._tasks) {\n if (t.chunkIndex == null) {\n nonChunked.push(t);\n } else if (t.chunkIndex === 0) {\n chunk0s.push(t);\n } else {\n const total = t._parentFile?.totalChunks || 0;\n if (total > 1 && t.chunkIndex === total - 1) {\n chunkLasts.push(t);\n } else {\n remaining.push(t);\n }\n }\n }\n\n nonChunked.sort((a, b) => (a._parentFile?.totalBytes || 0) - (b._parentFile?.totalBytes || 0));\n remaining.sort((a, b) => a.chunkIndex - b.chunkIndex);\n\n // Build: small files + critical chunks → BARRIER → bulk chunks\n const result = [...nonChunked, ...chunk0s, ...chunkLasts];\n if (remaining.length > 0) {\n result.push(BARRIER, ...remaining);\n }\n return result;\n }\n}\n\n/**\n * DownloadQueue - Flat queue with per-file and global concurrency limits\n *\n * Global concurrency limit (e.g., 6) controls total HTTP connections.\n * Per-file chunk limit (e.g., 2) prevents one large file from hogging all\n * connections, ensuring bandwidth per chunk is high and chunk 0 arrives fast.\n * HEAD requests are throttled to avoid flooding browser connection pool.\n */\nexport class DownloadQueue {\n constructor(options = {}) {\n this.concurrency = options.concurrency || DEFAULT_CONCURRENCY;\n this.chunkSize = options.chunkSize || DEFAULT_CHUNK_SIZE;\n this.maxChunksPerFile = options.chunksPerFile || DEFAULT_MAX_CHUNKS_PER_FILE;\n this.calculateMD5 = options.calculateMD5;\n this.onProgress = options.onProgress;\n\n this.queue = []; // DownloadTask[] — flat queue of chunk/file tasks\n this.active = new Map(); // stableKey → FileDownload\n this._activeTasks = []; // DownloadTask[] — currently in-flight tasks\n this.running = 0;\n\n // HEAD request throttling: prevents prepare() from flooding browser connections\n this._prepareQueue = [];\n this._preparingCount = 0;\n this._maxPreparing = 2; // Max concurrent HEAD requests\n\n // When paused, processQueue() is a no-op (used during barrier setup)\n this.paused = false;\n\n // Track getData re-enqueue timers so clear() can cancel them\n this._reenqueueTimers = new Set();\n }\n\n static stableKey(fileInfo) {\n return `${fileInfo.type}/${fileInfo.id}`;\n }\n\n enqueue(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.active.has(key)) {\n const existing = this.active.get(key);\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n log.info('[DownloadQueue] Refreshing URL for', key);\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.chunkSize,\n calculateMD5: this.calculateMD5,\n onProgress: this.onProgress\n });\n\n this.active.set(key, file);\n log.info('[DownloadQueue] Enqueued:', key);\n\n // Throttled prepare: HEAD requests are limited to avoid flooding connections\n this._schedulePrepare(file);\n\n return file;\n }\n\n /**\n * Schedule a FileDownload's prepare() with throttling.\n * Only N HEAD requests run concurrently to preserve connections for data transfers.\n */\n _schedulePrepare(file) {\n this._prepareQueue.push(file);\n this._processPrepareQueue();\n }\n\n _processPrepareQueue() {\n while (this._preparingCount < this._maxPreparing && this._prepareQueue.length > 0) {\n const file = this._prepareQueue.shift();\n this._preparingCount++;\n file.prepare(this).finally(() => {\n this._preparingCount--;\n this._processPrepareQueue();\n });\n }\n }\n\n enqueueChunkTasks(tasks) {\n for (const task of tasks) {\n this.queue.push(task);\n }\n this._sortQueue();\n\n log.info(`[DownloadQueue] ${tasks.length} tasks added (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /**\n * Enqueue a pre-ordered list of tasks (with optional BARRIER sentinels).\n * Preserves insertion order — no sorting. Position = priority.\n *\n * Used by LayoutQueueBuilder to push the entire download queue in layout\n * playback order with barriers separating critical chunks from bulk.\n *\n * @param {Array<DownloadTask|Symbol>} items - Tasks and BARRIERs in order\n */\n enqueueOrderedTasks(items) {\n let taskCount = 0;\n let barrierCount = 0;\n for (const item of items) {\n if (item === BARRIER) {\n this.queue.push(BARRIER);\n barrierCount++;\n } else {\n this.queue.push(item);\n taskCount++;\n }\n }\n\n log.info(`[DownloadQueue] Ordered queue: ${taskCount} tasks, ${barrierCount} barriers (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /** Sort queue by priority (highest first), stable within same priority. */\n _sortQueue() {\n this.queue.sort((a, b) => b._priority - a._priority);\n }\n\n /**\n * Boost priority for files needed by the current/next layout.\n * @param {Array} fileIds - Media IDs needed by the layout\n * @param {number} priority - Priority level (default: PRIORITY.high)\n */\n prioritizeLayoutFiles(fileIds, priority = PRIORITY.high) {\n const idSet = new Set(fileIds.map(String));\n\n let boosted = 0;\n for (const t of this.queue) {\n const matchValue = t._parentFile?.fileInfo.saveAs || String(t._parentFile?.fileInfo.id);\n if (idSet.has(matchValue) && t._priority < priority) {\n t._priority = priority;\n boosted++;\n }\n }\n for (const t of this._activeTasks) {\n const matchValue = t._parentFile?.fileInfo.saveAs || String(t._parentFile?.fileInfo.id);\n if (idSet.has(matchValue) && t._priority < priority) {\n t._priority = priority;\n }\n }\n this._sortQueue();\n\n log.info('[DownloadQueue] Layout files prioritized:', idSet.size, 'files,', boosted, 'tasks boosted to', priority);\n }\n\n /**\n * Emergency priority for a specific streaming chunk.\n * Called by the Service Worker when a video is stalled waiting for chunk N.\n * Sets urgent priority → queue re-sorts → processQueue() limits concurrency.\n */\n urgentChunk(fileType, fileId, chunkIndex) {\n const key = `${fileType}/${fileId}`;\n const file = this.active.get(key);\n\n if (!file) {\n log.info('[DownloadQueue] urgentChunk: file not active:', key, 'chunk', chunkIndex);\n return false;\n }\n\n // Already in-flight — nothing to do\n const isActive = this._activeTasks.some(\n t => t._parentFile === file && t.chunkIndex === chunkIndex && t.state === 'downloading'\n );\n if (isActive) {\n // Mark the in-flight task as urgent so processQueue() limits concurrency\n const activeTask = this._activeTasks.find(\n t => t._parentFile === file && t.chunkIndex === chunkIndex\n );\n if (activeTask && activeTask._priority < PRIORITY.urgent) {\n activeTask._priority = PRIORITY.urgent;\n log.info(`[DownloadQueue] URGENT: ${key} chunk ${chunkIndex} (already in-flight, limiting slots)`);\n // Don't call processQueue() — can't stop in-flight tasks, but next\n // processQueue() call (when any task completes) will see hasUrgent\n // and limit new starts to URGENT_CONCURRENCY.\n return true;\n }\n log.info('[DownloadQueue] urgentChunk: already urgent:', key, 'chunk', chunkIndex);\n return false;\n }\n\n // Find task in queue (may be past a barrier)\n const idx = this.queue.findIndex(\n t => t !== BARRIER && t._parentFile === file && t.chunkIndex === chunkIndex\n );\n\n if (idx === -1) {\n log.info('[DownloadQueue] urgentChunk: chunk not in queue:', key, 'chunk', chunkIndex);\n return false;\n }\n\n const task = this.queue.splice(idx, 1)[0];\n task._priority = PRIORITY.urgent;\n // Move to front of queue (past any barriers)\n this.queue.unshift(task);\n\n log.info(`[DownloadQueue] URGENT: ${key} chunk ${chunkIndex} (moved to front)`);\n this.processQueue();\n return true;\n }\n\n /**\n * Process queue — barrier-aware loop.\n *\n * Supports two modes:\n * 1. Priority-sorted (legacy): queue sorted by priority, urgent reduces concurrency\n * 2. Barrier-ordered: queue contains BARRIER sentinels that act as hard gates\n *\n * BARRIER behavior:\n * - When processQueue() hits a BARRIER and running > 0 → STOP (slots stay empty)\n * - When running === 0 → remove barrier, continue with tasks below\n * - Tasks are never reordered past a BARRIER (except urgentChunk which bypasses)\n *\n * Urgent mode: when any task has PRIORITY.urgent, concurrency drops to\n * URGENT_CONCURRENCY so the stalled chunk gets maximum bandwidth.\n */\n processQueue() {\n if (this.paused) return;\n\n // Determine effective concurrency and minimum priority to start\n const hasUrgent = this.queue.some(t => t !== BARRIER && t._priority >= PRIORITY.urgent) ||\n this._activeTasks?.some(t => t._priority >= PRIORITY.urgent && t.state === 'downloading');\n const maxSlots = hasUrgent ? URGENT_CONCURRENCY : this.concurrency;\n const minPriority = hasUrgent ? PRIORITY.urgent : 0; // Urgent = only urgent tasks run\n\n // Fill slots from front of queue\n while (this.running < maxSlots && this.queue.length > 0) {\n const next = this.queue[0];\n\n // Hit a BARRIER — hard gate\n if (next === BARRIER) {\n if (this.running > 0) {\n break; // In-flight tasks still running — slots stay empty\n }\n // All above-barrier tasks done → raise barrier, continue\n this.queue.shift();\n continue;\n }\n\n // Per-file limit: skip to next eligible task (but don't cross barrier)\n if (next._priority < minPriority || !this._canStartTask(next)) {\n let found = false;\n for (let i = 1; i < this.queue.length; i++) {\n if (this.queue[i] === BARRIER) break; // Don't look past barrier\n const task = this.queue[i];\n if (task._priority >= minPriority && this._canStartTask(task)) {\n this.queue.splice(i, 1);\n this._startTask(task);\n found = true;\n break;\n }\n }\n if (!found) break;\n continue;\n }\n\n this.queue.shift();\n this._startTask(next);\n }\n\n if (this.queue.length === 0 && this.running === 0) {\n log.info('[DownloadQueue] All downloads complete');\n }\n }\n\n /**\n * Per-file concurrency check. Priority sorting decides order,\n * this just prevents one file from hogging all connections.\n */\n _canStartTask(task) {\n return task._parentFile._runningCount < this.maxChunksPerFile;\n }\n\n _startTask(task) {\n this.running++;\n task._parentFile._runningCount++;\n this._activeTasks.push(task);\n const key = `${task.fileInfo.type}/${task.fileInfo.id}`;\n const chunkLabel = task.chunkIndex != null ? ` chunk ${task.chunkIndex}` : '';\n log.info(`[DownloadQueue] Starting: ${key}${chunkLabel} (${this.running}/${this.concurrency} active)`);\n\n task.start()\n .then(() => {\n this.running--;\n task._parentFile._runningCount--;\n this._activeTasks = this._activeTasks.filter(t => t !== task);\n log.info(`[DownloadQueue] Fetched: ${key}${chunkLabel} (${this.running} active, ${this.queue.length} pending)`);\n this.processQueue();\n return task._parentFile.onTaskComplete(task);\n })\n .catch(err => {\n this.running--;\n task._parentFile._runningCount--;\n this._activeTasks = this._activeTasks.filter(t => t !== task);\n\n // Re-enqueueable types (e.g. datasets): defer re-enqueue instead of permanent failure.\n // CMS \"cache not ready\" resolves when the XTR task runs (30-120s).\n const { maxReenqueues, reenqueueDelayMs } = task._typeConfig;\n if (maxReenqueues > 0) {\n task._reenqueueCount = (task._reenqueueCount || 0) + 1;\n if (task._reenqueueCount > maxReenqueues) {\n log.error(`[DownloadQueue] ${key} exceeded ${maxReenqueues} re-enqueues, failing permanently`);\n this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n return;\n }\n log.warn(`[DownloadQueue] ${key} failed all retries (attempt ${task._reenqueueCount}/${maxReenqueues}), scheduling re-enqueue in ${reenqueueDelayMs / 1000}s`);\n const timerId = setTimeout(() => {\n this._reenqueueTimers.delete(timerId);\n task.state = 'pending';\n task._parentFile.state = 'downloading';\n this.queue.push(task);\n log.info(`[DownloadQueue] ${key} re-enqueued for retry`);\n this.processQueue();\n }, reenqueueDelayMs);\n this._reenqueueTimers.add(timerId);\n this.processQueue();\n return;\n }\n\n this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n });\n }\n\n removeCompleted(key) {\n const file = this.active.get(key);\n if (file && (file.state === 'complete' || file.state === 'failed')) {\n this.queue = this.queue.filter(t => t === BARRIER || t._parentFile !== file);\n this.active.delete(key);\n }\n }\n\n getTask(key) {\n return this.active.get(key) || null;\n }\n\n getProgress() {\n const progress = {};\n for (const [key, file] of this.active.entries()) {\n // Skip completed/failed — they stay in active until removeCompleted() runs\n if (file.state === 'complete' || file.state === 'failed') continue;\n progress[key] = {\n downloaded: file.downloadedBytes,\n total: file.totalBytes,\n percent: file.totalBytes > 0 ? (file.downloadedBytes / file.totalBytes * 100).toFixed(1) : 0,\n state: file.state\n };\n }\n return progress;\n }\n\n clear() {\n this.queue = [];\n this.active.clear();\n this.running = 0;\n this._prepareQueue = [];\n this._preparingCount = 0;\n // Cancel any pending getData re-enqueue timers\n for (const id of this._reenqueueTimers) clearTimeout(id);\n this._reenqueueTimers.clear();\n }\n}\n\n/**\n * DownloadManager - Main API\n */\nexport class DownloadManager {\n constructor(options = {}) {\n this.queue = new DownloadQueue(options);\n }\n\n enqueue(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n getTask(key) {\n return this.queue.getTask(key);\n }\n\n getProgress() {\n return this.queue.getProgress();\n }\n\n prioritizeLayoutFiles(fileIds, priority) {\n this.queue.prioritizeLayoutFiles(fileIds, priority);\n this.queue.processQueue();\n }\n\n urgentChunk(fileType, fileId, chunkIndex) {\n return this.queue.urgentChunk(fileType, fileId, chunkIndex);\n }\n\n createTaskBuilder() {\n return new LayoutTaskBuilder(this.queue);\n }\n\n enqueueOrderedTasks(tasks) {\n this.queue.enqueueOrderedTasks(tasks);\n }\n\n removeCompleted(key) {\n this.queue.removeCompleted(key);\n }\n\n get running() {\n return this.queue.running;\n }\n\n get queued() {\n return this.queue.queue.length;\n }\n\n clear() {\n this.queue.clear();\n }\n}\n","{\n \"name\": \"@xiboplayer/cache\",\n \"version\": \"0.7.23\",\n \"description\": \"Offline caching and download management with parallel chunk downloads\",\n \"type\": \"module\",\n \"main\": \"./src/index.js\",\n \"types\": \"./src/index.d.ts\",\n \"exports\": {\n \".\": \"./src/index.js\",\n \"./cache\": \"./src/cache.js\",\n \"./store-client\": \"./src/store-client.js\",\n \"./download-manager\": \"./src/download-manager.js\",\n \"./cache-analyzer\": \"./src/cache-analyzer.js\",\n \"./widget-html\": \"./src/widget-html.js\"\n },\n \"scripts\": {\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\"\n },\n \"dependencies\": {\n \"@xiboplayer/utils\": \"workspace:*\",\n \"spark-md5\": \"^3.0.2\"\n },\n \"devDependencies\": {\n \"jsdom\": \"^29.0.2\",\n \"vitest\": \"^4.1.2\"\n },\n \"keywords\": [\n \"xibo\",\n \"digital-signage\",\n \"cache\",\n \"offline\",\n \"download\",\n \"indexeddb\"\n ],\n \"author\": \"Pau Aliagas <linuxnow@gmail.com>\",\n \"license\": \"AGPL-3.0-or-later\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/xibo-players/xiboplayer.git\",\n \"directory\": \"packages/cache\"\n },\n \"homepage\": \"https://xiboplayer.org\"\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CacheManager - Dependant tracking and cache lifecycle\n *\n * After the storage unification, all downloads and file retrieval go through\n * the proxy's ContentStore (via StoreClient/DownloadClient). This class retains:\n * - Dependant tracking (which layouts reference which media)\n * - Cache key generation\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\n\nexport class CacheManager {\n constructor() {\n // Dependants: mediaId → Set<layoutId> — tracks which layouts use each media file\n this.dependants = new Map();\n }\n\n /**\n * Track that a media file is used by a layout (dependant)\n * @param {string|number} mediaId\n * @param {string|number} layoutId\n */\n addDependant(mediaId, layoutId) {\n const key = String(mediaId);\n if (!this.dependants.has(key)) {\n this.dependants.set(key, new Set());\n }\n this.dependants.get(key).add(String(layoutId));\n }\n\n /**\n * Remove a layout from all dependant sets (layout removed from schedule)\n * @param {string|number} layoutId\n * @returns {string[]} Media IDs that are now orphaned (no layouts reference them)\n */\n removeLayoutDependants(layoutId) {\n const lid = String(layoutId);\n const orphaned = [];\n\n for (const [mediaId, layouts] of this.dependants) {\n layouts.delete(lid);\n if (layouts.size === 0) {\n this.dependants.delete(mediaId);\n orphaned.push(mediaId);\n }\n }\n\n if (orphaned.length > 0) {\n log.info(`${orphaned.length} media files orphaned after layout ${layoutId} removed:`, orphaned);\n }\n return orphaned;\n }\n\n /**\n * Check if a media file is still referenced by any layout\n * @param {string|number} mediaId\n * @returns {boolean}\n */\n isMediaReferenced(mediaId) {\n const layouts = this.dependants.get(String(mediaId));\n return layouts ? layouts.size > 0 : false;\n }\n\n /**\n * Clear all cached files via proxy\n */\n async clearAll() {\n this.dependants.clear();\n }\n}\n\nexport const cacheManager = new CacheManager();\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * StoreClient — Pure REST client for ContentStore\n *\n * Communicates with the proxy's /store/* endpoints via fetch().\n * No Service Worker dependency — works immediately after construction.\n *\n * Usage:\n * const store = new StoreClient();\n * const exists = await store.has('media', '123');\n * const blob = await store.get('media', '123');\n * await store.put('widget', 'layout/1/region/2/media/3', htmlBlob, 'text/html');\n * await store.remove([{ type: 'media', id: '456' }]);\n * const files = await store.list();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('StoreClient');\n\nexport class StoreClient {\n /**\n * Check if a file exists in the store.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @returns {Promise<boolean>}\n */\n async has(type, id) {\n try {\n const response = await fetch(`/store/${type}/${id}`, { method: 'HEAD' });\n if (response.status === 204) return false; // Not in store (no console error)\n if (response.status === 200) {\n // Incomplete chunked files return 200 with X-Store-Complete: false\n return response.headers.get('X-Store-Complete') !== 'false';\n }\n if (response.status === 404) return false;\n // Non-404 HTTP errors (500, 502, etc.) indicate proxy/store problems\n const err = new Error(`Store error: ${response.status}`);\n err.status = response.status;\n log.warn(`has(${type}/${id}): unexpected status ${response.status}`);\n throw err;\n } catch (error) {\n // Re-throw errors that are not simple network failures swallowed above\n // (includes HTTP errors we threw, AbortError, TypeError from fetch)\n if (error.status || error.name === 'AbortError' || error.name === 'TimeoutError') {\n throw error;\n }\n // Network errors (proxy unreachable) — log and re-throw so callers\n // can distinguish from \"not cached\" (which returns false)\n log.warn(`has(${type}/${id}): network error — ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Get a file from the store as a Blob.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @returns {Promise<Blob|null>}\n */\n async get(type, id) {\n try {\n const response = await fetch(`/store/${type}/${id}`);\n if (response.status === 204 || response.status === 404) {\n response.body?.cancel();\n return null;\n }\n if (!response.ok) {\n response.body?.cancel();\n throw new Error(`Failed to get file: ${response.status}`);\n }\n return await response.blob();\n } catch (error) {\n log.error('get error:', error.message);\n return null;\n }\n }\n\n /**\n * Store a file in the ContentStore.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @param {Blob|ArrayBuffer|string} body - Content to store\n * @param {string} [contentType='application/octet-stream'] - MIME type\n * @returns {Promise<boolean>} true if stored successfully\n */\n async put(type, id, body, contentType = 'application/octet-stream') {\n try {\n const response = await fetch(`/store/${type}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': contentType },\n body,\n });\n response.body?.cancel();\n return response.ok;\n } catch (error) {\n log.error('put error:', error.message);\n return false;\n }\n }\n\n /**\n * Delete files from the store.\n * @param {Array<{type: string, id: string}>} files - Files to delete\n * @returns {Promise<{deleted: number, total: number}>}\n */\n async remove(files) {\n try {\n const response = await fetch('/store/delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files }),\n });\n const result = await response.json();\n return { deleted: result.deleted || 0, total: result.total || files.length };\n } catch (error) {\n log.error('remove error:', error.message);\n return { deleted: 0, total: files.length };\n }\n }\n\n /**\n * List all files in the store.\n * @returns {Promise<Array<{id: string, type: string, size: number}>>}\n */\n async list() {\n try {\n const response = await fetch('/store/list');\n const data = await response.json();\n return data.files || [];\n } catch (error) {\n log.error('list error:', error.message);\n return [];\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CacheAnalyzer - Stale media detection and storage health monitoring\n *\n * Compares cached files against RequiredFiles from the CMS to identify\n * orphaned media that is no longer needed. Logs a summary every collection\n * cycle. Only evicts when storage pressure exceeds a configurable threshold.\n *\n * Works entirely through StoreClient (REST to proxy) — no IndexedDB,\n * no direct Cache API access.\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('CacheAnalyzer');\n\n/**\n * Format bytes into human-readable string (e.g. 1.2 GB, 350 MB)\n */\nfunction formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n if (!Number.isFinite(bytes)) return '∞';\n const units = ['B', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(1024));\n const value = bytes / 1024 ** i;\n return `${value.toFixed(i > 0 ? 1 : 0)} ${units[i]}`;\n}\n\nexport class CacheAnalyzer {\n /**\n * @param {import('./store-client.js').StoreClient} cache - StoreClient instance\n * @param {object} [options]\n * @param {number} [options.threshold=80] - Storage usage % above which eviction triggers\n */\n constructor(cache, { threshold = 80 } = {}) {\n this.cache = cache;\n this.threshold = threshold;\n }\n\n /**\n * Analyze cache health by comparing cached files against required files.\n *\n * @param {Array<{id: string, type: string}>} requiredFiles - Current RequiredFiles from CMS\n * @returns {Promise<object>} Analysis report\n */\n async analyze(requiredFiles) {\n const cachedFiles = await this.cache.list();\n const storage = await this._getStorageEstimate();\n\n // Build set of required file IDs (as strings for consistent comparison)\n const requiredIds = new Set(requiredFiles.map(f => String(f.id)));\n\n // Categorize cached files\n const required = [];\n const orphaned = [];\n\n for (const file of cachedFiles) {\n if (requiredIds.has(String(file.id))) {\n required.push(file);\n } else if (file.type === 'widget') {\n // Widget HTML IDs are \"layoutId/regionId/widgetId\" — check parent layout\n const parentLayoutId = String(file.id).split('/')[0];\n if (requiredIds.has(parentLayoutId)) {\n required.push(file);\n } else {\n orphaned.push(file);\n }\n } else if (file.type === 'static') {\n // Static files (bundle.min.js, fonts.css, fonts, images) are shared widget\n // dependencies — never orphan them, they're referenced from widget HTML\n required.push(file);\n } else {\n orphaned.push(file);\n }\n }\n\n // Sort orphaned by cachedAt ascending (oldest first — evict these first)\n orphaned.sort((a, b) => (a.cachedAt || 0) - (b.cachedAt || 0));\n\n const orphanedSize = orphaned.reduce((sum, f) => sum + (f.size || 0), 0);\n\n const report = {\n timestamp: Date.now(),\n storage: {\n usage: storage.usage,\n quota: storage.quota,\n percent: storage.quota > 0 ? Math.round((storage.usage / storage.quota) * 100) : 0,\n },\n files: {\n required: required.length,\n orphaned: orphaned.length,\n total: cachedFiles.length,\n },\n orphaned: orphaned.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n })),\n orphanedSize,\n evicted: [],\n threshold: this.threshold,\n };\n\n // Log summary\n log.info(`Storage: ${formatBytes(storage.usage)} / ${formatBytes(storage.quota)} (${report.storage.percent}%)`);\n log.info(`Cache: ${required.length} required, ${orphaned.length} orphaned (${formatBytes(orphanedSize)} reclaimable)`);\n\n if (orphaned.length > 0) {\n for (const f of orphaned) {\n const age = Date.now() - (f.cachedAt || 0);\n const days = Math.floor(age / 86400000);\n const hours = Math.floor((age % 86400000) / 3600000);\n const ageStr = days > 0 ? `${days}d ago` : `${hours}h ago`;\n log.info(` Orphaned: ${f.type}/${f.id} (${formatBytes(f.size || 0)}, cached ${ageStr})`);\n }\n }\n\n // Evict only when storage exceeds threshold\n if (report.storage.percent > this.threshold && orphaned.length > 0) {\n log.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);\n const targetBytes = storage.usage - (storage.quota * this.threshold / 100);\n report.evicted = await this._evict(orphaned, targetBytes);\n } else {\n log.info(`No eviction needed (threshold: ${this.threshold}%)`);\n }\n\n return report;\n }\n\n /**\n * Get storage estimate from the browser.\n * Falls back to { usage: 0, quota: Infinity } in environments without the API.\n */\n async _getStorageEstimate() {\n try {\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n const { usage, quota } = await navigator.storage.estimate();\n return { usage: usage || 0, quota: quota || Infinity };\n }\n } catch (e) {\n log.warn('Storage estimate unavailable:', e.message);\n }\n return { usage: 0, quota: Infinity };\n }\n\n /**\n * Evict orphaned files (oldest first) until targetBytes are freed.\n * Delegates deletion to StoreClient.remove() which routes to proxy.\n *\n * @param {Array} orphanedFiles - Files to evict, sorted oldest-first\n * @param {number} targetBytes - Bytes to free\n * @returns {Promise<Array>} Evicted file records\n */\n async _evict(orphanedFiles, targetBytes) {\n const toEvict = [];\n let plannedBytes = 0;\n\n for (const file of orphanedFiles) {\n if (plannedBytes >= targetBytes) break;\n toEvict.push(file);\n plannedBytes += file.size || 0;\n }\n\n if (toEvict.length === 0) return [];\n\n try {\n const filesToDelete = toEvict.map(f => ({ type: f.type, id: f.id }));\n await this.cache.remove(filesToDelete);\n\n for (const f of toEvict) {\n log.info(` Evicted: ${f.type}/${f.id} (${formatBytes(f.size || 0)})`);\n }\n log.info(`Evicted ${toEvict.length} files, freed ${formatBytes(plannedBytes)}`);\n } catch (err) {\n log.warn('Eviction failed:', err.message);\n return [];\n }\n\n return toEvict.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n }));\n }\n}\n\nexport { formatBytes };\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Widget HTML processing — preprocesses widget HTML and stores via REST\n *\n * Handles:\n * - <base> tag injection for relative path resolution (CMS mirror paths)\n * - Interactive Control hostAddress rewriting\n * - CSS object-position fix for CMS template alignment\n *\n * URL rewriting is no longer needed — the CMS serves CSS with relative paths\n * (${PLAYER_API}/dependencies/font.otf), and the <base> tag resolves widget\n * media references via mirror routes. Zero translation, zero regex.\n *\n * Runs on the main thread (needs window.location for URL construction).\n * Stores content via PUT /store/... — no Cache API needed.\n */\n\nimport { createLogger, PLAYER_API } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\n\n// Dynamic base path for multi-variant deployment (pwa, pwa-xmds, pwa-xlr)\nconst BASE = (typeof window !== 'undefined')\n ? window.location.pathname.replace(/\\/[^/]*$/, '').replace(/\\/$/, '') || '/player/pwa'\n : '/player/pwa';\n\n/**\n * Store widget HTML in ContentStore for iframe loading.\n * Stored at mirror path ${PLAYER_API}/widgets/{L}/{R}/{M} — same URL the\n * CMS serves from, so iframes load directly from Express mirror routes.\n *\n * @param {string} layoutId - Layout ID\n * @param {string} regionId - Region ID\n * @param {string} mediaId - Media ID\n * @param {string} html - Widget HTML content\n * @returns {Promise<string>} Cache key URL (absolute path for iframe src)\n */\nexport async function cacheWidgetHtml(layoutId, regionId, mediaId, html) {\n const cacheKey = `${PLAYER_API}/widgets/${layoutId}/${regionId}/${mediaId}`;\n\n // Inject <base> tag — resolves relative media refs (e.g. \"42\") to mirror route\n const baseTag = `<base href=\"${PLAYER_API}/media/file/\">`;\n let modifiedHtml = html;\n\n // Insert base tag after <head> opening tag (skip if already present)\n if (!html.includes('<base ')) {\n if (html.includes('<head>')) {\n modifiedHtml = html.replace('<head>', '<head>' + baseTag);\n } else if (html.includes('<HEAD>')) {\n modifiedHtml = html.replace('<HEAD>', '<HEAD>' + baseTag);\n } else {\n modifiedHtml = baseTag + html;\n }\n }\n\n // Inject CSS default for object-position to suppress CMS template warning\n const cssFixTag = '<style>img,video{object-position:center center}</style>';\n if (!modifiedHtml.includes('object-position:center center')) {\n if (modifiedHtml.includes('</head>')) {\n modifiedHtml = modifiedHtml.replace('</head>', cssFixTag + '</head>');\n } else if (modifiedHtml.includes('</HEAD>')) {\n modifiedHtml = modifiedHtml.replace('</HEAD>', cssFixTag + '</HEAD>');\n }\n }\n\n // Replace CMS placeholders left for \"client-side SDK handling\"\n modifiedHtml = modifiedHtml.replace(/\\[\\[ViewPortWidth]]/g, 'device-width');\n\n // Route HLS streams through local proxy (adds CORS headers, rewrites segments)\n modifiedHtml = modifiedHtml.replace(\n /https?:\\/\\/[^\\s\"')<]+\\.m3u8\\b/gi,\n (url) => '/stream-proxy?url=' + encodeURIComponent(url)\n );\n\n // Rewrite dependency URLs to absolute local paths. CMS SOAP GetResource sends\n // bare filenames (e.g. src=\"bundle.min.js\") which resolve against <base> to the\n // wrong /media/file/ path. Normalize all dependency references to absolute paths.\n const depsPattern = new RegExp(\n `https?://[^\"'\\\\s)]+?(${PLAYER_API.replace(/\\//g, '\\\\/')}/dependencies/[^\"'\\\\s?)]+)(\\\\?[^\"'\\\\s)]*)?`,\n 'g'\n );\n modifiedHtml = modifiedHtml.replace(depsPattern, (_, path) => path);\n modifiedHtml = modifiedHtml.replace(\n /(<(?:script|link)\\b[^>]*(?:src|href)=\")(?!\\/|https?:\\/\\/)(bundle\\.min\\.js|fonts\\.css)(\")/g,\n `$1${PLAYER_API}/dependencies/$2$3`\n );\n\n // Inject xiboICTargetId — XIC library reads this global before its IIFE runs\n // to set _lib.targetId, which is included in every IC HTTP request as {id: ...}\n if (!modifiedHtml.includes('xiboICTargetId')) {\n const targetIdScript = `<script>var xiboICTargetId = '${mediaId}';</script>`;\n if (modifiedHtml.includes(baseTag)) {\n modifiedHtml = modifiedHtml.replace(baseTag, baseTag + targetIdScript);\n } else if (modifiedHtml.includes('<head>')) {\n modifiedHtml = modifiedHtml.replace('<head>', '<head>' + targetIdScript);\n } else {\n modifiedHtml = targetIdScript + modifiedHtml;\n }\n }\n\n // Rewrite Interactive Control hostAddress to SW-interceptable path\n modifiedHtml = modifiedHtml.replace(\n /hostAddress\\s*:\\s*[\"']https?:\\/\\/[^\"']+[\"']/g,\n `hostAddress: \"${BASE}/ic\"`\n );\n\n log.info('Injected base tag in widget HTML');\n\n // Store widget HTML — deps are already downloaded by the pipeline\n const putResp = await fetch(`/store${PLAYER_API}/widgets/${layoutId}/${regionId}/${mediaId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\n body: modifiedHtml,\n });\n putResp.body?.cancel();\n log.info(`Stored widget HTML at ${cacheKey} (${modifiedHtml.length} bytes)`);\n\n return { cacheKey, html: modifiedHtml };\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n// @xiboplayer/cache - Offline caching and downloads\nimport pkg from '../package.json' with { type: 'json' };\nexport const VERSION = pkg.version;\nexport { CacheManager, cacheManager } from './cache.js';\nexport { StoreClient } from './store-client.js';\nexport { DownloadManager, FileDownload, LayoutTaskBuilder, BARRIER, isUrlExpired } from './download-manager.js';\nexport { CacheAnalyzer } from './cache-analyzer.js';\nexport { cacheWidgetHtml } from './widget-html.js';\nexport { FILE_TYPES, getFileTypeConfig } from './file-types.js';\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Service Worker Utility Functions\n * Shared helpers to eliminate code duplication and improve maintainability\n */\n\n/**\n * Dynamic base path derived from the Service Worker's registration scope.\n * Allows the same build to serve /player/pwa/, /player/pwa-xmds/, /player/pwa-xlr/.\n */\nexport const BASE = (() => {\n if (typeof self !== 'undefined' && self.registration?.scope) {\n return new URL(self.registration.scope).pathname.replace(/\\/$/, '');\n }\n return '/player/pwa'; // fallback\n})();\n\n/**\n * Format byte size to human-readable string\n * @param {number} bytes - Size in bytes\n * @param {number} decimals - Decimal places (default: 1)\n * @returns {string} Formatted size (e.g., \"1.5 MB\", \"512.0 KB\")\n */\nexport function formatBytes(bytes, decimals = 1) {\n if (bytes === 0) return '0 Bytes';\n if (bytes < 1024) return `${bytes} Bytes`;\n\n const kb = bytes / 1024;\n if (kb < 1024) return `${kb.toFixed(decimals)} KB`;\n\n const mb = kb / 1024;\n if (mb < 1024) return `${mb.toFixed(decimals)} MB`;\n\n const gb = mb / 1024;\n return `${gb.toFixed(decimals)} GB`;\n}\n\n/**\n * Parse HTTP Range header\n * @param {string} rangeHeader - Range header value (e.g., \"bytes=0-1000\")\n * @param {number} totalSize - Total file size\n * @returns {{ start: number, end: number }} Byte range\n */\nexport function parseRangeHeader(rangeHeader, totalSize) {\n const parts = rangeHeader.replace(/bytes=/, '').split('-');\n const start = parseInt(parts[0], 10);\n const end = parts[1] ? parseInt(parts[1], 10) : totalSize - 1;\n\n return { start, end };\n}\n\n/**\n * Create standardized response headers for media files\n * @param {Object} options - Header options\n * @param {string} options.contentType - Content-Type header\n * @param {number|string} options.contentLength - Content-Length header\n * @param {boolean} options.includeCache - Include Cache-Control header\n * @param {string} options.contentRange - Content-Range for 206 responses\n * @returns {Object} Response headers\n */\nexport function createMediaHeaders({\n contentType = 'application/octet-stream',\n contentLength = null,\n includeCache = false,\n contentRange = null\n}) {\n const headers = {\n 'Content-Type': contentType,\n 'Accept-Ranges': 'bytes',\n 'Access-Control-Allow-Origin': '*'\n };\n\n if (contentLength !== null) {\n headers['Content-Length'] = String(contentLength);\n }\n\n if (includeCache) {\n headers['Cache-Control'] = 'public, max-age=31536000';\n }\n\n if (contentRange) {\n headers['Content-Range'] = contentRange;\n }\n\n return headers;\n}\n\n/**\n * Create error response with consistent format\n * @param {string} message - Error message\n * @param {number} status - HTTP status code\n * @returns {Response}\n */\nexport function createErrorResponse(message, status = 500) {\n const statusTexts = {\n 404: 'Not Found',\n 500: 'Internal Server Error',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable'\n };\n\n return new Response(message, {\n status,\n statusText: statusTexts[status] || 'Error',\n headers: { 'Content-Type': 'text/plain' }\n });\n}\n\n/**\n * HTTP Status Codes\n */\nexport const HTTP_STATUS = {\n OK: 200,\n PARTIAL_CONTENT: 206,\n NOT_FOUND: 404,\n INTERNAL_ERROR: 500,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503\n};\n\n/**\n * Timeouts (milliseconds)\n */\nexport const TIMEOUTS = {\n SW_CLAIM_WAIT: 100, // Wait for SW to claim page\n SW_FETCH_READY: 200, // Wait for SW fetch handler\n SW_READY_MAX: 10000, // Max wait for SW ready\n DOWNLOAD_CHECK: 1000 // Download progress check interval\n};\n\n/**\n * Calculate chunk boundaries\n * @param {number} chunkIndex - Chunk index\n * @param {number} chunkSize - Size per chunk\n * @param {number} totalSize - Total file size\n * @returns {{ start: number, end: number, size: number }}\n */\nexport function getChunkBoundaries(chunkIndex, chunkSize, totalSize) {\n const start = chunkIndex * chunkSize;\n const end = Math.min(start + chunkSize, totalSize);\n return { start, end, size: end - start };\n}\n\n/**\n * Calculate which chunks contain a byte range\n * @param {number} rangeStart - Range start byte\n * @param {number} rangeEnd - Range end byte\n * @param {number} chunkSize - Size per chunk\n * @returns {{ startChunk: number, endChunk: number, count: number }}\n */\nexport function getChunksForRange(rangeStart, rangeEnd, chunkSize) {\n const startChunk = Math.floor(rangeStart / chunkSize);\n const endChunk = Math.floor(rangeEnd / chunkSize);\n return {\n startChunk,\n endChunk,\n count: endChunk - startChunk + 1\n };\n}\n\n/**\n * Extract byte range from chunk blobs\n * @param {Blob[]} chunkBlobs - Array of chunk blobs\n * @param {number} rangeStart - Desired start byte (absolute position in file)\n * @param {number} rangeEnd - Desired end byte (absolute position in file)\n * @param {number} chunkSize - Size per chunk\n * @param {string} contentType - Content type for result blob\n * @returns {Blob} Extracted range\n */\nexport function extractRangeFromChunks(chunkBlobs, rangeStart, rangeEnd, chunkSize, contentType) {\n if (chunkBlobs.length === 1) {\n // Single chunk - simple slice\n const offset = rangeStart % chunkSize;\n const length = rangeEnd - rangeStart + 1;\n return chunkBlobs[0].slice(offset, offset + length);\n }\n\n // Multiple chunks - concatenate parts\n const parts = [];\n const firstChunkOffset = rangeStart % chunkSize;\n const lastChunkEnd = rangeEnd % chunkSize;\n\n // First chunk (partial from offset to end)\n parts.push(chunkBlobs[0].slice(firstChunkOffset));\n\n // Middle chunks (complete - use as-is)\n for (let i = 1; i < chunkBlobs.length - 1; i++) {\n parts.push(chunkBlobs[i]);\n }\n\n // Last chunk (partial from start to lastChunkEnd)\n if (chunkBlobs.length > 1) {\n parts.push(chunkBlobs[chunkBlobs.length - 1].slice(0, lastChunkEnd + 1));\n }\n\n return new Blob(parts, { type: contentType });\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * RequestHandler - Handles fetch events for cached content\n *\n * With CMS mirror routes on the proxy, the SW's role is minimal:\n * - ${PLAYER_API}/* requests pass through to Express (mirror routes serve them)\n * - Static pages pass through to network\n *\n * No URL translation needed — the proxy serves at CMS paths directly.\n * Widget HTML is served by the Express mirror route at ${PLAYER_API}/widgets/{L}/{R}/{M}.\n */\n\nimport { BASE } from './sw-utils.js';\nimport { createLogger, PLAYER_API } from '@xiboplayer/utils';\n\nexport class RequestHandler {\n /**\n * @param {Object} downloadManager - DownloadManager instance\n */\n constructor(downloadManager) {\n this.downloadManager = downloadManager;\n this.log = createLogger('SW');\n }\n\n /**\n * Handle fetch request\n */\n async handleRequest(event) {\n const url = new URL(event.request.url);\n\n // Static pages — pass through to Express\n if (url.pathname === BASE + '/' ||\n url.pathname === BASE + '/index.html' ||\n url.pathname === BASE + '/setup.html') {\n return fetch(event.request);\n }\n\n // Player API — pass through to Express mirror routes\n if (url.pathname.startsWith(PLAYER_API + '/')) {\n return fetch(event.request);\n }\n\n // XMDS file downloads — route through Express cache-through\n if (url.pathname.includes('xmds.php') && url.searchParams.has('file')) {\n return this._handleXmdsFile(event, url);\n }\n\n // Not a cache request — pass through to network\n return fetch(event.request);\n }\n\n /**\n * Route XMDS file downloads to the local Express cache-through proxy.\n *\n * XMDS RequiredFiles returns cross-origin signed URLs like:\n * https://cms/xmds.php?file=42.mp4&type=M&X-Amz-Signature=...\n *\n * We rewrite these to local proxy mirror paths so the download goes through\n * ContentStore caching, avoiding CORS issues and enabling chunked downloads.\n */\n _handleXmdsFile(event, url) {\n const filename = url.searchParams.get('file');\n const fileType = url.searchParams.get('type'); // L=layout, M=media, P=resource/font\n const itemId = url.searchParams.get('itemId');\n\n let proxyPath;\n if (fileType === 'L') {\n proxyPath = `${PLAYER_API}/layouts/${itemId}`;\n } else if (fileType === 'P') {\n proxyPath = `${PLAYER_API}/dependencies/${filename}`;\n } else {\n proxyPath = `${PLAYER_API}/media/file/${filename}`;\n }\n\n this.log.info(`XMDS redirect: ${fileType}/${filename} → ${proxyPath}`);\n\n // Pass original XMDS URL so proxy can fetch from CMS on cache miss\n const headers = new Headers(event.request.headers);\n headers.set('X-Cms-Download-Url', url.href);\n\n return fetch(proxyPath, { headers });\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * MessageHandler - Handles postMessage from client\n *\n * Lightweight SW message handler for lifecycle and file management.\n * Download orchestration has moved to the main thread (PwaPlayer).\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\n/** Store key = URL path without leading / and query params */\nconst storeKeyFrom = (f) => (f.path || '').split('?')[0].replace(/^\\/+/, '') || `${f.type || 'media'}/${f.id}`;\n\nexport class MessageHandler {\n /**\n * @param {Object} downloadManager - DownloadManager instance (kept for future SW-only mode)\n * @param {Object} config\n */\n constructor(downloadManager, config) {\n this.downloadManager = downloadManager;\n this.config = config;\n this.log = createLogger('SW Message');\n }\n\n /**\n * Handle message from client\n */\n async handleMessage(event) {\n const { type, data } = event.data;\n this.log.info('Received:', type);\n\n switch (type) {\n case 'PING': {\n this.log.info('PING received, broadcasting SW_READY');\n const clients = await self.clients.matchAll();\n clients.forEach(client => {\n client.postMessage({ type: 'SW_READY' });\n });\n return { success: true };\n }\n\n case 'DELETE_FILES':\n return await this.handleDeleteFiles(data.files);\n\n case 'GET_ALL_FILES':\n return await this.handleGetAllFiles();\n\n case 'CLEAR_CACHE':\n return { success: true };\n\n default:\n this.log.warn('Unknown message type:', type);\n return { success: false, error: 'Unknown message type' };\n }\n }\n\n /**\n * Handle DELETE_FILES message - purge obsolete files from ContentStore via proxy\n */\n async handleDeleteFiles(files) {\n if (!files || !Array.isArray(files)) {\n return { success: false, error: 'No files provided' };\n }\n\n try {\n const deleteFiles = files.map(f => ({\n ...f,\n key: storeKeyFrom(f),\n }));\n const resp = await fetch('/store/delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files: deleteFiles }),\n });\n const result = await resp.json();\n this.log.info(`Purge complete: ${result.deleted}/${result.total} files deleted`);\n return { success: true, deleted: result.deleted, total: result.total };\n } catch (err) {\n this.log.error('Delete failed:', err.message);\n return { success: false, error: err.message };\n }\n }\n\n /**\n * Handle GET_ALL_FILES — list files from ContentStore via proxy\n */\n async handleGetAllFiles() {\n try {\n const resp = await fetch('/store/list');\n const data = await resp.json();\n return { success: true, files: data.files || [] };\n } catch (err) {\n this.log.error('Failed to list files:', err.message);\n return { success: true, files: [] };\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Chunk configuration for Service Worker downloads\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\n/**\n * Calculate optimal chunk size based on available device memory.\n * Returns configuration for chunk streaming, blob caching, and download concurrency.\n *\n * @param {{ info: Function }} [log] - Optional logger (created internally if not provided)\n * @returns {{ chunkSize: number, blobCacheSize: number, threshold: number, concurrency: number }}\n */\nexport function calculateChunkConfig(log) {\n if (!log) log = createLogger('ChunkConfig');\n\n // Try to detect device memory (Chrome only for now)\n const deviceMemoryGB = (typeof navigator !== 'undefined' && navigator.deviceMemory) || null;\n\n // Fallback: estimate from user agent\n let estimatedRAM_GB = 4; // Default assumption\n\n if (deviceMemoryGB) {\n estimatedRAM_GB = deviceMemoryGB;\n log.info('Detected device memory:', deviceMemoryGB, 'GB');\n } else if (typeof navigator !== 'undefined') {\n // Parse user agent for hints\n const ua = navigator.userAgent.toLowerCase();\n if (ua.includes('raspberry pi') || ua.includes('armv6')) {\n estimatedRAM_GB = 0.5; // Pi Zero\n log.info('Detected Pi Zero (512 MB RAM estimated)');\n } else if (ua.includes('armv7')) {\n estimatedRAM_GB = 1; // Pi 3/4\n log.info('Detected ARM device (1 GB RAM estimated)');\n } else {\n log.info('Using default RAM estimate:', estimatedRAM_GB, 'GB');\n }\n }\n\n // Configure based on RAM - chunk size, cache, threshold, AND concurrency\n let chunkSize, blobCacheSize, threshold, concurrency;\n\n if (estimatedRAM_GB <= 0.5) {\n // Pi Zero (512 MB) - very conservative\n chunkSize = 10 * 1024 * 1024;\n blobCacheSize = 25;\n threshold = 25 * 1024 * 1024;\n concurrency = 1;\n log.info('Low-memory config: 10 MB chunks, 25 MB cache, 1 concurrent download');\n } else if (estimatedRAM_GB <= 1) {\n // 1 GB RAM (Pi 3) - conservative\n chunkSize = 20 * 1024 * 1024;\n blobCacheSize = 50;\n threshold = 50 * 1024 * 1024;\n concurrency = 2;\n log.info('1GB-RAM config: 20 MB chunks, 50 MB cache, 2 concurrent downloads');\n } else if (estimatedRAM_GB <= 2) {\n // 2 GB RAM - moderate\n chunkSize = 30 * 1024 * 1024;\n blobCacheSize = 100;\n threshold = 75 * 1024 * 1024;\n concurrency = 2;\n log.info('2GB-RAM config: 30 MB chunks, 100 MB cache, 2 concurrent downloads');\n } else if (estimatedRAM_GB <= 4) {\n // 4 GB RAM - default\n chunkSize = 50 * 1024 * 1024;\n blobCacheSize = 200;\n threshold = 100 * 1024 * 1024;\n concurrency = 4;\n log.info('4GB-RAM config: 50 MB chunks, 200 MB cache, 4 concurrent downloads');\n } else {\n // 8+ GB RAM - generous but heap-safe (100 MB × 4 = 400 MB peak, within 768 MB V8 heap)\n chunkSize = 100 * 1024 * 1024;\n blobCacheSize = 500;\n threshold = 200 * 1024 * 1024;\n concurrency = 4;\n log.info('High-RAM config: 100 MB chunks, 500 MB cache, 4 concurrent downloads');\n }\n\n return { chunkSize, blobCacheSize, threshold, concurrency };\n}\n","/**\n * Standalone Service Worker for Xibo PWA Player\n * Thin entry point — all reusable logic lives in @xiboplayer/sw\n *\n * Architecture:\n * - @xiboplayer/sw: RequestHandler, MessageHandler\n * - @xiboplayer/cache: DownloadManager, LayoutTaskBuilder\n * - @xiboplayer/proxy: ContentStore (filesystem storage — runs server-side)\n * - This file: PWA-specific wiring (lifecycle events, Interactive Control)\n *\n * Media storage flow:\n * CMS → proxy cache-through → ContentStore (filesystem) → proxy /store → renderer\n * Download orchestration lives in the main thread (PwaPlayer).\n */\n\nimport { DownloadManager } from '@xiboplayer/cache/download-manager';\nimport { VERSION as CACHE_VERSION } from '@xiboplayer/cache';\nimport {\n RequestHandler,\n MessageHandler,\n calculateChunkConfig\n} from '@xiboplayer/sw';\nimport { createLogger } from '@xiboplayer/utils';\nimport { BASE } from '@xiboplayer/sw/utils';\n\n// ── Configuration ──────────────────────────────────────────────────────────\nconst SW_VERSION = __BUILD_DATE__;\n\nconst log = createLogger('SW');\n\n// ── Device-adaptive chunk config ───────────────────────────────────────────\nconst CHUNK_CONFIG = calculateChunkConfig(log);\nconst CHUNK_SIZE = CHUNK_CONFIG.chunkSize;\nconst CHUNK_STORAGE_THRESHOLD = CHUNK_CONFIG.threshold;\nconst CONCURRENT_DOWNLOADS = CHUNK_CONFIG.concurrency;\n\nlog.info('Loading modular Service Worker:', SW_VERSION);\n\n// ── Initialize shared instances ────────────────────────────────────────────\nconst downloadManager = new DownloadManager({\n concurrency: CONCURRENT_DOWNLOADS,\n chunkSize: CHUNK_SIZE,\n chunksPerFile: 2\n});\n\nconst requestHandler = new RequestHandler(downloadManager);\n\nconst messageHandler = new MessageHandler(downloadManager, {\n chunkSize: CHUNK_SIZE,\n chunkStorageThreshold: CHUNK_STORAGE_THRESHOLD\n});\n\n// ── PWA-specific: Interactive Control handler ──────────────────────────────\n\n/**\n * Handle Interactive Control requests from widget iframes.\n * Forwards to main thread via MessageChannel and returns the response.\n * IC library in widgets uses XHR to /player/pwa/ic/{route}.\n */\nasync function handleInteractiveControl(event) {\n const url = new URL(event.request.url);\n const icPath = url.pathname.replace(BASE + '/ic', '');\n const method = event.request.method;\n\n log.info('Interactive Control request:', method, icPath);\n\n let body = null;\n if (method === 'POST' || method === 'PUT') {\n try {\n body = await event.request.text();\n } catch (_) {}\n }\n\n // Forward to main thread via MessageChannel\n const clients = await self.clients.matchAll({ type: 'window' });\n if (clients.length === 0) {\n return new Response(JSON.stringify({ error: 'No active player' }), {\n status: 503,\n headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }\n });\n }\n\n const client = clients[0];\n\n try {\n const response = await new Promise((resolve, reject) => {\n const channel = new MessageChannel();\n const timer = setTimeout(() => reject(new Error('IC timeout')), 5000);\n\n channel.port1.onmessage = (msg) => {\n clearTimeout(timer);\n resolve(msg.data);\n };\n\n client.postMessage({\n type: 'INTERACTIVE_CONTROL',\n method,\n path: icPath,\n search: url.search,\n body\n }, [channel.port2]);\n });\n\n return new Response(response.body || '', {\n status: response.status || 200,\n headers: {\n 'Content-Type': response.contentType || 'application/json',\n 'Access-Control-Allow-Origin': '*'\n }\n });\n } catch (error) {\n log.error('IC handler error:', error);\n return new Response(JSON.stringify({ error: error.message }), {\n status: 500,\n headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }\n });\n }\n}\n\n// ── Lifecycle: Install ─────────────────────────────────────────────────────\nself.addEventListener('install', (event) => {\n log.info('Installing... Version:', SW_VERSION);\n event.waitUntil(\n (async () => {\n // Check if same version is already active — skip activation to preserve streams\n if (self.registration.active) {\n try {\n const versionCache = await caches.open('xibo-sw-version');\n const stored = await versionCache.match('version');\n if (stored) {\n const activeVersion = await stored.text();\n if (activeVersion === SW_VERSION) {\n log.info('Same version already active, skipping activation to preserve streams');\n return;\n }\n log.info('Version changed:', activeVersion, '→', SW_VERSION);\n }\n } catch (_) {}\n }\n log.info('New version, activating immediately');\n return self.skipWaiting();\n })()\n );\n});\n\n// ── Lifecycle: Activate ────────────────────────────────────────────────────\nself.addEventListener('activate', (event) => {\n log.info('Activating... Version:', SW_VERSION, '| @xiboplayer/cache:', CACHE_VERSION);\n event.waitUntil(\n // Clean up legacy Cache API caches (migration from pre-ContentStore)\n caches.keys().then((cacheNames) => {\n return Promise.all(\n cacheNames\n .filter((name) => name.startsWith('xibo-') && name !== 'xibo-sw-version')\n .map((name) => {\n log.info('Deleting legacy cache:', name);\n return caches.delete(name);\n })\n );\n }).then(async () => {\n const versionCache = await caches.open('xibo-sw-version');\n await versionCache.put('version', new Response(SW_VERSION));\n log.info('Taking control of all clients immediately');\n return self.clients.claim();\n }).then(async () => {\n log.info('Notifying all clients that fetch handler is ready');\n const clients = await self.clients.matchAll();\n clients.forEach(client => {\n client.postMessage({ type: 'SW_READY' });\n });\n })\n );\n});\n\n// ── Fetch handler ──────────────────────────────────────────────────────────\nself.addEventListener('fetch', (event) => {\n const url = new URL(event.request.url);\n\n const shouldIntercept =\n url.pathname.startsWith(BASE + '/ic/') ||\n url.pathname.startsWith('/player/') && (url.pathname.endsWith('.html') || url.pathname === '/player/') ||\n (url.pathname.includes('xmds.php') && url.searchParams.has('file') && event.request.method === 'GET');\n\n if (shouldIntercept) {\n if (url.pathname.startsWith(BASE + '/ic/')) {\n event.respondWith(handleInteractiveControl(event));\n return;\n }\n event.respondWith(requestHandler.handleRequest(event));\n }\n});\n\n// ── Message handler ────────────────────────────────────────────────────────\nself.addEventListener('message', (event) => {\n event.waitUntil(\n messageHandler.handleMessage(event).then((result) => {\n event.ports[0]?.postMessage(result);\n })\n );\n});\n\nlog.info('Modular Service Worker ready');\n"],"mappings":"qvBCoBM,EAAa,CACjB,MAAO,EACP,KAAM,EACN,QAAS,EACT,MAAO,EACP,KAAM,EACP,CAGK,EAAW,EAAE,CAEb,EAAN,KAAa,CAKX,YAAY,EAAM,EAAQ,KAAM,CAC9B,KAAK,KAAO,EACZ,KAAK,UAAa,IAAU,KACvB,KAAK,WACR,KAAK,SAAS,EAAM,CAKxB,KAAM,CACJ,IAAM,EAAI,IAAI,KACd,MAAO,GAAG,OAAO,EAAE,UAAU,CAAC,CAAC,SAAS,EAAG,IAAI,CAAC,GAAG,OAAO,EAAE,YAAY,CAAC,CAAC,SAAS,EAAG,IAAI,CAAC,GAAG,OAAO,EAAE,YAAY,CAAC,CAAC,SAAS,EAAG,IAAI,CAAC,GAAG,OAAO,EAAE,iBAAiB,CAAC,CAAC,SAAS,EAAG,IAAI,GAGvL,SAAS,EAAO,CACd,KAAK,UAAY,GACb,OAAO,GAAU,SACnB,KAAK,MAAQ,EAAW,EAAM,aAAa,GAAK,EAAW,KAE3D,KAAK,MAAQ,EAKjB,mBAAoB,CA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