@glivion/square-screen-js-sdk 0.1.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +874 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +522 -0
- package/dist/index.d.mts +522 -0
- package/dist/index.mjs +870 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +8 -1
- package/.github/workflows/build-js-sdk.yml +0 -70
- package/eslint.config.js +0 -3
- package/examples/react-app/README.md +0 -73
- package/examples/react-app/eslint.config.js +0 -22
- package/examples/react-app/index.html +0 -13
- package/examples/react-app/package-lock.json +0 -2239
- package/examples/react-app/package.json +0 -31
- package/examples/react-app/public/favicon.svg +0 -1
- package/examples/react-app/public/icons.svg +0 -24
- package/examples/react-app/src/App.css +0 -184
- package/examples/react-app/src/App.tsx +0 -157
- package/examples/react-app/src/EmergencyTicker.tsx +0 -25
- package/examples/react-app/src/HeadlessExample.tsx +0 -66
- package/examples/react-app/src/RendererExample.tsx +0 -70
- package/examples/react-app/src/assets/hero.png +0 -0
- package/examples/react-app/src/assets/react.svg +0 -1
- package/examples/react-app/src/assets/vite.svg +0 -1
- package/examples/react-app/src/index.css +0 -183
- package/examples/react-app/src/main.tsx +0 -10
- package/examples/react-app/src/mockNetworkDataSource.ts +0 -116
- package/examples/react-app/src/usePlayer.ts +0 -71
- package/examples/react-app/tsconfig.app.json +0 -25
- package/examples/react-app/tsconfig.json +0 -7
- package/examples/react-app/tsconfig.node.json +0 -24
- package/examples/react-app/vite.config.ts +0 -7
- package/examples/react-app/yarn.lock +0 -1089
- package/src/__tests__/cache/SquareScreenCache.test.ts +0 -375
- package/src/__tests__/network/NetworkClient.test.ts +0 -217
- package/src/__tests__/network/mappers.test.ts +0 -163
- package/src/__tests__/player/SquareScreenPlayer.test.ts +0 -840
- package/src/cache/SquareScreenCache.ts +0 -154
- package/src/constants.ts +0 -9
- package/src/core/types.ts +0 -251
- package/src/env.d.ts +0 -4
- package/src/index.ts +0 -34
- package/src/network/NetworkClient.ts +0 -234
- package/src/network/apiTypes.ts +0 -89
- package/src/network/mappers.ts +0 -106
- package/src/player/SquareScreenPlayer.ts +0 -414
- package/src/renderer/SquareScreenRenderer.ts +0 -282
- package/tsconfig.json +0 -12
- package/tsdown.config.ts +0 -23
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/constants.ts","../src/network/mappers.ts","../src/network/NetworkClient.ts","../src/cache/SquareScreenCache.ts","../src/player/SquareScreenPlayer.ts","../src/renderer/SquareScreenRenderer.ts"],"sourcesContent":["/**\n * Production root URL for the SquareScreen REST API.\n *\n * {@link SquareScreenPlayer} uses this for all network requests. Integrators cannot\n * override it via player configuration; supply a custom {@link NetworkDataSource}\n * only if you must talk to a different host (e.g. tests or a private gateway).\n */\nexport const SQUARESCREEN_API_BASE_URL =\n \"https://square-screen-api-development-f7zuxa.laravel.cloud/api/v1\";\n","import {\n EmergencyAlert,\n HeartbeatAck,\n MediaType,\n Playlist,\n PlaylistItem,\n PlaybackStrategy,\n HeartbeatPayload,\n TransitionType,\n} from \"../core/types\";\nimport {\n ApiEmergencyResponse,\n ApiHeartbeatAck,\n ApiHeartbeatPayload,\n ApiPlaybackStrategy,\n ApiPlaylistItem,\n ApiPlaylistResponse,\n} from \"./apiTypes\";\n\n/** Maps a raw playlist item to the core PlaylistItem type. */\nexport function mapPlaylistItem(raw: ApiPlaylistItem): PlaylistItem {\n return {\n uuid: raw.uuid,\n name: raw.name,\n type: raw.type as MediaType,\n url: raw.url,\n duration: raw.duration_seconds,\n ...(raw.transition !== undefined && {\n transition: raw.transition as TransitionType,\n }),\n ...(raw.width !== undefined && { width: raw.width }),\n ...(raw.height !== undefined && { height: raw.height }),\n ...(raw.title !== undefined && { title: raw.title }),\n ...(raw.thumbnail !== undefined && { thumbnail: raw.thumbnail }),\n };\n}\n\n/**\n * Maps the raw strategy field to a PlaybackStrategy.\n * Returns undefined when the API sends an empty array instead of a real object.\n */\nexport function mapPlaybackStrategy(\n raw: ApiPlaybackStrategy | [],\n): PlaybackStrategy | undefined {\n if (Array.isArray(raw)) return undefined;\n return {\n loop: raw.loop,\n shuffle: raw.shuffle,\n preloadCount: raw.preload_count ?? 0,\n };\n}\n\n/** Maps a raw playlist response to the core Playlist type. */\nexport function mapPlaylistResponse(raw: ApiPlaylistResponse): Playlist {\n return {\n uuid: raw.playlist!.uuid,\n items: raw.items.map(mapPlaylistItem),\n strategy: mapPlaybackStrategy(raw.strategy),\n schedule: raw.schedule,\n playlistMeta: raw.playlist,\n cachedAt: Date.now(),\n };\n}\n\n/**\n * Maps a raw emergency response to an EmergencyAlert.\n * Returns null when no emergency is active.\n */\nexport function mapEmergencyResponse(\n raw: ApiEmergencyResponse,\n): EmergencyAlert | null {\n if (raw.emergency === null) return null;\n return {\n id: raw.emergency.id,\n uuid: raw.emergency.uuid,\n companyId: raw.emergency.company_id,\n title: raw.emergency.title,\n message: raw.emergency.message,\n backgroundColor: raw.emergency.background_color,\n textColor: raw.emergency.text_color,\n targetScope: raw.emergency.target_scope,\n isActive: raw.emergency.is_active,\n startedAt: raw.emergency.started_at,\n ...(raw.emergency.ended_at !== undefined && {\n endedAt: raw.emergency.ended_at,\n }),\n };\n}\n\n/** Maps a raw heartbeat acknowledgement to the core HeartbeatAck type. */\nexport function mapHeartbeatAck(raw: ApiHeartbeatAck): HeartbeatAck {\n return { received: raw.received };\n}\n\nexport function mapHeartbeatPayload(\n raw: HeartbeatPayload,\n): ApiHeartbeatPayload {\n return {\n cpu_usage: raw.cpuUsage,\n memory_usage: raw.memoryUsage,\n disk_usage: raw.diskUsage,\n temperature: raw.temperature,\n os_version: raw.osVersion,\n app_version: raw.playerVersion,\n };\n}\n","import {\n EmergencyAlert,\n HeartbeatAck,\n HeartbeatPayload,\n ImagePlaylistParams,\n NetworkDataSource,\n PlaybackEvent,\n Playlist,\n SquareScreenResult,\n VideoPlaylistParams,\n} from \"../core/types\";\nimport {\n ApiEmergencyResponse,\n ApiHeartbeatAck,\n ApiPlaylistResponse,\n} from \"./apiTypes\";\nimport {\n mapEmergencyResponse,\n mapHeartbeatAck,\n mapPlaylistResponse,\n mapHeartbeatPayload,\n} from \"./mappers\";\n\n/**\n * Handles all HTTP communication with the SquareScreen API.\n *\n * Implements {@link NetworkDataSource} and is the only class in the SDK\n * that calls `fetch` directly. Auth headers are injected automatically on\n * every request — callers never set them manually.\n *\n * This class is internal to the SDK. Consumers interact with it only through\n * the `NetworkDataSource` interface via the player module.\n */\nexport class NetworkClient implements NetworkDataSource {\n private readonly baseUrl: string;\n private readonly deviceId: string;\n private readonly deviceToken: string;\n\n /**\n * @param baseUrl - Root URL of the SquareScreen API, e.g. `\"https://api.squarescreen.io/api/v1\"`.\n * @param deviceId - Unique identifier for this device.\n * @param deviceToken - Secret token used to authenticate this device. Never log or expose this value.\n */\n constructor(baseUrl: string, deviceId: string, deviceToken: string) {\n this.baseUrl = baseUrl;\n this.deviceId = deviceId;\n this.deviceToken = deviceToken;\n }\n\n /**\n * Central fetch wrapper used by all public methods.\n *\n * Injects auth headers, separates HTTP errors from network failures,\n * and isolates JSON parse errors — so callers always receive a\n * {@link SquareScreenResult} and never an uncaught exception.\n *\n * Error mapping:\n * - 401/403 → `AuthError`\n * - Other non-2xx → `NetworkError`\n * - JSON parse failure → `ParseError`\n * - `fetch` throw (no internet, CORS, timeout) → `NetworkError` with code `0`\n */\n private async fetchWrapper<T>(\n endpoint: string,\n options: RequestInit,\n ): Promise<SquareScreenResult<T>> {\n try {\n const response = await fetch(`${this.baseUrl}${endpoint}`, {\n ...options,\n headers: {\n ...(options?.headers ?? {}),\n \"Content-Type\": \"application/json\",\n \"X-Device-Id\": this.deviceId,\n \"X-Device-Token\": this.deviceToken,\n },\n });\n\n if (!response.ok) {\n if (response.status === 401) {\n return {\n success: false,\n error: {\n kind: \"auth\",\n message: \"Unauthorized\",\n },\n };\n }\n if (response.status === 403) {\n return {\n success: false,\n error: {\n kind: \"auth\",\n message: \"Forbidden\",\n },\n };\n }\n return {\n success: false,\n error: {\n kind: \"network\",\n code: response.status,\n message: response.statusText || `HTTP error ${response.status}`,\n },\n };\n }\n\n try {\n const data = (await response.json()) as T;\n return { success: true, data };\n } catch {\n return {\n success: false,\n error: {\n kind: \"parse\",\n message: \"Response could not be parsed as JSON\",\n },\n };\n }\n } catch (err) {\n return {\n success: false,\n error: {\n kind: \"network\",\n code: 0,\n message:\n err instanceof Error ? err.message : \"Network request failed\",\n },\n };\n }\n }\n\n /** Fetches the full active playlist for this device. */\n async fetchPlaylist(): Promise<SquareScreenResult<Playlist>> {\n const result = await this.fetchWrapper<ApiPlaylistResponse>(\n \"/screen/now-playing\",\n { method: \"GET\" },\n );\n if (!result.success) return result;\n return { success: true, data: mapPlaylistResponse(result.data) };\n }\n\n /** Fetches a playlist filtered to video items only. */\n async fetchVideoPlaylist(\n params: VideoPlaylistParams,\n ): Promise<SquareScreenResult<Playlist>> {\n const query = new URLSearchParams({\n type: \"video\",\n ...(params.category && { category: params.category }),\n ...(params.quality && { quality: params.quality }),\n ...(params.limit && { limit: String(params.limit) }),\n ...(params.tags && { tags: params.tags.join(\",\") }),\n });\n const result = await this.fetchWrapper<ApiPlaylistResponse>(\n `/screen/now-playing?${query}`,\n { method: \"GET\" },\n );\n if (!result.success) return result;\n return { success: true, data: mapPlaylistResponse(result.data) };\n }\n\n /** Fetches a playlist filtered to image items only. */\n async fetchImagePlaylist(\n params: ImagePlaylistParams,\n ): Promise<SquareScreenResult<Playlist>> {\n const query = new URLSearchParams({\n type: \"image\",\n ...(params.category && { category: params.category }),\n ...(params.limit && { limit: String(params.limit) }),\n ...(params.tags && { tags: params.tags.join(\",\") }),\n });\n const result = await this.fetchWrapper<ApiPlaylistResponse>(\n `/screen/now-playing?${query}`,\n { method: \"GET\" },\n );\n if (!result.success) return result;\n return { success: true, data: mapPlaylistResponse(result.data) };\n }\n\n /**\n * Checks whether an emergency broadcast is currently active for this device.\n * Resolves to `null` when no emergency is active.\n */\n async checkForEmergencyAlert(): Promise<\n SquareScreenResult<EmergencyAlert | null>\n > {\n const result = await this.fetchWrapper<ApiEmergencyResponse>(\n \"/screen/emergency\",\n { method: \"GET\" },\n );\n if (!result.success) return result;\n return { success: true, data: mapEmergencyResponse(result.data) };\n }\n\n /**\n * Posts device health metrics to the server.\n * The payload is mapped to snake_case before sending to match the API's expected format.\n *\n * @param payload - Collected device metrics. Hardware fields are optional;\n * `playerVersion` is always required.\n */\n async healthCheck(\n payload: HeartbeatPayload,\n ): Promise<SquareScreenResult<HeartbeatAck>> {\n const result = await this.fetchWrapper<ApiHeartbeatAck>(\n \"/screen/heartbeat\",\n { method: \"POST\", body: JSON.stringify(mapHeartbeatPayload(payload)) },\n );\n if (!result.success) return result;\n return { success: true, data: mapHeartbeatAck(result.data) };\n }\n\n /** Reports a playback event to the server.\n * @param event - The playback event to report.\n * @returns A result indicating whether the event was recorded successfully.\n * @example\n * const result = await networkClient.reportPlaybackEvent({\n * media_uuid: \"mf-00000001-0000-0000-0000-000000000001\",\n * playlist_uuid: \"pl-00000001-0000-0000-0000-000000000001\",\n * schedule_uuid: \"sc-00000001-0000-0000-0000-000000000001\",\n * started_at: \"2026-04-28T07:05:00Z\",\n * ended_at: \"2026-04-28T07:05:10Z\",\n * });\n */\n async reportPlaybackEvent(\n event: PlaybackEvent,\n ): Promise<SquareScreenResult<{ recorded: boolean }>> {\n const result = await this.fetchWrapper<{ recorded: boolean }>(\n \"/screen/playback\",\n { method: \"POST\", body: JSON.stringify(event) },\n );\n if (!result.success) return result;\n return { success: true, data: { recorded: result.data.recorded } };\n }\n}\n","import { openDB, deleteDB } from \"idb\";\nimport { Playlist, SquareScreenCacheProvider } from \"../core/types\";\n\nconst DEFAULT_DB_NAME = \"square-screen-cache\";\nconst DEFAULT_CACHE_NAME = \"square-screen-cache\";\n\n/**\n * Default {@link SquareScreenCacheProvider} backed by IndexedDB (playlist metadata)\n * and the Cache API (media blobs).\n *\n * **IndexedDB** — a single `playlists` object store holds one document per\n * playlist UUID. A private `_ttl` field (milliseconds) is stored alongside the\n * record and stripped before returning data to callers.\n *\n * **Cache API** — media files are stored under their original URL as the cache\n * key, matching the same URL-keyed approach used by the Android SDK's\n * `MediaFileCache`. Once a blob is retrieved from the Cache API it is wrapped\n * in a `URL.createObjectURL` handle that is kept in an in-memory map and reused\n * on subsequent calls to avoid redundant allocations. All handles are revoked\n * when {@link clear} is called.\n *\n * Integrators who need different storage behaviour (a service-worker cache,\n * an in-memory store for tests, a custom database) should implement\n * {@link SquareScreenCacheProvider} and pass it via\n * `SquareScreenPlayerConfig.cacheProvider`.\n */\nexport class SquareScreenCache implements SquareScreenCacheProvider {\n private readonly dbName: string;\n private readonly cacheName: string;\n /** Tracks the blob URL created for each media URL so it is reused across calls. */\n private readonly objectUrls = new Map<string, string>();\n\n /**\n * @param dbName Name of the IndexedDB database. Override in tests to isolate state.\n * @param cacheName Name of the Cache API bucket. Override in tests to isolate state.\n */\n constructor({\n dbName = DEFAULT_DB_NAME,\n cacheName = DEFAULT_CACHE_NAME,\n }: { dbName?: string; cacheName?: string } = {}) {\n this.dbName = dbName;\n this.cacheName = cacheName;\n }\n\n /** Opens (or lazily creates) the IndexedDB database with the `playlists` object store. */\n private openDB() {\n return openDB(this.dbName, 1, {\n upgrade(db) {\n if (!db.objectStoreNames.contains(\"playlists\")) {\n db.createObjectStore(\"playlists\", { keyPath: \"uuid\" });\n }\n },\n });\n }\n\n /**\n * Returns the cached playlist for the given UUID, or `null` if:\n * - nothing has been stored for that UUID, or\n * - the record's age exceeds its TTL and `allowStale` is `false`.\n *\n * @param uuid The playlist UUID to look up.\n * @param allowStale When `true`, expired records are returned as-is (useful\n * for serving a fallback when the network is unreachable).\n */\n async getPlaylist(uuid: string, allowStale = false): Promise<Playlist | null> {\n const db = await this.openDB();\n const record = await db.get(\"playlists\", uuid);\n if (!record) return null;\n if (!allowStale && Date.now() - record.cachedAt > record._ttl) return null;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- strip cache metadata before return\n const { _ttl, ...playlist } = record;\n return playlist as Playlist;\n }\n\n /**\n * Persists a playlist to IndexedDB, overwriting any previous record with the\n * same UUID. `cachedAt` is set to the current wall-clock time so that TTL\n * checks in {@link getPlaylist} have an accurate baseline.\n *\n * @param playlist The playlist to store. Items are persisted inline as part\n * of the same document — no separate per-item records.\n * @param ttlMs How long (in milliseconds) the record is considered fresh.\n * Passed through `SquareScreenPlayerConfig.ttl` by the player.\n */\n async savePlaylist(playlist: Playlist, ttlMs: number): Promise<void> {\n const db = await this.openDB();\n await db.put(\"playlists\", { ...playlist, cachedAt: Date.now(), _ttl: ttlMs });\n }\n\n /**\n * Returns a blob URL for the locally cached copy of `url`, or `null` if the\n * media has not been downloaded yet.\n *\n * The blob URL is created once and stored in an in-memory map. Subsequent\n * calls for the same `url` return the same handle without re-reading the\n * Cache API, which avoids both I/O and unnecessary `URL.createObjectURL`\n * allocations on long-running signage devices.\n *\n * @param url The original remote URL used as the Cache API key.\n */\n async getMediaUrl(url: string): Promise<string | null> {\n const existing = this.objectUrls.get(url);\n if (existing) return existing;\n\n const cache = await caches.open(this.cacheName);\n const response = await cache.match(url);\n if (!response) return null;\n\n const blob = await response.blob();\n const objectUrl = URL.createObjectURL(blob);\n this.objectUrls.set(url, objectUrl);\n return objectUrl;\n }\n\n /**\n * Stores `blob` in the Cache API under `url` and returns a blob URL for\n * immediate use by the renderer.\n *\n * Called by the player after a successful `fetch()` so that subsequent\n * {@link getMediaUrl} calls for the same URL skip the network entirely.\n *\n * @param url The original remote URL — used as the Cache API key so that\n * {@link getMediaUrl} can retrieve the entry with a simple `match`.\n * @param blob The downloaded media blob to persist.\n * @returns A blob URL that the renderer can set as `src` on an\n * `<img>` or `<video>` element.\n */\n async saveMedia(url: string, blob: Blob): Promise<string> {\n const cache = await caches.open(this.cacheName);\n await cache.put(url, new Response(blob));\n const objectUrl = URL.createObjectURL(blob);\n this.objectUrls.set(url, objectUrl);\n return objectUrl;\n }\n\n /**\n * Wipes all cached data:\n * - Revokes every outstanding blob URL to release the underlying Blob references.\n * - Deletes the IndexedDB database entirely (recreated on next access).\n * - Removes all entries from the Cache API bucket.\n *\n * Useful for a \"factory reset\" flow or in tests to guarantee a clean slate.\n */\n async clear(): Promise<void> {\n for (const url of this.objectUrls.values()) URL.revokeObjectURL(url);\n this.objectUrls.clear();\n const db = await this.openDB();\n db.close();\n await deleteDB(this.dbName);\n const cache = await caches.open(this.cacheName);\n const keys = await cache.keys();\n await Promise.all(keys.map((req) => cache.delete(req)));\n }\n}\n","import { SQUARESCREEN_API_BASE_URL } from \"../constants\";\nimport { NetworkClient } from \"../network/NetworkClient\";\nimport {\n DeviceStatus,\n EmergencyAlert,\n NetworkDataSource,\n PlaybackEvent,\n Playlist,\n PlaylistItem,\n SquareScreenCacheProvider,\n} from \"../core/types\";\nimport { SquareScreenCache } from \"../cache/SquareScreenCache\";\n\nconst LAST_PLAYLIST_KEY = \"square-screen:last-playlist-uuid\";\n\nexport interface SquareScreenPlayerConfig {\n /** Unique identifier for this device. */\n deviceId: string;\n /** Secret token used to authenticate this device. Never log or expose this value. */\n deviceToken: string;\n /** SDK version string sent on every heartbeat. */\n version: string;\n /** How long a cached playlist is considered fresh, in ms. Defaults to 5 minutes. */\n ttl?: number;\n /** How often to poll the API for playlist updates, in ms. Defaults to 30 seconds. */\n pollInterval?: number;\n /** How often to poll the API for emergency alerts, in ms. Defaults to 15 seconds. */\n emergencyPollInterval?: number;\n /** How often to send a heartbeat to the API, in ms. Defaults to 60 seconds. */\n heartbeatInterval?: number;\n /**\n * Override the network layer with a custom implementation — useful for testing\n * or mocking without a real API. When provided, `deviceId` and `deviceToken`\n * are ignored for network calls. Otherwise requests go to the production API\n * URL defined by {@link SQUARESCREEN_API_BASE_URL}.\n */\n networkDataSource?: NetworkDataSource;\n /**\n * Override the cache layer with a custom implementation. When omitted the default\n * `SquareScreenCache` (IndexedDB + Cache API) is used. Pass your own implementation\n * to integrate with an existing media storage layer.\n */\n cacheProvider?: SquareScreenCacheProvider;\n}\n\n/** Typed detail payloads for each player event. */\nexport type PlayerEventMap = {\n /** Fires when the current playlist item changes. */\n itemchange: CustomEvent<{ item: PlaylistItem; index: number; total: number }>;\n /** Fires when the device connectivity/sync status changes. */\n statuschange: CustomEvent<{ status: DeviceStatus }>;\n /** Fires when an emergency alert becomes active or is cleared. */\n emergencyalert: CustomEvent<{ alert: EmergencyAlert | null }>;\n /** Fires whenever the playlist is refreshed from the network or cache. */\n playlistupdate: CustomEvent<{ playlist: Playlist }>;\n};\n\n/**\n * Headless, framework-agnostic player that manages playlist fetching, caching,\n * item advancement, preloading, polling, and emergency alerts.\n *\n * Extends `EventTarget` — use `addEventListener` / `removeEventListener` to\n * react to player events. No DOM or rendering logic lives here.\n *\n * @example\n * const player = new SquareScreenPlayer({ deviceId, deviceToken, version: \"1.0.0\" });\n * player.addEventListener(\"itemchange\", ({ detail }) => render(detail.item));\n * player.addEventListener(\"emergencyalert\", ({ detail }) => showAlert(detail.alert));\n * await player.start();\n */\nexport class SquareScreenPlayer extends EventTarget {\n private readonly network: NetworkDataSource;\n private readonly cache: SquareScreenCacheProvider;\n private readonly config: Required<\n Omit<SquareScreenPlayerConfig, \"networkDataSource\" | \"cacheProvider\">\n >;\n\n private playlist: Playlist | null = null;\n private stopped = false;\n private currentIndex = 0;\n private status: DeviceStatus = \"connecting\";\n private activeAlert: EmergencyAlert | null = null;\n private currentItemStartTime: number | null = null;\n\n private itemTimer: ReturnType<typeof setTimeout> | null = null;\n private playlistPollTimer: ReturnType<typeof setInterval> | null = null;\n private emergencyPollTimer: ReturnType<typeof setInterval> | null = null;\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n\n constructor(config: SquareScreenPlayerConfig) {\n super();\n\n if (!config.networkDataSource) {\n if (!config.deviceId) throw new Error(\"SquareScreenPlayer: deviceId is required.\");\n if (!config.deviceToken) throw new Error(\"SquareScreenPlayer: deviceToken is required.\");\n }\n\n this.network =\n config.networkDataSource ??\n new NetworkClient(SQUARESCREEN_API_BASE_URL, config.deviceId, config.deviceToken);\n\n this.cache = config.cacheProvider ?? new SquareScreenCache();\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- omit injected deps from persisted config snapshot\n const { networkDataSource: _n, cacheProvider: _c, ...rest } = config;\n this.config = {\n ttl: 5 * 60 * 1000,\n pollInterval: 30_000,\n emergencyPollInterval: 15_000,\n heartbeatInterval: 60_000,\n ...rest,\n };\n }\n\n /** The playlist item currently being displayed, or null if no playlist is loaded. */\n get currentItem(): PlaylistItem | null {\n return this.playlist?.items[this.currentIndex] ?? null;\n }\n\n /**\n * Starts the player: fetches the playlist, begins playback, and starts polling\n * and heartbeat intervals. Safe to await — resolves once the first playlist load\n * attempt completes (whether from network or cache fallback).\n */\n async start(): Promise<void> {\n this.stopped = false;\n this.setStatus(\"connecting\");\n await this.loadPlaylist();\n await this.checkEmergencyAlert();\n this.startPolling();\n this.startHeartbeat();\n }\n\n /** Stops all timers and clears internal state. Call this when tearing down the player. */\n stop(): void {\n if (this.itemTimer) clearTimeout(this.itemTimer);\n if (this.playlistPollTimer) clearInterval(this.playlistPollTimer);\n if (this.emergencyPollTimer) clearInterval(this.emergencyPollTimer);\n if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);\n this.itemTimer = null;\n this.playlistPollTimer = null;\n this.emergencyPollTimer = null;\n this.heartbeatTimer = null;\n // Prevent in-flight loadPlaylist/applyPlaylist/scheduleItem continuations\n // from dispatching events or setting new timers after teardown.\n this.stopped = true;\n this.playlist = null;\n }\n\n // ---------------------------------------------------------------------------\n // Playlist loading\n // ---------------------------------------------------------------------------\n\n /**\n * Network-first playlist load. On success the playlist is saved to cache and\n * applied if the UUID changed. On failure the player falls back to the last\n * known playlist UUID stored in `localStorage`, loading it from cache with\n * `allowStale = true` so it is served even after its TTL has expired.\n */\n private async loadPlaylist(): Promise<void> {\n const result = await this.network.fetchPlaylist();\n\n if (result.success) {\n this.setStatus(\"online\");\n const playlist = result.data;\n localStorage.setItem(LAST_PLAYLIST_KEY, playlist.uuid);\n await this.cache.savePlaylist(playlist, this.config.ttl);\n\n const isNewPlaylist = !this.playlist || this.playlist.uuid !== playlist.uuid;\n if (isNewPlaylist) {\n await this.applyPlaylist(playlist);\n } else {\n this.dispatch(\"playlistupdate\", { playlist });\n }\n } else {\n this.setStatus(\"offline\");\n if (!this.playlist) {\n const lastUuid = localStorage.getItem(LAST_PLAYLIST_KEY);\n if (lastUuid) {\n const cached = await this.cache.getPlaylist(lastUuid, true);\n if (cached) await this.applyPlaylist(cached);\n }\n }\n }\n }\n\n /**\n * Activates a playlist: optionally shuffles the items, resets the index to 0,\n * emits `playlistupdate`, and kicks off the first `scheduleItem` call.\n * Bails out immediately if `stop()` has been called.\n */\n private async applyPlaylist(playlist: Playlist): Promise<void> {\n if (this.stopped) return;\n const items = playlist.strategy?.shuffle\n ? [...playlist.items].sort(() => Math.random() - 0.5)\n : playlist.items;\n\n this.playlist = { ...playlist, items };\n this.currentIndex = 0;\n this.dispatch(\"playlistupdate\", { playlist: this.playlist });\n this.scheduleItem();\n }\n\n refreshPlaylist(): void {\n this.loadPlaylist();\n }\n\n // ---------------------------------------------------------------------------\n // Playback\n // ---------------------------------------------------------------------------\n\n /**\n * Emits `itemchange` immediately with either the cached blob URL or the raw\n * HTTPS URL, then arms the advancement timer. Never blocks on a network fetch —\n * if the media isn't cached yet the browser loads it directly while\n * `preloadNext` / `downloadInBackground` cache it for the next cycle.\n *\n * Guards against `stop()` being called while awaiting the cache lookup.\n */\n private async scheduleItem(): Promise<void> {\n if (this.itemTimer) clearTimeout(this.itemTimer);\n\n const item = this.currentItem;\n if (!item || !this.playlist) return;\n\n this.currentItemStartTime = Date.now();\n\n // Cache lookup only — never fetch inline so the timer isn't delayed.\n const url = (await this.cache.getMediaUrl(item.url)) ?? item.url;\n if (!this.playlist) return; // stopped while awaiting\n\n this.dispatch(\"itemchange\", {\n item: { ...item, url },\n index: this.currentIndex,\n total: this.playlist.items.length,\n });\n\n // If the current item wasn't in cache, download it now for the next cycle.\n if (url === item.url) this.downloadInBackground(item.url);\n this.preloadNext();\n const elapsed = Date.now() - this.currentItemStartTime!;\n const remaining = Math.max(0, item.duration * 1000 - elapsed);\n this.itemTimer = setTimeout(() => this.advance(), remaining);\n }\n\n /**\n * Schedules background downloads for upcoming items while the current one\n * is playing, so subsequent transitions can serve blob URLs immediately.\n *\n * - `preloadCount: 0` — disabled; nothing is downloaded.\n * - `preloadCount: N` — downloads the next N items ahead (wraps at end).\n * - `preloadCount` absent — downloads all items in the playlist up front.\n */\n private preloadNext(): void {\n if (!this.playlist) return;\n const preloadCount = this.playlist.strategy?.preloadCount;\n if (preloadCount === 0) return;\n const count = preloadCount ?? this.playlist.items.length;\n\n for (let i = 1; i <= count; i++) {\n const idx = (this.currentIndex + i) % this.playlist.items.length;\n this.downloadInBackground(this.playlist.items[idx].url);\n }\n }\n\n /**\n * Fire-and-forget download. Checks the cache first; if the media is already\n * present the call is a no-op. Errors are silently swallowed — a failed\n * download is not fatal; the raw URL will be used until the next successful download.\n */\n private downloadInBackground(url: string): void {\n this.cache\n .getMediaUrl(url)\n .then((cached) => {\n if (cached || !this.playlist) return;\n return fetch(url, { mode: \"cors\" })\n .then((r) => (r.ok ? r.blob() : Promise.reject(new Error(`HTTP ${r.status}`))))\n .then((blob) => this.cache.saveMedia(url, blob));\n })\n .catch(() => {});\n }\n\n /**\n * Moves to the next item. Reports the completed playback event, then either\n * wraps back to index 0 (when `loop` is true or absent) or halts when\n * `loop: false` and the last item has finished.\n */\n private advance(): void {\n if (!this.playlist) return;\n const total = this.playlist.items.length;\n const next = this.currentIndex + 1;\n\n this.reportPlaybackEvent();\n\n if (next >= total) {\n if (this.playlist.strategy?.loop ?? true) {\n this.currentIndex = 0;\n } else {\n return;\n }\n } else {\n this.currentIndex = next;\n }\n\n this.scheduleItem();\n }\n\n /** Sends a proof-of-play event to the server. Fire-and-forget; failures are not surfaced. */\n private async reportPlaybackEvent(): Promise<void> {\n if (!this.currentItemStartTime) return;\n if (!this.currentItem || !this.playlist) return;\n const endedAt = Date.now();\n const event: PlaybackEvent = {\n media_uuid: this.currentItem.uuid,\n playlist_uuid: this.playlist.uuid,\n schedule_uuid: this.playlist.schedule?.uuid ?? \"\",\n started_at: new Date(this.currentItemStartTime).toISOString(),\n ended_at: new Date(endedAt).toISOString(),\n duration_seconds: Math.round((endedAt - this.currentItemStartTime) / 1000),\n completed: true,\n };\n this.network.reportPlaybackEvent(event);\n }\n\n // ---------------------------------------------------------------------------\n // Polling and heartbeat\n // ---------------------------------------------------------------------------\n\n /** Arms the playlist-refresh and emergency-alert polling intervals. */\n private startPolling(): void {\n this.playlistPollTimer = setInterval(\n () => this.loadPlaylist(),\n this.config.pollInterval,\n );\n this.emergencyPollTimer = setInterval(\n () => this.checkEmergencyAlert(),\n this.config.emergencyPollInterval,\n );\n }\n\n /** Arms the periodic heartbeat that keeps the device registration alive. */\n private startHeartbeat(): void {\n this.heartbeatTimer = setInterval(async () => {\n await this.network.healthCheck({ playerVersion: this.config.version });\n }, this.config.heartbeatInterval);\n }\n\n /**\n * Polls the server for an active emergency alert. Emits `emergencyalert` only\n * when the state actually changes (alert activated, cleared, or replaced by a\n * different UUID) to avoid redundant re-renders on the consumer side.\n */\n private async checkEmergencyAlert(): Promise<void> {\n const result = await this.network.checkForEmergencyAlert();\n if (!result.success) return;\n\n const incoming = result.data;\n const wasActive = this.activeAlert !== null;\n const isActive = incoming !== null;\n const alertChanged = isActive && incoming!.uuid !== this.activeAlert?.uuid;\n\n if (wasActive !== isActive || alertChanged) {\n this.activeAlert = incoming;\n this.dispatch(\"emergencyalert\", { alert: incoming });\n }\n }\n\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n private setStatus(status: DeviceStatus): void {\n if (this.status === status) return;\n this.status = status;\n this.dispatch(\"statuschange\", { status });\n }\n\n private dispatch<K extends keyof PlayerEventMap>(\n type: K,\n detail: PlayerEventMap[K] extends CustomEvent<infer D> ? D : never,\n ): void {\n this.dispatchEvent(new CustomEvent(type, { detail }));\n }\n\n addEventListener<K extends keyof PlayerEventMap>(\n type: K,\n listener: (event: PlayerEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions,\n ): void;\n addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n addEventListener(type: string, listener: any, options?: any): void {\n super.addEventListener(type, listener, options);\n }\n\n removeEventListener<K extends keyof PlayerEventMap>(\n type: K,\n listener: (event: PlayerEventMap[K]) => void,\n options?: boolean | EventListenerOptions,\n ): void;\n removeEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n removeEventListener(type: string, listener: any, options?: any): void {\n super.removeEventListener(type, listener, options);\n }\n}\n","import { EmergencyAlert, PlaylistItem, TransitionType } from \"../core/types\";\nimport { SquareScreenPlayer, PlayerEventMap } from \"../player/SquareScreenPlayer\";\n\nexport interface SquareScreenRendererConfig {\n /** Transition to use when an item doesn't specify one. Defaults to `\"none\"`. */\n defaultTransition?: TransitionType;\n /** Duration of transition animations in ms. Defaults to `500`. */\n transitionDuration?: number;\n /**\n * Maximum ms to wait for a video to reach `canplay` before transitioning anyway.\n * Keeps transitions on-time when media loads from a slow network.\n * Defaults to `3000`. Set to `0` to transition immediately without waiting.\n */\n canPlayTimeout?: number;\n}\n\n/**\n * Optional vanilla JS renderer that wires a {@link SquareScreenPlayer} to a DOM container.\n * Handles `<img>` / `<video>` element lifecycle, autoplay, transitions, and emergency alerts.\n *\n * When an emergency alert is active it renders a full-screen overlay on top of all content.\n * Normal playback resumes automatically once the alert is cleared.\n *\n * @example\n * const player = new SquareScreenPlayer({ ... });\n * const renderer = new SquareScreenRenderer(document.getElementById(\"screen\"), player);\n * renderer.mount();\n * await player.start();\n *\n * // Tear down\n * player.stop();\n * renderer.unmount();\n */\nexport class SquareScreenRenderer {\n private readonly container: HTMLElement;\n private readonly player: SquareScreenPlayer;\n private readonly config: Required<SquareScreenRendererConfig>;\n\n private wrapper: HTMLDivElement | null = null;\n /** Two slots that alternate as current/next during transitions. */\n private slots: [HTMLDivElement, HTMLDivElement] | null = null;\n private activeSlot = 0;\n private alertOverlay: HTMLDivElement | null = null;\n\n private readonly onItemChange: (event: PlayerEventMap[\"itemchange\"]) => void;\n private readonly onEmergencyAlert: (event: PlayerEventMap[\"emergencyalert\"]) => void;\n\n constructor(\n container: HTMLElement,\n player: SquareScreenPlayer,\n config: SquareScreenRendererConfig = {},\n ) {\n this.container = container;\n this.player = player;\n this.config = {\n defaultTransition: \"none\",\n transitionDuration: 500,\n canPlayTimeout: 3000,\n ...config,\n };\n this.onItemChange = (e) => this.handleItemChange(e.detail.item);\n this.onEmergencyAlert = (e) => this.handleEmergencyAlert(e.detail.alert);\n }\n\n /** Injects the renderer DOM into the container and begins listening to the player. */\n mount(): void {\n this.buildDOM();\n this.player.addEventListener(\"itemchange\", this.onItemChange);\n this.player.addEventListener(\"emergencyalert\", this.onEmergencyAlert);\n }\n\n /** Removes the renderer DOM and stops listening to the player. */\n unmount(): void {\n this.player.removeEventListener(\"itemchange\", this.onItemChange);\n this.player.removeEventListener(\"emergencyalert\", this.onEmergencyAlert);\n if (this.wrapper && this.container.contains(this.wrapper)) {\n this.container.removeChild(this.wrapper);\n }\n this.wrapper = null;\n this.slots = null;\n }\n\n // ---------------------------------------------------------------------------\n // DOM setup\n // ---------------------------------------------------------------------------\n\n private buildDOM(): void {\n this.wrapper = document.createElement(\"div\");\n Object.assign(this.wrapper.style, {\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n overflow: \"hidden\",\n backgroundColor: \"#000\",\n });\n\n const slotA = this.createSlot(true);\n const slotB = this.createSlot(false);\n this.wrapper.appendChild(slotA);\n this.wrapper.appendChild(slotB);\n this.slots = [slotA, slotB];\n\n this.alertOverlay = document.createElement(\"div\");\n Object.assign(this.alertOverlay.style, {\n display: \"none\",\n position: \"absolute\",\n top: \"0\",\n right: \"0\",\n bottom: \"0\",\n left: \"0\",\n zIndex: \"9999\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n padding: \"2rem\",\n textAlign: \"center\",\n boxSizing: \"border-box\",\n });\n this.wrapper.appendChild(this.alertOverlay);\n\n this.container.appendChild(this.wrapper);\n }\n\n private createSlot(visible: boolean): HTMLDivElement {\n const slot = document.createElement(\"div\");\n Object.assign(slot.style, {\n position: \"absolute\",\n top: \"0\",\n right: \"0\",\n bottom: \"0\",\n left: \"0\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n opacity: visible ? \"1\" : \"0\",\n transition: `opacity ${this.config.transitionDuration}ms ease`,\n });\n return slot;\n }\n\n // ---------------------------------------------------------------------------\n // Item rendering\n // ---------------------------------------------------------------------------\n\n private async handleItemChange(item: PlaylistItem): Promise<void> {\n if (!this.slots) return;\n\n const nextIndex = (this.activeSlot + 1) % 2;\n const currentSlot = this.slots[this.activeSlot];\n const nextSlot = this.slots[nextIndex];\n\n nextSlot.innerHTML = \"\";\n const media =\n item.type === \"video\"\n ? this.createVideo(item.url)\n : this.createImage(item.url);\n nextSlot.appendChild(media);\n\n if (item.type === \"video\") {\n await this.waitForCanPlay(media as HTMLVideoElement);\n }\n\n const transitionType = item.transition ?? this.config.defaultTransition;\n await this.applyTransition(currentSlot, nextSlot, transitionType);\n\n this.activeSlot = nextIndex;\n }\n\n private handleEmergencyAlert(alert: EmergencyAlert | null): void {\n if (!this.alertOverlay) return;\n\n if (!alert) {\n this.alertOverlay.style.display = \"none\";\n this.alertOverlay.innerHTML = \"\";\n return;\n }\n\n this.alertOverlay.style.display = \"flex\";\n this.alertOverlay.style.backgroundColor = alert.backgroundColor;\n this.alertOverlay.style.color = alert.textColor;\n\n const title = document.createElement(\"h1\");\n title.textContent = alert.title;\n Object.assign(title.style, { margin: \"0 0 1rem\", fontSize: \"2.5rem\", fontWeight: \"bold\" });\n\n const message = document.createElement(\"p\");\n message.textContent = alert.message;\n Object.assign(message.style, { margin: \"0\", fontSize: \"1.5rem\" });\n\n this.alertOverlay.innerHTML = \"\";\n this.alertOverlay.appendChild(title);\n this.alertOverlay.appendChild(message);\n }\n\n private createImage(src: string): HTMLImageElement {\n const img = document.createElement(\"img\");\n Object.assign(img.style, {\n maxWidth: \"100%\",\n maxHeight: \"100%\",\n objectFit: \"contain\",\n });\n img.src = src;\n return img;\n }\n\n private createVideo(src: string): HTMLVideoElement {\n const video = document.createElement(\"video\");\n Object.assign(video.style, {\n width: \"100%\",\n height: \"100%\",\n objectFit: \"contain\",\n });\n video.src = src;\n video.autoplay = true;\n video.muted = true; // required for autoplay in most browsers\n video.playsInline = true; // required on iOS\n video.loop = true; // loop within the item's duration window\n return video;\n }\n\n private waitForCanPlay(video: HTMLVideoElement): Promise<void> {\n return new Promise((resolve) => {\n if (video.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA) {\n resolve();\n return;\n }\n const timeout = this.config.canPlayTimeout;\n const timer = timeout > 0 ? setTimeout(resolve, timeout) : null;\n const handler = () => {\n if (timer) clearTimeout(timer);\n video.removeEventListener(\"canplay\", handler);\n resolve();\n };\n video.addEventListener(\"canplay\", handler);\n });\n }\n\n // ---------------------------------------------------------------------------\n // Transitions\n // ---------------------------------------------------------------------------\n\n private async applyTransition(\n from: HTMLDivElement,\n to: HTMLDivElement,\n type: TransitionType,\n ): Promise<void> {\n const duration = this.config.transitionDuration;\n\n if (type === \"none\" || duration === 0) {\n from.style.opacity = \"0\";\n to.style.opacity = \"1\";\n } else if (type === \"fade\") {\n to.style.opacity = \"1\";\n from.style.opacity = \"0\";\n await this.wait(duration);\n } else if (type === \"slide\") {\n // Snap next slot into position off-screen (no animation), then slide both\n to.style.transition = \"none\";\n to.style.transform = \"translateX(100%)\";\n to.style.opacity = \"1\";\n void to.offsetWidth; // force reflow so the snap takes effect before animating\n\n to.style.transition = `transform ${duration}ms ease`;\n from.style.transition = `transform ${duration}ms ease`;\n to.style.transform = \"translateX(0)\";\n from.style.transform = \"translateX(-100%)\";\n await this.wait(duration);\n }\n\n // Reset both slots to a clean opacity-only state for the next transition\n from.style.transition = `opacity ${duration}ms ease`;\n from.style.transform = \"\";\n from.style.opacity = \"0\";\n to.style.transition = `opacity ${duration}ms ease`;\n to.style.transform = \"\";\n to.style.opacity = \"1\";\n }\n\n private wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,4BACX;;;;ACYF,SAAgB,gBAAgB,KAAoC;AAClE,QAAO;EACL,MAAM,IAAI;EACV,MAAM,IAAI;EACV,MAAM,IAAI;EACV,KAAK,IAAI;EACT,UAAU,IAAI;EACd,GAAI,IAAI,eAAe,KAAA,KAAa,EAClC,YAAY,IAAI,YACjB;EACD,GAAI,IAAI,UAAU,KAAA,KAAa,EAAE,OAAO,IAAI,OAAO;EACnD,GAAI,IAAI,WAAW,KAAA,KAAa,EAAE,QAAQ,IAAI,QAAQ;EACtD,GAAI,IAAI,UAAU,KAAA,KAAa,EAAE,OAAO,IAAI,OAAO;EACnD,GAAI,IAAI,cAAc,KAAA,KAAa,EAAE,WAAW,IAAI,WAAW;EAChE;;;;;;AAOH,SAAgB,oBACd,KAC8B;AAC9B,KAAI,MAAM,QAAQ,IAAI,CAAE,QAAO,KAAA;AAC/B,QAAO;EACL,MAAM,IAAI;EACV,SAAS,IAAI;EACb,cAAc,IAAI,iBAAiB;EACpC;;;AAIH,SAAgB,oBAAoB,KAAoC;AACtE,QAAO;EACL,MAAM,IAAI,SAAU;EACpB,OAAO,IAAI,MAAM,IAAI,gBAAgB;EACrC,UAAU,oBAAoB,IAAI,SAAS;EAC3C,UAAU,IAAI;EACd,cAAc,IAAI;EAClB,UAAU,KAAK,KAAK;EACrB;;;;;;AAOH,SAAgB,qBACd,KACuB;AACvB,KAAI,I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,QAAQ;AAC7C,aAAS;;AAEX,SAAM,iBAAiB,WAAW,QAAQ;IAC1C;;CAOJ,MAAc,gBACZ,MACA,IACA,MACe;EACf,MAAM,WAAW,KAAK,OAAO;AAE7B,MAAI,SAAS,UAAU,aAAa,GAAG;AACrC,QAAK,MAAM,UAAU;AACrB,MAAG,MAAM,UAAU;aACV,SAAS,QAAQ;AAC1B,MAAG,MAAM,UAAU;AACnB,QAAK,MAAM,UAAU;AACrB,SAAM,KAAK,KAAK,SAAS;aAChB,SAAS,SAAS;AAE3B,MAAG,MAAM,aAAa;AACtB,MAAG,MAAM,YAAY;AACrB,MAAG,MAAM,UAAU;AACd,MAAG;AAER,MAAG,MAAM,aAAa,aAAa,SAAS;AAC5C,QAAK,MAAM,aAAa,aAAa,SAAS;AAC9C,MAAG,MAAM,YAAY;AACrB,QAAK,MAAM,YAAY;AACvB,SAAM,KAAK,KAAK,SAAS;;AAI3B,OAAK,MAAM,aAAa,WAAW,SAAS;AAC5C,OAAK,MAAM,YAAY;AACvB,OAAK,MAAM,UAAU;AACrB,KAAG,MAAM,aAAa,WAAW,SAAS;AAC1C,KAAG,MAAM,YAAY;AACrB,KAAG,MAAM,UAAU;;CAGrB,KAAa,IAA2B;AACtC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC"}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
//#region src/constants.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Production root URL for the SquareScreen REST API.
|
|
4
|
+
*
|
|
5
|
+
* {@link SquareScreenPlayer} uses this for all network requests. Integrators cannot
|
|
6
|
+
* override it via player configuration; supply a custom {@link NetworkDataSource}
|
|
7
|
+
* only if you must talk to a different host (e.g. tests or a private gateway).
|
|
8
|
+
*/
|
|
9
|
+
declare const SQUARESCREEN_API_BASE_URL = "https://square-screen-api-development-f7zuxa.laravel.cloud/api/v1";
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region src/core/types.d.ts
|
|
12
|
+
/** The type of media content in a playlist item. Matches the string values returned by the API. */
|
|
13
|
+
type MediaType = "image" | "video";
|
|
14
|
+
/** The transition animation to apply when moving between playlist items. */
|
|
15
|
+
type TransitionType = "fade" | "slide" | "none";
|
|
16
|
+
/** The current connectivity and sync state of the device. */
|
|
17
|
+
type DeviceStatus = "connecting" | "online" | "offline" | "syncing";
|
|
18
|
+
/** Playback strategy metadata returned alongside a playlist. */
|
|
19
|
+
interface PlaybackStrategy {
|
|
20
|
+
loop: boolean;
|
|
21
|
+
shuffle: boolean;
|
|
22
|
+
/** Number of upcoming items to pre-download. 0 means no preloading. */
|
|
23
|
+
preloadCount?: number;
|
|
24
|
+
}
|
|
25
|
+
/** Schedule metadata associated with a playlist. */
|
|
26
|
+
interface Schedule {
|
|
27
|
+
uuid: string;
|
|
28
|
+
name: string;
|
|
29
|
+
/** Higher value means higher priority when multiple schedules overlap. */
|
|
30
|
+
priority: number;
|
|
31
|
+
}
|
|
32
|
+
/** Metadata about the playlist container returned by the API. */
|
|
33
|
+
interface PlaylistMeta {
|
|
34
|
+
uuid: string;
|
|
35
|
+
name: string;
|
|
36
|
+
}
|
|
37
|
+
/** A playlist returned from the API, representing everything the device should display. */
|
|
38
|
+
interface Playlist {
|
|
39
|
+
uuid: string;
|
|
40
|
+
items: PlaylistItem[];
|
|
41
|
+
/** Present when the backend includes scheduling/playback hints. Not always populated. */
|
|
42
|
+
strategy?: PlaybackStrategy;
|
|
43
|
+
/** Metadata about the active schedule driving this playlist. */
|
|
44
|
+
schedule?: Schedule;
|
|
45
|
+
/** Metadata about the playlist container itself. */
|
|
46
|
+
playlistMeta?: PlaylistMeta;
|
|
47
|
+
/** Unix timestamp (ms) recording when this playlist was stored in the local cache. */
|
|
48
|
+
cachedAt: number;
|
|
49
|
+
}
|
|
50
|
+
/** A single piece of content within a playlist. */
|
|
51
|
+
interface PlaylistItem {
|
|
52
|
+
uuid: string;
|
|
53
|
+
name: string;
|
|
54
|
+
type: MediaType;
|
|
55
|
+
/** URL of the media file to display. */
|
|
56
|
+
url: string;
|
|
57
|
+
/** How long to display this item, in seconds. */
|
|
58
|
+
duration: number;
|
|
59
|
+
/** Animation to use when transitioning away from this item. Defaults to none if absent. */
|
|
60
|
+
transition?: TransitionType;
|
|
61
|
+
/** Native width of the media in pixels. */
|
|
62
|
+
width?: number;
|
|
63
|
+
/** Native height of the media in pixels. */
|
|
64
|
+
height?: number;
|
|
65
|
+
/** Human-readable title. Present on some item types (e.g. video). */
|
|
66
|
+
title?: string;
|
|
67
|
+
/** Thumbnail URL for preloading previews. */
|
|
68
|
+
thumbnail?: string;
|
|
69
|
+
}
|
|
70
|
+
/** An active emergency broadcast targeting this device. */
|
|
71
|
+
interface EmergencyAlert {
|
|
72
|
+
/** Server-assigned integer ID. */
|
|
73
|
+
id: number;
|
|
74
|
+
uuid: string;
|
|
75
|
+
/** ID of the company that issued the broadcast. */
|
|
76
|
+
companyId: number;
|
|
77
|
+
title: string;
|
|
78
|
+
message: string;
|
|
79
|
+
/** Hex color string for the alert background, e.g. "#FF0000". */
|
|
80
|
+
backgroundColor: string;
|
|
81
|
+
/** Hex color string for the alert text, e.g. "#FFFFFF". */
|
|
82
|
+
textColor: string;
|
|
83
|
+
/** The scope this broadcast targets, e.g. "all", "workspace", "group", or "device". */
|
|
84
|
+
targetScope: string;
|
|
85
|
+
/** Whether this broadcast is currently active. */
|
|
86
|
+
isActive: boolean;
|
|
87
|
+
/** ISO 8601 timestamp when the broadcast started. */
|
|
88
|
+
startedAt: string;
|
|
89
|
+
/** ISO 8601 timestamp when the broadcast ended, or undefined if still active. */
|
|
90
|
+
endedAt?: string;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Device health metrics sent to the server on each heartbeat.
|
|
94
|
+
* All hardware metrics are optional — not all browsers expose them.
|
|
95
|
+
*/
|
|
96
|
+
interface HeartbeatPayload {
|
|
97
|
+
cpuUsage?: number;
|
|
98
|
+
memoryUsage?: number;
|
|
99
|
+
diskUsage?: number;
|
|
100
|
+
temperature?: number;
|
|
101
|
+
osVersion?: string;
|
|
102
|
+
/** The version string of this SDK, included on every heartbeat. */
|
|
103
|
+
playerVersion: string;
|
|
104
|
+
}
|
|
105
|
+
/** Acknowledgement returned by the server after a successful heartbeat POST. */
|
|
106
|
+
interface HeartbeatAck {
|
|
107
|
+
received: boolean;
|
|
108
|
+
}
|
|
109
|
+
/** Query parameters for filtering a playlist to video items only. */
|
|
110
|
+
interface VideoPlaylistParams {
|
|
111
|
+
category?: string;
|
|
112
|
+
tags?: string[];
|
|
113
|
+
quality?: string;
|
|
114
|
+
limit?: number;
|
|
115
|
+
}
|
|
116
|
+
/** Query parameters for filtering a playlist to image items only. */
|
|
117
|
+
interface ImagePlaylistParams {
|
|
118
|
+
category?: string;
|
|
119
|
+
tags?: string[];
|
|
120
|
+
limit?: number;
|
|
121
|
+
}
|
|
122
|
+
/** Playback event data sent to the server. */
|
|
123
|
+
interface PlaybackEvent {
|
|
124
|
+
media_uuid: string;
|
|
125
|
+
playlist_uuid: string;
|
|
126
|
+
schedule_uuid: string;
|
|
127
|
+
started_at: string;
|
|
128
|
+
ended_at: string;
|
|
129
|
+
/** Actual number of seconds the item was displayed. */
|
|
130
|
+
duration_seconds: number;
|
|
131
|
+
/** Whether the item played to its full duration without interruption. */
|
|
132
|
+
completed: boolean;
|
|
133
|
+
}
|
|
134
|
+
/** An HTTP-level failure — the request reached the server but returned an error status. */
|
|
135
|
+
interface NetworkError {
|
|
136
|
+
kind: "network";
|
|
137
|
+
code: number;
|
|
138
|
+
message: string;
|
|
139
|
+
}
|
|
140
|
+
/** The device credentials (ID or token) were rejected by the server. */
|
|
141
|
+
interface AuthError {
|
|
142
|
+
kind: "auth";
|
|
143
|
+
message: string;
|
|
144
|
+
}
|
|
145
|
+
/** Reading from or writing to the local cache failed. */
|
|
146
|
+
interface CacheError {
|
|
147
|
+
kind: "cache";
|
|
148
|
+
message: string;
|
|
149
|
+
}
|
|
150
|
+
/** The server response could not be parsed into the expected shape. */
|
|
151
|
+
interface ParseError {
|
|
152
|
+
kind: "parse";
|
|
153
|
+
message: string;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Signals that an emergency broadcast is active.
|
|
157
|
+
* The caller should switch to displaying the EmergencyAlert instead of normal content.
|
|
158
|
+
*/
|
|
159
|
+
interface EmergencyOverrideActive {
|
|
160
|
+
kind: "emergency_override";
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Every error the SDK can produce.
|
|
164
|
+
* Check the `kind` field to identify and handle each case.
|
|
165
|
+
*/
|
|
166
|
+
type SquareScreenError = NetworkError | AuthError | CacheError | ParseError | EmergencyOverrideActive;
|
|
167
|
+
/**
|
|
168
|
+
* The return type for all SDK operations that can fail.
|
|
169
|
+
*
|
|
170
|
+
* Check `result.success` first — TypeScript will then narrow the type
|
|
171
|
+
* so that `result.data` is only accessible on success and `result.error`
|
|
172
|
+
* is only accessible on failure.
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
* if (result.success) {
|
|
176
|
+
* console.log(result.data);
|
|
177
|
+
* } else {
|
|
178
|
+
* console.error(result.error.kind);
|
|
179
|
+
* }
|
|
180
|
+
*/
|
|
181
|
+
type SquareScreenResult<T> = {
|
|
182
|
+
success: true;
|
|
183
|
+
data: T;
|
|
184
|
+
} | {
|
|
185
|
+
success: false;
|
|
186
|
+
error: SquareScreenError;
|
|
187
|
+
};
|
|
188
|
+
interface NetworkDataSource {
|
|
189
|
+
fetchPlaylist: () => Promise<SquareScreenResult<Playlist>>;
|
|
190
|
+
fetchVideoPlaylist: (params: VideoPlaylistParams) => Promise<SquareScreenResult<Playlist>>;
|
|
191
|
+
fetchImagePlaylist: (params: ImagePlaylistParams) => Promise<SquareScreenResult<Playlist>>;
|
|
192
|
+
/** Resolves to null when no emergency is active. */
|
|
193
|
+
checkForEmergencyAlert: () => Promise<SquareScreenResult<EmergencyAlert | null>>;
|
|
194
|
+
healthCheck: (payload: HeartbeatPayload) => Promise<SquareScreenResult<HeartbeatAck>>;
|
|
195
|
+
reportPlaybackEvent: (event: PlaybackEvent) => Promise<SquareScreenResult<{
|
|
196
|
+
recorded: boolean;
|
|
197
|
+
}>>;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Abstraction over local storage. The default implementation is `SquareScreenCache`
|
|
201
|
+
* (IndexedDB for playlist metadata + Cache API for media blobs). Pass a custom
|
|
202
|
+
* implementation via `SquareScreenPlayerConfig.cacheProvider` to integrate with
|
|
203
|
+
* an existing storage layer.
|
|
204
|
+
*/
|
|
205
|
+
interface SquareScreenCacheProvider {
|
|
206
|
+
/** Returns the cached playlist, or null if not found / TTL expired. Pass `allowStale` to bypass TTL for offline fallback. */
|
|
207
|
+
getPlaylist(uuid: string, allowStale?: boolean): Promise<Playlist | null>;
|
|
208
|
+
/** Persists a playlist. `ttlMs` controls how long it is considered fresh. */
|
|
209
|
+
savePlaylist(playlist: Playlist, ttlMs: number): Promise<void>;
|
|
210
|
+
/** Returns a blob URL for the cached media, or null if not yet downloaded. */
|
|
211
|
+
getMediaUrl(url: string): Promise<string | null>;
|
|
212
|
+
/** Downloads and stores the media blob, returns a blob URL for immediate use. */
|
|
213
|
+
saveMedia(url: string, blob: Blob): Promise<string>;
|
|
214
|
+
/** Wipes all cached data (playlist metadata and media blobs). */
|
|
215
|
+
clear(): Promise<void>;
|
|
216
|
+
}
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region src/player/SquareScreenPlayer.d.ts
|
|
219
|
+
interface SquareScreenPlayerConfig {
|
|
220
|
+
/** Unique identifier for this device. */
|
|
221
|
+
deviceId: string;
|
|
222
|
+
/** Secret token used to authenticate this device. Never log or expose this value. */
|
|
223
|
+
deviceToken: string;
|
|
224
|
+
/** SDK version string sent on every heartbeat. */
|
|
225
|
+
version: string;
|
|
226
|
+
/** How long a cached playlist is considered fresh, in ms. Defaults to 5 minutes. */
|
|
227
|
+
ttl?: number;
|
|
228
|
+
/** How often to poll the API for playlist updates, in ms. Defaults to 30 seconds. */
|
|
229
|
+
pollInterval?: number;
|
|
230
|
+
/** How often to poll the API for emergency alerts, in ms. Defaults to 15 seconds. */
|
|
231
|
+
emergencyPollInterval?: number;
|
|
232
|
+
/** How often to send a heartbeat to the API, in ms. Defaults to 60 seconds. */
|
|
233
|
+
heartbeatInterval?: number;
|
|
234
|
+
/**
|
|
235
|
+
* Override the network layer with a custom implementation — useful for testing
|
|
236
|
+
* or mocking without a real API. When provided, `deviceId` and `deviceToken`
|
|
237
|
+
* are ignored for network calls. Otherwise requests go to the production API
|
|
238
|
+
* URL defined by {@link SQUARESCREEN_API_BASE_URL}.
|
|
239
|
+
*/
|
|
240
|
+
networkDataSource?: NetworkDataSource;
|
|
241
|
+
/**
|
|
242
|
+
* Override the cache layer with a custom implementation. When omitted the default
|
|
243
|
+
* `SquareScreenCache` (IndexedDB + Cache API) is used. Pass your own implementation
|
|
244
|
+
* to integrate with an existing media storage layer.
|
|
245
|
+
*/
|
|
246
|
+
cacheProvider?: SquareScreenCacheProvider;
|
|
247
|
+
}
|
|
248
|
+
/** Typed detail payloads for each player event. */
|
|
249
|
+
type PlayerEventMap = {
|
|
250
|
+
/** Fires when the current playlist item changes. */itemchange: CustomEvent<{
|
|
251
|
+
item: PlaylistItem;
|
|
252
|
+
index: number;
|
|
253
|
+
total: number;
|
|
254
|
+
}>; /** Fires when the device connectivity/sync status changes. */
|
|
255
|
+
statuschange: CustomEvent<{
|
|
256
|
+
status: DeviceStatus;
|
|
257
|
+
}>; /** Fires when an emergency alert becomes active or is cleared. */
|
|
258
|
+
emergencyalert: CustomEvent<{
|
|
259
|
+
alert: EmergencyAlert | null;
|
|
260
|
+
}>; /** Fires whenever the playlist is refreshed from the network or cache. */
|
|
261
|
+
playlistupdate: CustomEvent<{
|
|
262
|
+
playlist: Playlist;
|
|
263
|
+
}>;
|
|
264
|
+
};
|
|
265
|
+
/**
|
|
266
|
+
* Headless, framework-agnostic player that manages playlist fetching, caching,
|
|
267
|
+
* item advancement, preloading, polling, and emergency alerts.
|
|
268
|
+
*
|
|
269
|
+
* Extends `EventTarget` — use `addEventListener` / `removeEventListener` to
|
|
270
|
+
* react to player events. No DOM or rendering logic lives here.
|
|
271
|
+
*
|
|
272
|
+
* @example
|
|
273
|
+
* const player = new SquareScreenPlayer({ deviceId, deviceToken, version: "1.0.0" });
|
|
274
|
+
* player.addEventListener("itemchange", ({ detail }) => render(detail.item));
|
|
275
|
+
* player.addEventListener("emergencyalert", ({ detail }) => showAlert(detail.alert));
|
|
276
|
+
* await player.start();
|
|
277
|
+
*/
|
|
278
|
+
declare class SquareScreenPlayer extends EventTarget {
|
|
279
|
+
private readonly network;
|
|
280
|
+
private readonly cache;
|
|
281
|
+
private readonly config;
|
|
282
|
+
private playlist;
|
|
283
|
+
private stopped;
|
|
284
|
+
private currentIndex;
|
|
285
|
+
private status;
|
|
286
|
+
private activeAlert;
|
|
287
|
+
private currentItemStartTime;
|
|
288
|
+
private itemTimer;
|
|
289
|
+
private playlistPollTimer;
|
|
290
|
+
private emergencyPollTimer;
|
|
291
|
+
private heartbeatTimer;
|
|
292
|
+
constructor(config: SquareScreenPlayerConfig);
|
|
293
|
+
/** The playlist item currently being displayed, or null if no playlist is loaded. */
|
|
294
|
+
get currentItem(): PlaylistItem | null;
|
|
295
|
+
/**
|
|
296
|
+
* Starts the player: fetches the playlist, begins playback, and starts polling
|
|
297
|
+
* and heartbeat intervals. Safe to await — resolves once the first playlist load
|
|
298
|
+
* attempt completes (whether from network or cache fallback).
|
|
299
|
+
*/
|
|
300
|
+
start(): Promise<void>;
|
|
301
|
+
/** Stops all timers and clears internal state. Call this when tearing down the player. */
|
|
302
|
+
stop(): void;
|
|
303
|
+
/**
|
|
304
|
+
* Network-first playlist load. On success the playlist is saved to cache and
|
|
305
|
+
* applied if the UUID changed. On failure the player falls back to the last
|
|
306
|
+
* known playlist UUID stored in `localStorage`, loading it from cache with
|
|
307
|
+
* `allowStale = true` so it is served even after its TTL has expired.
|
|
308
|
+
*/
|
|
309
|
+
private loadPlaylist;
|
|
310
|
+
/**
|
|
311
|
+
* Activates a playlist: optionally shuffles the items, resets the index to 0,
|
|
312
|
+
* emits `playlistupdate`, and kicks off the first `scheduleItem` call.
|
|
313
|
+
* Bails out immediately if `stop()` has been called.
|
|
314
|
+
*/
|
|
315
|
+
private applyPlaylist;
|
|
316
|
+
refreshPlaylist(): void;
|
|
317
|
+
/**
|
|
318
|
+
* Emits `itemchange` immediately with either the cached blob URL or the raw
|
|
319
|
+
* HTTPS URL, then arms the advancement timer. Never blocks on a network fetch —
|
|
320
|
+
* if the media isn't cached yet the browser loads it directly while
|
|
321
|
+
* `preloadNext` / `downloadInBackground` cache it for the next cycle.
|
|
322
|
+
*
|
|
323
|
+
* Guards against `stop()` being called while awaiting the cache lookup.
|
|
324
|
+
*/
|
|
325
|
+
private scheduleItem;
|
|
326
|
+
/**
|
|
327
|
+
* Schedules background downloads for upcoming items while the current one
|
|
328
|
+
* is playing, so subsequent transitions can serve blob URLs immediately.
|
|
329
|
+
*
|
|
330
|
+
* - `preloadCount: 0` — disabled; nothing is downloaded.
|
|
331
|
+
* - `preloadCount: N` — downloads the next N items ahead (wraps at end).
|
|
332
|
+
* - `preloadCount` absent — downloads all items in the playlist up front.
|
|
333
|
+
*/
|
|
334
|
+
private preloadNext;
|
|
335
|
+
/**
|
|
336
|
+
* Fire-and-forget download. Checks the cache first; if the media is already
|
|
337
|
+
* present the call is a no-op. Errors are silently swallowed — a failed
|
|
338
|
+
* download is not fatal; the raw URL will be used until the next successful download.
|
|
339
|
+
*/
|
|
340
|
+
private downloadInBackground;
|
|
341
|
+
/**
|
|
342
|
+
* Moves to the next item. Reports the completed playback event, then either
|
|
343
|
+
* wraps back to index 0 (when `loop` is true or absent) or halts when
|
|
344
|
+
* `loop: false` and the last item has finished.
|
|
345
|
+
*/
|
|
346
|
+
private advance;
|
|
347
|
+
/** Sends a proof-of-play event to the server. Fire-and-forget; failures are not surfaced. */
|
|
348
|
+
private reportPlaybackEvent;
|
|
349
|
+
/** Arms the playlist-refresh and emergency-alert polling intervals. */
|
|
350
|
+
private startPolling;
|
|
351
|
+
/** Arms the periodic heartbeat that keeps the device registration alive. */
|
|
352
|
+
private startHeartbeat;
|
|
353
|
+
/**
|
|
354
|
+
* Polls the server for an active emergency alert. Emits `emergencyalert` only
|
|
355
|
+
* when the state actually changes (alert activated, cleared, or replaced by a
|
|
356
|
+
* different UUID) to avoid redundant re-renders on the consumer side.
|
|
357
|
+
*/
|
|
358
|
+
private checkEmergencyAlert;
|
|
359
|
+
private setStatus;
|
|
360
|
+
private dispatch;
|
|
361
|
+
addEventListener<K extends keyof PlayerEventMap>(type: K, listener: (event: PlayerEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void;
|
|
362
|
+
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
|
|
363
|
+
removeEventListener<K extends keyof PlayerEventMap>(type: K, listener: (event: PlayerEventMap[K]) => void, options?: boolean | EventListenerOptions): void;
|
|
364
|
+
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
|
|
365
|
+
}
|
|
366
|
+
//#endregion
|
|
367
|
+
//#region src/renderer/SquareScreenRenderer.d.ts
|
|
368
|
+
interface SquareScreenRendererConfig {
|
|
369
|
+
/** Transition to use when an item doesn't specify one. Defaults to `"none"`. */
|
|
370
|
+
defaultTransition?: TransitionType;
|
|
371
|
+
/** Duration of transition animations in ms. Defaults to `500`. */
|
|
372
|
+
transitionDuration?: number;
|
|
373
|
+
/**
|
|
374
|
+
* Maximum ms to wait for a video to reach `canplay` before transitioning anyway.
|
|
375
|
+
* Keeps transitions on-time when media loads from a slow network.
|
|
376
|
+
* Defaults to `3000`. Set to `0` to transition immediately without waiting.
|
|
377
|
+
*/
|
|
378
|
+
canPlayTimeout?: number;
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Optional vanilla JS renderer that wires a {@link SquareScreenPlayer} to a DOM container.
|
|
382
|
+
* Handles `<img>` / `<video>` element lifecycle, autoplay, transitions, and emergency alerts.
|
|
383
|
+
*
|
|
384
|
+
* When an emergency alert is active it renders a full-screen overlay on top of all content.
|
|
385
|
+
* Normal playback resumes automatically once the alert is cleared.
|
|
386
|
+
*
|
|
387
|
+
* @example
|
|
388
|
+
* const player = new SquareScreenPlayer({ ... });
|
|
389
|
+
* const renderer = new SquareScreenRenderer(document.getElementById("screen"), player);
|
|
390
|
+
* renderer.mount();
|
|
391
|
+
* await player.start();
|
|
392
|
+
*
|
|
393
|
+
* // Tear down
|
|
394
|
+
* player.stop();
|
|
395
|
+
* renderer.unmount();
|
|
396
|
+
*/
|
|
397
|
+
declare class SquareScreenRenderer {
|
|
398
|
+
private readonly container;
|
|
399
|
+
private readonly player;
|
|
400
|
+
private readonly config;
|
|
401
|
+
private wrapper;
|
|
402
|
+
/** Two slots that alternate as current/next during transitions. */
|
|
403
|
+
private slots;
|
|
404
|
+
private activeSlot;
|
|
405
|
+
private alertOverlay;
|
|
406
|
+
private readonly onItemChange;
|
|
407
|
+
private readonly onEmergencyAlert;
|
|
408
|
+
constructor(container: HTMLElement, player: SquareScreenPlayer, config?: SquareScreenRendererConfig);
|
|
409
|
+
/** Injects the renderer DOM into the container and begins listening to the player. */
|
|
410
|
+
mount(): void;
|
|
411
|
+
/** Removes the renderer DOM and stops listening to the player. */
|
|
412
|
+
unmount(): void;
|
|
413
|
+
private buildDOM;
|
|
414
|
+
private createSlot;
|
|
415
|
+
private handleItemChange;
|
|
416
|
+
private handleEmergencyAlert;
|
|
417
|
+
private createImage;
|
|
418
|
+
private createVideo;
|
|
419
|
+
private waitForCanPlay;
|
|
420
|
+
private applyTransition;
|
|
421
|
+
private wait;
|
|
422
|
+
}
|
|
423
|
+
//#endregion
|
|
424
|
+
//#region src/cache/SquareScreenCache.d.ts
|
|
425
|
+
/**
|
|
426
|
+
* Default {@link SquareScreenCacheProvider} backed by IndexedDB (playlist metadata)
|
|
427
|
+
* and the Cache API (media blobs).
|
|
428
|
+
*
|
|
429
|
+
* **IndexedDB** — a single `playlists` object store holds one document per
|
|
430
|
+
* playlist UUID. A private `_ttl` field (milliseconds) is stored alongside the
|
|
431
|
+
* record and stripped before returning data to callers.
|
|
432
|
+
*
|
|
433
|
+
* **Cache API** — media files are stored under their original URL as the cache
|
|
434
|
+
* key, matching the same URL-keyed approach used by the Android SDK's
|
|
435
|
+
* `MediaFileCache`. Once a blob is retrieved from the Cache API it is wrapped
|
|
436
|
+
* in a `URL.createObjectURL` handle that is kept in an in-memory map and reused
|
|
437
|
+
* on subsequent calls to avoid redundant allocations. All handles are revoked
|
|
438
|
+
* when {@link clear} is called.
|
|
439
|
+
*
|
|
440
|
+
* Integrators who need different storage behaviour (a service-worker cache,
|
|
441
|
+
* an in-memory store for tests, a custom database) should implement
|
|
442
|
+
* {@link SquareScreenCacheProvider} and pass it via
|
|
443
|
+
* `SquareScreenPlayerConfig.cacheProvider`.
|
|
444
|
+
*/
|
|
445
|
+
declare class SquareScreenCache implements SquareScreenCacheProvider {
|
|
446
|
+
private readonly dbName;
|
|
447
|
+
private readonly cacheName;
|
|
448
|
+
/** Tracks the blob URL created for each media URL so it is reused across calls. */
|
|
449
|
+
private readonly objectUrls;
|
|
450
|
+
/**
|
|
451
|
+
* @param dbName Name of the IndexedDB database. Override in tests to isolate state.
|
|
452
|
+
* @param cacheName Name of the Cache API bucket. Override in tests to isolate state.
|
|
453
|
+
*/
|
|
454
|
+
constructor({
|
|
455
|
+
dbName,
|
|
456
|
+
cacheName
|
|
457
|
+
}?: {
|
|
458
|
+
dbName?: string;
|
|
459
|
+
cacheName?: string;
|
|
460
|
+
});
|
|
461
|
+
/** Opens (or lazily creates) the IndexedDB database with the `playlists` object store. */
|
|
462
|
+
private openDB;
|
|
463
|
+
/**
|
|
464
|
+
* Returns the cached playlist for the given UUID, or `null` if:
|
|
465
|
+
* - nothing has been stored for that UUID, or
|
|
466
|
+
* - the record's age exceeds its TTL and `allowStale` is `false`.
|
|
467
|
+
*
|
|
468
|
+
* @param uuid The playlist UUID to look up.
|
|
469
|
+
* @param allowStale When `true`, expired records are returned as-is (useful
|
|
470
|
+
* for serving a fallback when the network is unreachable).
|
|
471
|
+
*/
|
|
472
|
+
getPlaylist(uuid: string, allowStale?: boolean): Promise<Playlist | null>;
|
|
473
|
+
/**
|
|
474
|
+
* Persists a playlist to IndexedDB, overwriting any previous record with the
|
|
475
|
+
* same UUID. `cachedAt` is set to the current wall-clock time so that TTL
|
|
476
|
+
* checks in {@link getPlaylist} have an accurate baseline.
|
|
477
|
+
*
|
|
478
|
+
* @param playlist The playlist to store. Items are persisted inline as part
|
|
479
|
+
* of the same document — no separate per-item records.
|
|
480
|
+
* @param ttlMs How long (in milliseconds) the record is considered fresh.
|
|
481
|
+
* Passed through `SquareScreenPlayerConfig.ttl` by the player.
|
|
482
|
+
*/
|
|
483
|
+
savePlaylist(playlist: Playlist, ttlMs: number): Promise<void>;
|
|
484
|
+
/**
|
|
485
|
+
* Returns a blob URL for the locally cached copy of `url`, or `null` if the
|
|
486
|
+
* media has not been downloaded yet.
|
|
487
|
+
*
|
|
488
|
+
* The blob URL is created once and stored in an in-memory map. Subsequent
|
|
489
|
+
* calls for the same `url` return the same handle without re-reading the
|
|
490
|
+
* Cache API, which avoids both I/O and unnecessary `URL.createObjectURL`
|
|
491
|
+
* allocations on long-running signage devices.
|
|
492
|
+
*
|
|
493
|
+
* @param url The original remote URL used as the Cache API key.
|
|
494
|
+
*/
|
|
495
|
+
getMediaUrl(url: string): Promise<string | null>;
|
|
496
|
+
/**
|
|
497
|
+
* Stores `blob` in the Cache API under `url` and returns a blob URL for
|
|
498
|
+
* immediate use by the renderer.
|
|
499
|
+
*
|
|
500
|
+
* Called by the player after a successful `fetch()` so that subsequent
|
|
501
|
+
* {@link getMediaUrl} calls for the same URL skip the network entirely.
|
|
502
|
+
*
|
|
503
|
+
* @param url The original remote URL — used as the Cache API key so that
|
|
504
|
+
* {@link getMediaUrl} can retrieve the entry with a simple `match`.
|
|
505
|
+
* @param blob The downloaded media blob to persist.
|
|
506
|
+
* @returns A blob URL that the renderer can set as `src` on an
|
|
507
|
+
* `<img>` or `<video>` element.
|
|
508
|
+
*/
|
|
509
|
+
saveMedia(url: string, blob: Blob): Promise<string>;
|
|
510
|
+
/**
|
|
511
|
+
* Wipes all cached data:
|
|
512
|
+
* - Revokes every outstanding blob URL to release the underlying Blob references.
|
|
513
|
+
* - Deletes the IndexedDB database entirely (recreated on next access).
|
|
514
|
+
* - Removes all entries from the Cache API bucket.
|
|
515
|
+
*
|
|
516
|
+
* Useful for a "factory reset" flow or in tests to guarantee a clean slate.
|
|
517
|
+
*/
|
|
518
|
+
clear(): Promise<void>;
|
|
519
|
+
}
|
|
520
|
+
//#endregion
|
|
521
|
+
export { type AuthError, type CacheError, type DeviceStatus, type EmergencyAlert, type EmergencyOverrideActive, type HeartbeatAck, type HeartbeatPayload, type ImagePlaylistParams, type MediaType, type NetworkDataSource, type NetworkError, type ParseError, type PlaybackEvent, type PlaybackStrategy, type PlayerEventMap, type Playlist, type PlaylistItem, type PlaylistMeta, SQUARESCREEN_API_BASE_URL, type Schedule, SquareScreenCache, type SquareScreenCacheProvider, type SquareScreenError, SquareScreenPlayer, type SquareScreenPlayerConfig, SquareScreenRenderer, type SquareScreenRendererConfig, type SquareScreenResult, type TransitionType, type VideoPlaylistParams };
|
|
522
|
+
//# sourceMappingURL=index.d.cts.map
|