taglib-wasm
Version:
TagLib-Wasm is the universal tagging library for TypeScript/JavaScript platforms: Browsers, Node.js, Deno, Bun, Cloudflare Workers, and Electron apps
135 lines (134 loc) • 3.26 kB
JavaScript
import { errorMessage, MetadataError } from "../errors/classes.js";
import {
decodeAudioProperties,
decodeMessagePackAuto,
decodePicture,
decodeTagData,
isValidMessagePack
} from "./decoder.js";
import { compareEncodingEfficiency, encodeTagData } from "./encoder.js";
class MessagePackUtils {
/**
* Smart decode that automatically detects the data type
*/
static decode(buffer) {
return decodeMessagePackAuto(buffer);
}
/**
* Validate and decode tag data with error handling
*/
static safeDecodeTagData(buffer) {
try {
if (!isValidMessagePack(buffer)) {
return null;
}
return decodeTagData(buffer);
} catch {
return null;
}
}
/**
* Validate and decode audio properties with error handling
*/
static safeDecodeAudioProperties(buffer) {
try {
if (!isValidMessagePack(buffer)) {
return null;
}
return decodeAudioProperties(buffer);
} catch {
return null;
}
}
/**
* Validate and decode picture data with error handling
*/
static safeDecodePicture(buffer) {
try {
if (!isValidMessagePack(buffer)) {
return null;
}
return decodePicture(buffer);
} catch {
return null;
}
}
/**
* Get performance metrics for MessagePack vs JSON
*/
static getPerformanceComparison(data) {
const comparison = compareEncodingEfficiency(data);
return {
messagePackSize: comparison.messagePackSize,
jsonSize: comparison.jsonSize,
sizeReduction: comparison.sizeReduction,
estimatedSpeedImprovement: comparison.speedImprovement
};
}
/**
* Convert between MessagePack and JSON for debugging/comparison
*/
static toJson(buffer) {
try {
const decoded = decodeMessagePackAuto(buffer);
return JSON.stringify(decoded, null, 2);
} catch (error) {
throw new MetadataError(
"read",
`Failed to convert to JSON: ${errorMessage(error)}`
);
}
}
/**
* Convert JSON back to MessagePack (for testing/migration)
*/
static fromJson(jsonString) {
try {
const data = JSON.parse(jsonString);
return encodeTagData(data);
} catch (error) {
throw new MetadataError(
"write",
`Failed to convert from JSON: ${errorMessage(error)}`
);
}
}
/**
* Batch process multiple MessagePack buffers
*/
static batchDecode(buffers) {
return buffers.map((buffer) => {
try {
const data = decodeMessagePackAuto(buffer);
return { success: true, data };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : "Unknown error"
};
}
});
}
/**
* Check if data is compatible with TagLib MessagePack format
*/
static isTagLibCompatible(data) {
if (typeof data !== "object" || data === null) {
return false;
}
const obj = data;
if ("title" in obj || "artist" in obj || "album" in obj) {
return true;
}
if ("bitrate" in obj && "sampleRate" in obj) {
return true;
}
if ("mimeType" in obj && "data" in obj) {
return true;
}
return false;
}
}
export {
MessagePackUtils
};