### Manage Plugins with LunaPlugin
Source: https://context7.com/inrixia/tidaluna/llms.txt
Demonstrates how to load, enable, disable, install, and uninstall plugins using the LunaPlugin class. It also shows how to use the ReactiveStore for persistent plugin settings.
```typescript
import { LunaPlugin, ReactiveStore } from "@luna/core";
const plugin = await LunaPlugin.fromStorage({
url: "https://example.com/my-plugin",
enabled: true
});
const existingPlugin = LunaPlugin.getByName("@luna/lib");
await plugin.enable();
await plugin.disable();
await plugin.install();
await plugin.uninstall();
plugin.liveReload = true;
const storage = await ReactiveStore.getPluginStorage("my-plugin", {
myOption: true,
threshold: 50
});
storage.myOption = false;
```
--------------------------------
### Interact with MediaItem for Playback and Metadata
Source: https://context7.com/inrixia/tidaluna/llms.txt
Provides examples for retrieving media items, accessing metadata like lyrics and cover art, checking quality tags, and controlling playback or downloads.
```typescript
import { MediaItem, PlayState } from "@luna/lib";
const currentItem = await MediaItem.fromPlaybackContext();
console.log(currentItem?.tidalItem.title);
const track = await MediaItem.fromId(12345678, "track");
const title = await track.title();
const album = await track.album();
const artist = await track.artist();
const lyrics = await track.lyrics();
const coverUrl = await track.coverUrl({ res: "640" });
const quality = track.bestQuality;
const format = await track.updateFormat();
track.play();
await track.download("/path/to/save", "HI_RES_LOSSLESS");
MediaItem.onMediaTransition(unloads, (mediaItem) => {
console.log(`Now playing: ${mediaItem.tidalItem.title}`);
});
```
--------------------------------
### ReactiveStore for Persistent Storage
Source: https://context7.com/inrixia/tidaluna/llms.txt
Utilizes an IndexedDB-backed reactive storage for plugin settings. It automatically persists changes and supports reactive updates, offering methods for getting, setting, ensuring, deleting, and dumping store data.
```typescript
import { ReactiveStore } from "@luna/core";
// Get or create a named store
const store = ReactiveStore.getStore("my-plugin-data");
// Get reactive object (changes auto-persist)
const settings = await store.getReactive("settings", {
volume: 100,
notifications: true,
theme: "dark"
});
// Changes are automatically saved
settings.volume = 80;
settings.theme = "light";
// Simple key-value operations
await store.set("lastPlayed", Date.now());
const lastPlayed = await store.get("lastPlayed");
// Ensure value exists with default
const config = await store.ensure("config", { initialized: true });
// Delete key
await store.del("obsoleteKey");
// Get all keys
const keys = await store.keys();
// Dump entire store
const allData = await store.dump();
// Clear store
await store.clear();
// Plugin-specific storage helper
const pluginSettings = await ReactiveStore.getPluginStorage("my-plugin", {
option1: true,
option2: "default"
});
```
--------------------------------
### Configure Nix Flake Inputs and Overlays
Source: https://github.com/inrixia/tidaluna/blob/master/README.md
Configuration snippets for integrating TidaLuna into a Nix flake-based system configuration.
```nix
inputs.tidaLuna.url = "github:Inrixia/TidaLuna";
nixpkgs.overlay = [
inputs.tidaLuna.overlays.default
];
```
--------------------------------
### Album and Playlist Operations with MusicBrainz Integration (TypeScript)
Source: https://context7.com/inrixia/tidaluna/llms.txt
Demonstrates how to use the Album and Playlist wrapper classes to fetch metadata, iterate through media items, and access MusicBrainz data. It requires the '@luna/lib' package.
```typescript
import { Album, Playlist, MediaItem } from "@luna/lib";
// Album operations
const album = await Album.fromId(87654321);
const albumTitle = await album.title(); // Enhanced from MusicBrainz
const albumArtist = await album.artist();
const coverUrl = album.coverUrl({ res: "1280" });
const trackCount = album.numberOfTracks;
const genre = album.genre;
const label = album.recordLabel;
const releaseDate = album.releaseDate;
// Get album items as MediaItem objects
for await (const mediaItem of await album.mediaItems()) {
console.log(mediaItem.tidalItem.title);
}
// MusicBrainz data
const brainzAlbum = await album.brainzAlbum();
const brainzRelease = await album.brainzRelease();
const upc = await album.upc();
// Playlist operations
const playlist = await Playlist.fromId("playlist-uuid");
const playlistTitle = await playlist.title();
const itemCount = await playlist.count();
// Iterate playlist items
for await (const mediaItem of await playlist.mediaItems()) {
console.log(mediaItem.trackNumber, mediaItem.tidalItem.title);
}
```
--------------------------------
### Create Symbolic Link for Development
Source: https://github.com/inrixia/tidaluna/blob/master/README.md
Windows command to create a directory junction linking the local development dist folder to the Tidal resources directory for live testing.
```shell
mklink /D "%LOCALAPPDATA%\TIDAL\app-x.xx.x\resources\app" "./dist"
```
--------------------------------
### Album and Playlist Classes
Source: https://context7.com/inrixia/tidaluna/llms.txt
Wrapper classes for albums and playlists with MusicBrainz integration and media item iteration.
```APIDOC
## Album and Playlist Classes
Wrapper classes for albums and playlists with MusicBrainz integration and media item iteration.
### Description
Provides classes to represent and interact with albums and playlists, including fetching metadata from MusicBrainz and iterating through media items.
### Usage
```typescript
import { Album, Playlist, MediaItem } from "@luna/lib";
// Album operations
const album = await Album.fromId(87654321);
const albumTitle = await album.title(); // Enhanced from MusicBrainz
const albumArtist = await album.artist();
const coverUrl = album.coverUrl({ res: "1280" });
const trackCount = album.numberOfTracks;
const genre = album.genre;
const label = album.recordLabel;
const releaseDate = album.releaseDate;
// Get album items as MediaItem objects
for await (const mediaItem of await album.mediaItems()) {
console.log(mediaItem.tidalItem.title);
}
// MusicBrainz data
const brainzAlbum = await album.brainzAlbum();
const brainzRelease = await album.brainzRelease();
const upc = await album.upc();
// Playlist operations
const playlist = await Playlist.fromId("playlist-uuid");
const playlistTitle = await playlist.title();
const itemCount = await playlist.count();
// Iterate playlist items
for await (const mediaItem of await playlist.mediaItems()) {
console.log(mediaItem.trackNumber, mediaItem.tidalItem.title);
}
```
```
--------------------------------
### Register Custom UI Page with React
Source: https://context7.com/inrixia/tidaluna/llms.txt
Demonstrates registering a custom full-page UI view within the TIDAL client using React components. It covers component definition, registration, style customization, programmatic opening, and adding context menu entries.
```typescript
import { Page } from "@luna/ui";
import { ThemeProvider } from "@mui/material/styles";
import React from "react";
// Define your page component
const MySettingsPage: React.FC = () => (
My Plugin Settings
Configure your plugin here
);
// Register the page
const myPage = Page.register(
"MyPluginSettings",
unloads,
);
// Customize page background
myPage.pageStyles.background = "radial-gradient(ellipse at top left, rgba(88, 10, 82, 0.5), transparent 70%),
linear-gradient(to bottom, #1a1a2e, #16213e)";
// Open the page programmatically
myPage.open();
// Add context menu button to open page
const settingsButton = ContextMenu.addButton(unloads);
settingsButton.text = "My Plugin Settings";
settingsButton.onClick(() => myPage.open());
```
--------------------------------
### ReactiveStore (Persistent Storage)
Source: https://context7.com/inrixia/tidaluna/llms.txt
An IndexedDB-backed reactive storage solution for plugin settings. It automatically persists changes and supports reactive updates, simplifying the management of plugin data.
```APIDOC
## ReactiveStore (Persistent Storage)
IndexedDB-backed reactive storage for plugin settings that automatically persists changes and supports reactive updates.
```typescript
import { ReactiveStore } from "@luna/core";
// Get or create a named store
const store = ReactiveStore.getStore("my-plugin-data");
// Get reactive object (changes auto-persist)
const settings = await store.getReactive("settings", {
volume: 100,
notifications: true,
theme: "dark"
});
// Changes are automatically saved
settings.volume = 80;
settings.theme = "light";
// Simple key-value operations
await store.set("lastPlayed", Date.now());
const lastPlayed = await store.get("lastPlayed");
// Ensure value exists with default
const config = await store.ensure("config", { initialized: true });
// Delete key
await store.del("obsoleteKey");
// Get all keys
const keys = await store.keys();
// Dump entire store
const allData = await store.dump();
// Clear store
await store.clear();
// Plugin-specific storage helper
const pluginSettings = await ReactiveStore.getPluginStorage("my-plugin", {
option1: true,
option2: "default"
});
```
```
--------------------------------
### Injecting and Managing CSS Styles in TIDAL Client (TypeScript)
Source: https://context7.com/inrixia/tidaluna/llms.txt
Demonstrates how to use the StyleTag class to inject custom CSS into the TIDAL client, with automatic cleanup on plugin unload. Allows dynamic updates and direct access to the style element. Requires '@luna/lib'.
```typescript
import { StyleTag } from "@luna/lib";
// Create a style tag with CSS
const style = new StyleTag("my-plugin-styles", unloads, `
.my-custom-class {
color: #31d8ff;
font-weight: bold;
}
/* Hide specific TIDAL elements */
div[data-test="notification-update"] {
display: none !important;
}
`);
// Update CSS dynamically
style.css = `
.my-custom-class {
color: #ff00ff;
}
`;
// Remove style (also happens automatically on unload)
style.remove();
// Re-add style
style.add();
// Access underlying style element
const styleElement = style.styleTag;
```
--------------------------------
### TIDAL Quality Tier Handling and Conversion (TypeScript)
Source: https://context7.com/inrixia/tidaluna/llms.txt
Explains the usage of the Quality class for managing and comparing TIDAL's audio quality tiers. It provides methods for conversion from metadata tags and audio quality strings, and accessing quality properties. Requires '@luna/lib'.
```typescript
import { Quality } from "@luna/lib";
// Quality levels (highest to lowest)
Quality.HiRes; // Hi-Res Lossless (24-bit, up to 192kHz)
Quality.MQA; // MQA (Master Quality Authenticated)
Quality.Atmos; // Dolby Atmos
Quality.Sony630; // Sony 360 Reality Audio
Quality.High; // CD Quality Lossless (16-bit, 44.1kHz)
Quality.Low; // AAC 320kbps
Quality.Lowest; // AAC 96kbps
Quality.Max; // Alias for HiRes (highest available)
// Compare qualities
const q1 = Quality.HiRes;
const q2 = Quality.High;
console.log(q1 > q2); // true (valueOf returns index)
// Convert from TIDAL metadata tags
const qualities = Quality.fromMetaTags(["HIRES_LOSSLESS", "DOLBY_ATMOS"]);
// Returns [Quality.HiRes, Quality.Atmos]
// Convert from audio quality string
const quality = Quality.fromAudioQuality("HI_RES_LOSSLESS");
// Returns Quality.HiRes
// Get min/max from array
const best = Quality.max(Quality.High, Quality.MQA, Quality.Low);
// Returns Quality.MQA
// Convert back to TIDAL formats
const audioQualityStr = Quality.HiRes.audioQuality; // "HI_RES_LOSSLESS"
const metadataTag = Quality.HiRes.metadataTag; // "HIRES_LOSSLESS"
// Quality properties
console.log(Quality.HiRes.name); // "HiRes"
console.log(Quality.HiRes.color); // "#ffd432"
```
--------------------------------
### Replace Tidal Package in Nix Configuration
Source: https://github.com/inrixia/tidaluna/blob/master/README.md
Diff-style configuration to replace the standard tidal-hifi package with the TidaLuna version in Nix system packages.
```diff
environment.systemPackages = with pkgs; [
- tidal-hifi
+ inputs.tidaLuna.packages.${system}.default
];
```
--------------------------------
### ContextMenu Class
Source: https://context7.com/inrixia/tidaluna/llms.txt
Add custom buttons to TIDAL's context menus and listen for context menu events on media items.
```APIDOC
## ContextMenu Class
Add custom buttons to TIDAL's context menus and listen for context menu events on media items.
### Description
Allows developers to extend TIDAL's user interface by adding custom buttons to context menus and reacting to context menu events, including those specific to media items.
### Usage
```typescript
import { ContextMenu, Album, Playlist } from "@luna/lib";
// Add a custom context menu button
const myButton = ContextMenu.addButton(unloads);
myButton.text = "My Custom Action";
myButton.onClick((event) => {
console.log("Button clicked!", event);
});
// Listen for context menu opens and show button conditionally
ContextMenu.onOpen(unloads, async ({ event, contextMenu }) => {
if (event.type === "ALBUM" || event.type === "PLAYLIST") {
const elem = await myButton.show(contextMenu);
if (elem) elem.style.color = "#00ff00"; // Custom styling
}
});
// Listen for media item context menus specifically
ContextMenu.onMediaItem(unloads, async ({ mediaCollection, contextMenu }) => {
// mediaCollection can be MediaItems, Album, or Playlist
if (mediaCollection instanceof Album) {
console.log("Album context menu:", await mediaCollection.title());
}
// Show button on all media item menus
await myButton.show(contextMenu);
});
// Get current open context menu element
const currentMenu = await ContextMenu.getCurrent();
```
```
--------------------------------
### Custom Context Menu Button and Event Handling (TypeScript)
Source: https://context7.com/inrixia/tidaluna/llms.txt
Shows how to add custom buttons to TIDAL's context menus and respond to context menu events for media items, albums, and playlists. Requires '@luna/lib'. The 'unloads' parameter is a cleanup function.
```typescript
import { ContextMenu, Album, Playlist } from "@luna/lib";
// Add a custom context menu button
const myButton = ContextMenu.addButton(unloads);
myButton.text = "My Custom Action";
myButton.onClick((event) => {
console.log("Button clicked!", event);
});
// Listen for context menu opens and show button conditionally
ContextMenu.onOpen(unloads, async ({ event, contextMenu }) => {
if (event.type === "ALBUM" || event.type === "PLAYLIST") {
const elem = await myButton.show(contextMenu);
if (elem) elem.style.color = "#00ff00"; // Custom styling
}
});
// Listen for media item context menus specifically
ContextMenu.onMediaItem(unloads, async ({ mediaCollection, contextMenu }) => {
// mediaCollection can be MediaItems, Album, or Playlist
if (mediaCollection instanceof Album) {
console.log("Album context menu:", await mediaCollection.title());
}
// Show button on all media item menus
await myButton.show(contextMenu);
});
// Get current open context menu element
const currentMenu = await ContextMenu.getCurrent();
```
--------------------------------
### Plugin Lifecycle Management
Source: https://context7.com/inrixia/tidaluna/llms.txt
API methods for managing the lifecycle of plugins, including loading, enabling, disabling, and persisting plugin configurations.
```APIDOC
## Plugin Lifecycle Management
### Description
Manages the installation, activation, and configuration of plugins within the Tidal Luna framework.
### Methods
- **fromStorage(options)**: Loads a plugin from a URL.
- **getByName(name)**: Retrieves an existing plugin instance.
- **enable() / disable()**: Toggles plugin activity status.
- **install() / uninstall()**: Manages persistent plugin storage.
- **getPluginStorage(id, defaults)**: Returns a reactive store for plugin-specific settings.
### Request Example
const plugin = await LunaPlugin.fromStorage({ url: "https://example.com/my-plugin", enabled: true });
### Response
- **plugin** (Object) - The initialized plugin instance.
```
--------------------------------
### PlayState Class - Playback Controls
Source: https://context7.com/inrixia/tidaluna/llms.txt
Control playback, manage the queue, and adjust shuffle/repeat modes using the PlayState class.
```APIDOC
## PlayState Class - Playback Controls
### Description
Provides full control over playback state, queue management, shuffle, repeat modes, and scrobbling events.
### Methods
- `PlayState.play()`: Resume playback.
- `PlayState.play(trackId)`: Play a specific track.
- `PlayState.pause()`: Pause playback.
- `PlayState.next()`: Skip to the next track.
- `PlayState.previous()`: Go to the previous track.
- `PlayState.seek(seconds)`: Seek to a specific time in the current track.
- `PlayState.playNext(trackIds)`: Add tracks to the queue after the current track.
- `PlayState.moveTo(index)`: Jump to a specific index in the queue.
- `PlayState.setShuffle(enabled, shuffleItems)`: Enable or disable shuffle mode.
- `PlayState.setRepeatMode(mode)`: Set the repeat mode (e.g., `PlayState.RepeatMode.ONE`).
- `PlayState.nextMediaItem()`: Get the next media item in the queue.
- `PlayState.previousMediaItem()`: Get the previous media item in the queue.
- `PlayState.onState(unloads, callback)`: Listen for playback state changes.
- `PlayState.onScrobble(unloads, callback)`: Listen for scrobble events.
### Properties
- `PlayState.playing` (boolean): Indicates if playback is currently active.
- `PlayState.currentTime` (number): The live player position in seconds.
- `PlayState.playTime` (number): The Redux state position.
- `PlayState.shuffle` (any): Get the current shuffle state.
- `PlayState.repeatMode` (PlayState.RepeatMode): Get the current repeat mode.
```
--------------------------------
### Structured Logging with Tracer
Source: https://context7.com/inrixia/tidaluna/llms.txt
Implements structured logging and error signal support for displaying plugin errors in the Luna UI. It covers basic logging, error logging, user-visible messages, error handling with context, and creating sub-tracers for modularity.
```typescript
import { Tracer } from "@luna/core";
// Create a tracer for your plugin
const { trace, errSignal } = Tracer("[MyPlugin]");
export { errSignal }; // Export for Luna UI to show errors
// Basic logging
trace.log("Plugin loaded successfully");
trace.warn("Something might be wrong");
trace.debug("Debug information");
// Error logging (also sets errSignal)
trace.err("An error occurred", new Error("Details"));
// With message display (shows toast notification)
trace.msg.log("User-visible info message");
trace.msg.warn("User-visible warning");
trace.msg.err("User-visible error");
// Error handling with context
async function myAsyncFunction() {
await fetch("/api/data")
.catch(trace.err.withContext("Failed to fetch data"));
}
// Throw after logging
async function criticalFunction() {
await someOperation()
.catch(trace.err.withContext("Critical operation failed").throw);
}
// Create sub-tracers for different components
const apiTrace = trace.withSource(".API").trace;
a piTrace.log("API request"); // Logs: "[MyPlugin.API] API request"
```
--------------------------------
### StyleTag Class
Source: https://context7.com/inrixia/tidaluna/llms.txt
Inject and manage CSS styles in the TIDAL client with automatic cleanup on plugin unload.
```APIDOC
## StyleTag Class
Inject and manage CSS styles in the TIDAL client with automatic cleanup on plugin unload.
### Description
Provides a mechanism to dynamically inject CSS styles into the TIDAL application, with built-in handling for style removal when the plugin is unloaded.
### Usage
```typescript
import { StyleTag } from "@luna/lib";
// Create a style tag with CSS
const style = new StyleTag("my-plugin-styles", unloads, `
.my-custom-class {
color: #31d8ff;
font-weight: bold;
}
/* Hide specific TIDAL elements */
div[data-test="notification-update"] {
display: none !important;
}
`);
// Update CSS dynamically
style.css = `
.my-custom-class {
color: #ff00ff;
}
`;
// Remove style (also happens automatically on unload)
style.remove();
// Re-add style
style.add();
// Access underlying style element
const styleElement = style.styleTag;
```
```
--------------------------------
### Tracer (Logging and Error Handling)
Source: https://context7.com/inrixia/tidaluna/llms.txt
Provides structured logging with error signal support for plugin error display in the Luna UI. Enables detailed logging from debug to errors, including user-visible messages and context-aware error handling.
```APIDOC
## Tracer (Logging and Error Handling)
Structured logging with error signal support for plugin error display in the Luna UI.
```typescript
import { Tracer } from "@luna/core";
// Create a tracer for your plugin
const { trace, errSignal } = Tracer("[MyPlugin]");
export { errSignal }; // Export for Luna UI to show errors
// Basic logging
trace.log("Plugin loaded successfully");
trace.warn("Something might be wrong");
trace.debug("Debug information");
// Error logging (also sets errSignal)
trace.err("An error occurred", new Error("Details"));
// With message display (shows toast notification)
trace.msg.log("User-visible info message");
trace.msg.warn("User-visible warning");
trace.msg.err("User-visible error");
// Error handling with context
async function myAsyncFunction() {
await fetch("/api/data")
.catch(trace.err.withContext("Failed to fetch data"));
}
// Throw after logging
async function criticalFunction() {
await someOperation()
.catch(trace.err.withContext("Critical operation failed").throw);
}
// Create sub-tracers for different components
const apiTrace = trace.withSource(".API").trace;
aapiTrace.log("API request"); // Logs: "[MyPlugin.API] API request"
```
```
--------------------------------
### DOM Observer Utilities
Source: https://context7.com/inrixia/tidaluna/llms.txt
Utilities to observe DOM changes, allowing detection of element appearance for UI modifications. Includes functions to observe elements dynamically and wait for specific elements with a timeout.
```APIDOC
## DOM Observer Utilities
Observe DOM changes to detect when specific elements appear, useful for injecting UI modifications.
```typescript
import { observe, observePromise } from "@luna/lib";
// Observe for elements matching selector (called each time element appears)
const unobserve = observe(unloads, "div[class^='_trackRow']", (element) => {
// Add custom attribute or modify track rows
element.setAttribute("data-luna-processed", "true");
});
// Wait for specific element with timeout (returns Promise)
const titleElement = await observePromise(
unloads,
"div[class^='_mainContainer'] > div[class^='_title']",
5000 // 5 second timeout
);
if (titleElement) {
titleElement.innerHTML = 'Custom Title';
}
// Wait for context menu to appear
const contextMenu = await observePromise(
unloads,
`[data-type="list-container__context-menu"]`,
1000
);
```
```
--------------------------------
### Page Class (UI Registration)
Source: https://context7.com/inrixia/tidaluna/llms.txt
Register custom full-page UI views in the TIDAL client using React components. This allows for the creation of dedicated settings or view pages within the client interface.
```APIDOC
## Page Class (UI)
Register custom full-page UI views in the TIDAL client using React components.
```typescript
import { Page } from "@luna/ui";
import { ThemeProvider } from "@mui/material/styles";
import React from "react";
// Define your page component
const MySettingsPage: React.FC = () => (
My Plugin Settings
Configure your plugin here
);
// Register the page
const myPage = Page.register(
"MyPluginSettings",
unloads,
);
// Customize page background
myPage.pageStyles.background = `
radial-gradient(ellipse at top left, rgba(88, 10, 82, 0.5), transparent 70%),
linear-gradient(to bottom, #1a1a2e, #16213e)
`;
// Open the page programmatically
myPage.open();
// Add context menu button to open page
const settingsButton = ContextMenu.addButton(unloads);
settingsButton.text = "My Plugin Settings";
settingsButton.onClick(() => myPage.open());
```
```
--------------------------------
### Fetch Data with TidalApi Class
Source: https://context7.com/inrixia/tidaluna/llms.txt
Provides direct access to TIDAL's API for retrieving various media items like tracks, albums, playlists, and artists. It also supports fetching lyrics and playback information, including stream URLs.
```typescript
import { TidalApi } from "@luna/lib";
// Fetch track details
const track = await TidalApi.track(12345678);
console.log(track?.title, track?.artist?.name);
// Fetch album and its items
const album = await TidalApi.album(87654321);
const albumItems = await TidalApi.albumItems(87654321);
// Fetch playlist and items
const playlist = await TidalApi.playlist("playlist-uuid");
const playlistItems = await TidalApi.playlistItems("playlist-uuid");
// Fetch artist
const artist = await TidalApi.artist(999999);
// Fetch lyrics
const lyrics = await TidalApi.lyrics(12345678);
console.log(lyrics?.subtitles); // Synced lyrics
// Get playback info (stream URLs, quality info)
const playbackInfo = await TidalApi.playbackInfo(12345678, "HI_RES_LOSSLESS");
console.log(playbackInfo?.manifestMimeType);
console.log(playbackInfo?.bitDepth, playbackInfo?.sampleRate);
// Search by ISRC (async generator)
for await (const track of TidalApi.isrc("USRC12345678")) {
console.log(track.id, track.attributes.title);
}
// Get auth headers for custom API calls
const headers = await TidalApi.getAuthHeaders();
// { Authorization: "Bearer ...", "x-tidal-token": "..." }
```
--------------------------------
### DOM Observer Utilities
Source: https://context7.com/inrixia/tidaluna/llms.txt
Provides utilities for observing DOM changes to detect element appearance, useful for injecting UI modifications. It includes functions to observe elements matching a selector and to wait for specific elements with a timeout.
```typescript
import { observe, observePromise } from "@luna/lib";
// Observe for elements matching selector (called each time element appears)
const unobserve = observe(unloads, "div[class^='_trackRow']", (element) => {
// Add custom attribute or modify track rows
element.setAttribute("data-luna-processed", "true");
});
// Wait for specific element with timeout (returns Promise)
const titleElement = await observePromise(
unloads,
"div[class^='_mainContainer'] > div[class^='_title']",
5000 // 5 second timeout
);
if (titleElement) {
titleElement.innerHTML = 'Custom Title';
}
// Wait for context menu to appear
const contextMenu = await observePromise(
unloads,
`[data-type="list-container__context-menu"]`,
1000
);
```
--------------------------------
### Control Playback with PlayState Class
Source: https://context7.com/inrixia/tidaluna/llms.txt
Provides comprehensive control over audio playback, including play, pause, seek, queue management, shuffle, and repeat modes. It also includes event listeners for state changes and scrobbling.
```typescript
import { PlayState } from "@luna/lib";
// Playback controls
PlayState.play(); // Resume playback
PlayState.play(trackId); // Play specific track
PlayState.pause();
PlayState.next();
PlayState.previous();
PlayState.seek(120); // Seek to 120 seconds
// Queue management
PlayState.playNext([trackId1, trackId2]); // Add tracks after current
PlayState.moveTo(5); // Jump to queue index 5
// Playback state
const isPlaying = PlayState.playing;
const currentTime = PlayState.currentTime; // Live player position in seconds
const playTime = PlayState.playTime; // Redux state position
// Shuffle and repeat
PlayState.shuffle; // Get shuffle state
PlayState.setShuffle(true, true); // Enable shuffle and shuffle items
PlayState.setShuffle(false, true); // Disable and unshuffle
PlayState.repeatMode; // Get current repeat mode
PlayState.setRepeatMode(PlayState.RepeatMode.ONE);
// Get next/previous items
const nextTrack = await PlayState.nextMediaItem();
const prevTrack = await PlayState.previousMediaItem();
// Listen for playback state changes
PlayState.onState(unloads, (state) => {
// state: "PLAYING" | "PAUSED" | "IDLE" | etc.
console.log(`Playback state: ${state}`);
});
// Listen for scrobble events (50% played or 4 minutes)
PlayState.onScrobble(unloads, (mediaItem) => {
console.log(`Scrobble: ${mediaItem.tidalItem.title}`);
});
```
--------------------------------
### MediaItem API
Source: https://context7.com/inrixia/tidaluna/llms.txt
API methods for interacting with TIDAL media items, including metadata retrieval, playback control, and quality management.
```APIDOC
## MediaItem API
### Description
Provides access to track and video metadata, playback states, and download capabilities within the TIDAL client.
### Methods
- **fromPlaybackContext()**: Fetches the currently playing media item.
- **fromId(id, type)**: Retrieves a specific media item by ID.
- **play()**: Initiates playback for the media item.
- **download(path, quality)**: Downloads the media item to a local path.
- **onMediaTransition(callback)**: Event listener for track changes.
### Parameters
#### Path Parameters
- **id** (number) - Required - The unique identifier for the media item.
- **type** (string) - Required - The type of media (e.g., "track").
### Response
#### Success Response (200)
- **MediaItem** (Object) - Returns an object containing metadata, quality tags, and playback methods.
```
--------------------------------
### Sign Tidal Application on MacOS
Source: https://github.com/inrixia/tidaluna/blob/master/README.md
Command to re-sign the Tidal application bundle on MacOS after manual modification to prevent system rejection.
```shell
codesign --force --deep --sign - /Applications/TIDAL.app
```
--------------------------------
### Interact with Redux Store and Actions
Source: https://context7.com/inrixia/tidaluna/llms.txt
Allows access to the TIDAL Redux store state and provides functionality to dispatch actions. It also enables intercepting actions to modify their behavior or cancel them entirely.
```typescript
import { redux } from "@luna/lib";
// Access store state
const state = redux.store.getState();
const playbackState = state.playbackControls.playbackState;
const currentUser = state.session.user;
const countryCode = state.session.countryCode;
// Dispatch actions
redux.actions["playbackControls/PLAY"]();
redux.actions["playbackControls/PAUSE"]();
redux.actions["playQueue/MOVE_NEXT"]();
redux.actions["playQueue/SET_REPEAT_MODE"](redux.RepeatMode.ALL);
// Intercept actions (return true to cancel the action)
const unload = redux.intercept("playbackControls/PLAY", unloads, (payload, type) => {
console.log("Play action intercepted:", payload);
// Return true to prevent the action from being dispatched
return false;
});
// Intercept multiple action types
redux.intercept(
["player/PRELOAD_ITEM", "playbackControls/MEDIA_PRODUCT_TRANSITION"],
unloads,
(payload, type) => {
console.log(`Action ${type}:`, payload);
}
);
// Wait for specific action (one-time)
const payload = await redux.interceptPromise(
"content/LOAD_SINGLE_MEDIA_ITEM_SUCCESS",
unloads
);
// Wait for action with success/fail handling
const result = await redux.interceptActionResp(
() => redux.actions["content/LOAD_SINGLE_MEDIA_ITEM"]({ id: trackId, itemType: "track" }),
unloads,
["content/LOAD_SINGLE_MEDIA_ITEM_SUCCESS"], // Resolve on
["content/LOAD_SINGLE_MEDIA_ITEM_FAIL"], // Reject on
{ timeoutMs: 5000 }
);
```
--------------------------------
### Quality Class
Source: https://context7.com/inrixia/tidaluna/llms.txt
Utility class for handling TIDAL's quality tiers and converting between different quality formats.
```APIDOC
## Quality Class
Utility class for handling TIDAL's quality tiers and converting between different quality formats.
### Description
Manages audio quality levels in TIDAL, allowing comparison, conversion from metadata tags or strings, and retrieval of quality properties.
### Usage
```typescript
import { Quality } from "@luna/lib";
// Quality levels (highest to lowest)
Quality.HiRes; // Hi-Res Lossless (24-bit, up to 192kHz)
Quality.MQA; // MQA (Master Quality Authenticated)
Quality.Atmos; // Dolby Atmos
Quality.Sony630; // Sony 360 Reality Audio
Quality.High; // CD Quality Lossless (16-bit, 44.1kHz)
Quality.Low; // AAC 320kbps
Quality.Lowest; // AAC 96kbps
Quality.Max; // Alias for HiRes (highest available)
// Compare qualities
const q1 = Quality.HiRes;
const q2 = Quality.High;
console.log(q1 > q2); // true (valueOf returns index)
// Convert from TIDAL metadata tags
const qualities = Quality.fromMetaTags(["HIRES_LOSSLESS", "DOLBY_ATMOS"]);
// Returns [Quality.HiRes, Quality.Atmos]
// Convert from audio quality string
const quality = Quality.fromAudioQuality("HI_RES_LOSSLESS");
// Returns Quality.HiRes
// Get min/max from array
const best = Quality.max(Quality.High, Quality.MQA, Quality.Low);
// Returns Quality.MQA
// Convert back to TIDAL formats
const audioQualityStr = Quality.HiRes.audioQuality; // "HI_RES_LOSSLESS"
const metadataTag = Quality.HiRes.metadataTag; // "HIRES_LOSSLESS"
// Quality properties
console.log(Quality.HiRes.name); // "HiRes"
console.log(Quality.HiRes.color); // "#ffd432"
```
```
--------------------------------
### TidalApi Class - API Endpoints
Source: https://context7.com/inrixia/tidaluna/llms.txt
Directly access TIDAL's API endpoints for fetching various media and playback information.
```APIDOC
## TidalApi Class - API Endpoints
### Description
Provides direct access to TIDAL's API endpoints for fetching tracks, albums, playlists, artists, and playback information.
### Methods
- `TidalApi.track(trackId)`: Fetch details for a specific track.
- `TidalApi.album(albumId)`: Fetch details for a specific album.
- `TidalApi.albumItems(albumId)`: Fetch all items within an album.
- `TidalApi.playlist(playlistId)`: Fetch details for a specific playlist.
- `TidalApi.playlistItems(playlistId)`: Fetch all items within a playlist.
- `TidalApi.artist(artistId)`: Fetch details for a specific artist.
- `TidalApi.lyrics(trackId)`: Fetch lyrics for a track, including synced subtitles.
- `TidalApi.playbackInfo(trackId, quality)`: Get playback details like stream URLs and quality information.
- `TidalApi.isrc(isrc)`: Search for tracks by ISRC (International Standard Recording Code). Returns an async generator.
- `TidalApi.getAuthHeaders()`: Retrieve authentication headers required for custom API calls.
### Examples
- Fetching a track: `const track = await TidalApi.track(12345678);`
- Fetching album items: `const albumItems = await TidalApi.albumItems(87654321);`
- Fetching lyrics: `const lyrics = await TidalApi.lyrics(12345678); console.log(lyrics?.subtitles);`
- Getting playback info: `const playbackInfo = await TidalApi.playbackInfo(12345678, "HI_RES_LOSSLESS");`
- Searching by ISRC: `for await (const track of TidalApi.isrc("USRC12345678")) { ... }`
- Getting auth headers: `const headers = await TidalApi.getAuthHeaders();`
```
--------------------------------
### Redux Store and Action Interception
Source: https://context7.com/inrixia/tidaluna/llms.txt
Access and manipulate the TIDAL Redux store, and intercept actions to modify or cancel them.
```APIDOC
## Redux Store and Action Interception
### Description
Access and manipulate TIDAL's Redux store, intercept actions to modify behavior or cancel them entirely.
### Accessing Store State
- `redux.store.getState()`: Get the current state of the Redux store.
- Access specific state slices like `state.playbackControls.playbackState`, `state.session.user`, `state.session.countryCode`.
### Dispatching Actions
- `redux.actions[actionType](payload)`: Dispatch a Redux action.
- Example: `redux.actions["playbackControls/PLAY"]()`
- Example: `redux.actions["playQueue/SET_REPEAT_MODE"](redux.RepeatMode.ALL)`
### Intercepting Actions
- `redux.intercept(actionTypeOrArray, unloads, callback)`: Intercept one or more action types. The callback receives `payload` and `type`. Return `true` to cancel the action.
- Example: `redux.intercept("playbackControls/PLAY", unloads, (payload, type) => { ... return false; })`
- Example: `redux.intercept(["player/PRELOAD_ITEM", "playbackControls/MEDIA_PRODUCT_TRANSITION"], unloads, (payload, type) => { ... })`
### Waiting for Actions
- `redux.interceptPromise(actionType, unloads)`: Returns a promise that resolves with the action payload when the specified action is dispatched.
- `redux.interceptActionResp(actionDispatcher, unloads, resolveOn, rejectOn, options)`: Dispatches an action and waits for specific success or failure actions, with optional timeout.
- `actionDispatcher`: A function that returns the action to dispatch.
- `resolveOn`: Array of action types to resolve the promise.
- `rejectOn`: Array of action types to reject the promise.
- `options`: Object with `timeoutMs`.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.