Latest Threat Research:SANDWORM_MODE: Shai-Hulud-Style npm Worm Hijacks CI Workflows and Poisons AI Toolchains.Details
Socket
Book a DemoInstallSign in
Socket

@socaity/media-toolkit

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@socaity/media-toolkit - npm Package Compare versions

Comparing version
0.0.11
to
0.0.12
+9
-1
package.json
{
"name": "@socaity/media-toolkit",
"version": "0.0.11",
"version": "0.0.12",
"type": "module",

@@ -16,2 +16,10 @@ "description": "Web-ready standardized file processing and serialization. Read, write, convert and send files. Including image, audio, video and any other file. Easily convert between base64, bytes, numpy and more. Create browser elements or use in node.js",

"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/media-toolkit.es.js",
"require": "./dist/media-toolkit.umd.js",
"default": "./dist/media-toolkit.es.js"
}
},
"files": [

@@ -18,0 +26,0 @@ "dist",

-52
import { MediaFile } from './MediaFile';
/**
* A specialized MediaFile class for handling 3D model files.
* Provides methods specific to 3D model processing and metadata extraction.
*/
export declare class Asset3DFile extends MediaFile {
/**
* Creates a new Model3DFile instance.
*
* @param file_name - Default filename to use
* @param content_type - Default content type to use (defaults to model/obj)
*/
constructor(file_name?: string, content_type?: string);
/**
* Factory method to create a Model3DFile from any supported data type.
*
* @param data - Data to load (file path, URL, base64 string, etc.)
* @returns Promise resolving to a Model3DFile instance
*/
static create(data: any): Promise<Asset3DFile>;
/**
* Override fromAny to ensure the content type is a 3D model type.
*
* @param data - Data to load
* @returns Promise resolving to a Model3DFile instance
*/
fromAny(data: any): Promise<Asset3DFile>;
/**
* Get basic information about the 3D model.
* Attempts to extract metadata like format, vertices count, etc.
*
* @returns Object with model information
*/
getModelInfo(): {
format: string;
estimatedSize?: number;
hasTextures?: boolean;
};
/**
* Get the 3D model format based on content type or file extension.
*
* @returns String representing the model format
*/
getModelFormat(): string;
/**
* Validate that the content type is a 3D model type.
* If not, attempt to correct it based on file extension or magic bytes.
*
* @private
*/
private _validateModel3DContentType;
}
import { MediaFile } from './MediaFile';
/**
* A specialized MediaFile class for handling audio files.
* Provides methods specific to audio processing and playback.
*/
export declare class AudioFile extends MediaFile {
/**
* Creates a new AudioFile instance.
*
* @param file_name - Default filename to use
* @param content_type - Default content type to use (defaults to audio/mpeg)
*/
constructor(file_name?: string, content_type?: string);
/**
* Factory method to create an AudioFile from any supported data type.
*
* @param data - Data to load (file path, URL, base64 string, etc.)
* @returns Promise resolving to an AudioFile instance
*/
static create(data: any): Promise<AudioFile>;
/**
* Override fromAny to ensure the content type is an audio type.
*
* @param data - Data to load
* @returns Promise resolving to an AudioFile instance
*/
fromAny(data: any): Promise<AudioFile>;
/**
* Creates an HTML audio element from the audio data.
*
* @returns HTMLAudioElement that can be used for playback
*/
toAudioElement(): HTMLAudioElement;
/**
* Play the audio (browser only).
*
* @returns Promise that resolves when audio playback starts
*/
play(): Promise<void>;
/**
* Get duration of the audio file in seconds (browser only).
*
* @returns Promise resolving to the duration in seconds
*/
getDuration(): Promise<number>;
/**
* Create an embedded HTML audio player.
*
* @param options - Options for the audio player (controls, autoplay, loop)
* @returns HTML string containing an audio element
*/
toHTMLPlayer(options?: {
controls?: boolean;
autoplay?: boolean;
loop?: boolean;
}): string;
/**
* Validate that the content type is an audio type.
* If not, attempt to correct it based on file extension or magic bytes.
*
* @private
*/
private _validateAudioContentType;
}
/**
* Detects content type from various data sources.
*
* @param data - Data to detect content type from
* @returns Promise resolving to the detected content type or null
* @private
*/
export declare function detectContentType(data: any): Promise<string | null>;
/**
* Check if a string is a URL.
*
* @param url - URL to check
* @returns Whether the string is a URL
* @private
*/
export declare function isUrl(url: string): boolean; /**
* Detect a MIME type from a URL by its extension.
* Returns null if the URL is not http/https or the extension is unknown.
*/
export declare function detectMimeTypeFromUrl(value: string): string | null;
/**
* Check if a string is a base64 data URI.
*
* @param data - String to check
* @returns Whether the string is a base64 data URI
* @private
*/
export declare function isBase64Data(data: string): boolean;
/**
* Check if a string appears to be base64 encoded.
*
* @param str - String to check
* @returns Whether the string is base64 encoded
* @private
*/
export declare function isBase64String(str: string): boolean;
/**
* Check if a string is a valid file path.
*
* @param path - Path to check
* @returns Whether the path is valid
* @private
*/
export declare function isValidFilePath(path: string): Promise<boolean>;
/**
* Check if an object is a FileReader.vue component file object.
*
* @param obj - Object to check
* @returns Whether the object is a FileReader file object
* @private
*/
export declare function isFileReaderObject(obj: any): boolean;
/**
* Check if an object is a FileResult.
*
* @param obj - Object to check
* @returns Whether the object is a FileResult
* @private
*/
export declare function isFileResult(obj: any): boolean;
/**
* Universal content type detector using magic bytes and lightweight heuristics.
* Combines `magic-bytes.js` for general detection with custom logic for 3D formats.
*/
export declare class MagicByteDetector {
/**
* Detect MIME type from file content (ArrayBuffer).
* @param content - File content
* @returns Detected MIME type or `null` if unrecognized
*/
static detectMime(content: ArrayBuffer): string | null;
/**
* Detect image MIME type specifically.
* @param content - File content
*/
static detectImageFormat(content: ArrayBuffer): string | null;
/**
* Detect video MIME type specifically.
* @param content - File content
*/
static detectVideoFormat(content: ArrayBuffer): string | null;
/**
* Detect audio MIME type specifically.
* @param content - File content
*/
static detectAudioFormat(content: ArrayBuffer): string | null;
/**
* Custom fallback: detect 3D model formats by header patterns or keywords.
*/
static detect3DModel(content: ArrayBuffer): string | null;
/**
* Detect 3D model format name specifically (human-readable name).
* @param content - File content
*/
static detect3DModelFormatName(content: ArrayBuffer): string | null;
/**
* Detect inline SVG by checking for XML <svg> tag in first 200 bytes.
*/
static detectSvg(content: ArrayBuffer): string | null;
}
/**
* Consolidated file type support definitions for all MediaFile types.
* This serves as the single source of truth for supported file formats.
*/
/**
* Supported audio MIME types and extensions
*/
export declare const AUDIO_MIME_TYPES: Record<string, string>;
/**
* Supported video MIME types and extensions
*/
export declare const VIDEO_MIME_TYPES: Record<string, string>;
/**
* Supported image MIME types and extensions
*/
export declare const IMAGE_MIME_TYPES: Record<string, string>;
/**
* Supported 3D model MIME types and extensions
*/
export declare const MODEL_3D_MIME_TYPES: Record<string, string>;
/**
* Other common file MIME types and extensions
*/
export declare const OTHER_MIME_TYPES: Record<string, string>;
/**
* All supported MIME types combined
*/
export declare const ALL_MIME_TYPES: {
[x: string]: string;
};
export declare const MIME_TYPE_ALIASES: Record<string, string>;
/**
* Media type categories
*/
export type MediaTypeCategory = 'audio' | 'video' | 'image' | 'asset_3d' | 'file';
/**
* Get accepted MIME types and file extensions for a specific media category
* @param category - The media category to get accepted types for
* @returns Array of MIME types and file extensions
*/
export declare function getAcceptedTypes(category: MediaTypeCategory): string[];
/**
* Get user-friendly display name for a media category
* @param category - The media category
* @returns Display name for the category
*/
export declare function getCategoryDisplayName(category: MediaTypeCategory): string;
/**
* Detect media category from MIME type
* @param mimeType - MIME type to check
* @returns Media category or null if not recognized
*/
export declare function detectCategoryFromMimeType(mimeType: string): MediaTypeCategory | null;
/**
* Lookup a MIME type from a file extension (without leading dot).
*/
export declare function getMimeTypeFromExtension(extension: string): string | null;
import { MediaFile } from './MediaFile';
/**
* A specialized MediaFile class for handling image files.
* Provides methods specific to image processing and rendering.
*/
export declare class ImageFile extends MediaFile {
/**
* Creates a new ImageFile instance.
*
* @param file_name - Default filename to use
* @param content_type - Default content type to use (defaults to image/png)
*/
constructor(file_name?: string, content_type?: string);
/**
* Factory method to create an ImageFile from any supported data type.
*
* @param data - Data to load (file path, URL, base64 string, etc.)
* @returns Promise resolving to an ImageFile instance
*/
static create(data: any): Promise<ImageFile>;
/**
* Override fromAny to ensure the content type is an image type.
*
* @param data - Data to load
* @returns Promise resolving to an ImageFile instance
*/
fromAny(data: any): Promise<ImageFile>;
/**
* Creates an HTML image element from the image data.
*
* @param options - Optional image element attributes (width, height, alt, className)
* @returns HTML string containing an image element
*/
toImageElement(options?: {
width?: number;
height?: number;
alt?: string;
className?: string;
}): string;
/**
* Create an actual DOM Image element (browser only).
*
* @param options - Optional image element attributes
* @returns HTMLImageElement that can be added to the DOM
*/
toDOMImageElement(options?: {
width?: number;
height?: number;
alt?: string;
className?: string;
}): HTMLImageElement;
/**
* Get image dimensions (browser only).
*
* @returns Promise resolving to an object with width and height
*/
getDimensions(): Promise<{
width: number;
height: number;
}>;
/**
* Validate that the content type is an image type.
* If not, attempt to correct it based on file extension or magic bytes.
*
* @private
*/
private _validateImageContentType;
}
import { MediaFile } from './MediaFile';
import { ImageFile } from './ImageFile';
import { AudioFile } from './AudioFile';
import { VideoFile } from './VideoFile';
import { Asset3DFile as Asset3DFile } from './Asset3DFile';
import { MediaList } from './media_containers/media_list';
import { MediaDict } from './media_containers/media_dict';
import { MagicByteDetector } from './content_detectors/MagicByteDetector';
export { MediaFile, ImageFile, AudioFile, VideoFile, Asset3DFile, MediaList, MediaDict, MagicByteDetector };
export * from './content_detectors/SupportedTypes';
export * from './content_detectors/ContentDetector';
export * from './types';
export interface IMediaFileConstructor {
new (): MediaFile;
}
export declare const MediaTypes: Record<string, IMediaFileConstructor>;
import { IMediaFile } from "../types";
/**
* Interface for media containers that hold multiple media files.
* Extends IMediaFile to allow containers to be treated as files themselves.
*/
export interface IMediaContainer<T extends IMediaFile> extends IMediaFile, Iterable<T | string | any> {
/**
* Get all processable files from the container.
* @param options - Options for processing
* @returns Container with processable files
*/
getProcessableFiles(options?: {
ignoreErrors?: boolean;
raiseException?: boolean;
silent?: boolean;
}): IMediaContainer<T>;
/**
* Get all leaf files (non-container media files) and their indices.
* @returns Object with files array and indices array
*/
getLeafFiles(): {
files: T[];
indices: number[];
};
/**
* Get all URL files that haven't been processed.
* @returns Array of URL strings
*/
getUrlFiles(): any;
/**
* Get all file path strings that haven't been processed.
* @returns Array of file path strings
*/
getFilePathFiles(): any;
/**
* Get all non-file parameters.
* @param includeUrls - Whether to include URLs in the result
* @returns Array of non-processable items
*/
getNonFileParams(includeUrls?: boolean): any;
/**
* Save all files in the container.
* @param path - Target directory or file path pattern
*/
save(path?: string): Promise<void>;
/**
* Number of items in the container.
*/
readonly length: number;
}
import { MediaFile } from '../MediaFile';
import { IMediaContainer } from './IMediaContainer';
/**
* Options for MediaDict initialization.
*/
export interface MediaDictOptions {
/**
* Initial dictionary of files to process
*/
files?: Record<string, any>;
/**
* Whether to automatically download files from URLs
* @default true
*/
downloadFiles?: boolean;
/**
* Whether to automatically read files from the file system
* @default true
*/
readSystemFiles?: boolean;
/**
* Name for this media dictionary (used when saving)
* @default "MediaDict"
*/
fileName?: string;
}
/**
* A flexible media file dictionary that handles multiple file types and sources with configurable loading behaviors.
*
* Supports:
* - Multiple MediaFile types as dictionary values
* - Nested containers (MediaList, MediaDict)
* - Batch media processing
* - Generic type restrictions (e.g., MediaDict<ImageFile>)
* - Dictionary-like operations (get, set, delete, keys, values, items)
*
* @example
* ```typescript
* // Create a dictionary with files
* const dict = new MediaDict({
* files: {
* 'avatar': '/path/to/avatar.jpg',
* 'banner': 'https://example.com/banner.png'
* },
* downloadFiles: true,
* readSystemFiles: true
* });
*
* // Access files by key
* const avatar = dict.get('avatar');
*
* // Add more files
* await dict.set('logo', logoFile);
*
* // Save all files
* await dict.save('/output/directory');
* ```
*/
export declare class MediaDict<T extends MediaFile = MediaFile> implements IMediaContainer<T> {
private _allItems;
private _mediaFiles;
private _urlFiles;
private _nonProcessableFiles;
private _mediaContainers;
downloadFiles: boolean;
readSystemFiles: boolean;
fileName: string;
/**
* Initialize MediaDict with optional files and configuration.
*
* @param options - Configuration options
*/
constructor(options?: MediaDictOptions);
/**
* Initialize files synchronously (only for already-loaded MediaFile instances).
* For async loading, use fromAny() or set() instead.
*
* @private
*/
private _initializeFiles;
/**
* Check if a value is empty.
* @private
*/
private _isEmptyFile;
/**
* Remove key from all category sets.
* @private
*/
private _removeFromAllSets;
/**
* Add a processed item to storage and categorize it.
* @private
*/
private _addToStorage;
/**
* Process a single file and automatically categorize it.
*
* @param key - The key for this file
* @param file - File to process
* @returns Promise resolving to the processed file
* @private
*/
private _processFile;
/**
* Load files from a dictionary of files.
*
* @param data - Dictionary of files to load
* @returns Promise resolving to this MediaDict instance
*/
fromAny(data: Record<string, any>): Promise<MediaDict<T>>;
/**
* Get all leaf files (non-container media files).
*
* @returns Object with files and indices
*/
getLeafFiles(): {
files: T[];
indices: number[];
};
/**
* Get all media containers from this dictionary.
*
* @returns MediaDict containing only containers
*/
getMediaContainers(): MediaDict<T>;
/**
* Get all processable files from the container.
*
* @param options - Processing options
* @returns New MediaDict with processable files
*/
getProcessableFiles(options?: {
ignoreErrors?: boolean;
raiseException?: boolean;
silent?: boolean;
}): MediaDict<T>;
/**
* Get all URL files that haven't been processed.
*
* @returns MediaDict containing URL files
*/
getUrlFiles(): Record<string, any>;
/**
* Get all file path strings that haven't been processed.
*
* @returns Dictionary of file path strings
*/
getFilePathFiles(): Record<string, any>;
/**
* Get all non-file parameters as a dictionary.
* Returns non-processable files with their keys preserved.
*
* @param includeUrls - Whether to include URL files in the result
* @returns Dictionary of non-processable files and optionally URLs
*/
getNonFileParams(includeUrls?: boolean): Record<string, any>;
/**
* Create a shallow copy with the same settings.
* @private
*/
private _shallowCopyWithSettings;
/**
* Convert all media files to base64 strings.
*
* @param includeDataUri - Whether to include data URI prefix
* @returns Object mapping keys to base64 strings
*/
toBase64(includeDataUri?: boolean): Record<string, string>;
/**
* Convert all media files to Blob objects (browser only).
*
* @returns Object mapping keys to Blobs
*/
toBlob(): Record<string, Blob>;
/**
* Convert all media files to ArrayBuffer objects.
*
* @returns Object mapping keys to ArrayBuffers
*/
toArrayBuffer(): Record<string, ArrayBuffer>;
/**
* Convert all media files to Uint8Array objects.
*
* @returns Object mapping keys to Uint8Arrays
*/
toUint8Array(): Record<string, Uint8Array>;
/**
* Convert all media files to Buffer objects (Node.js only).
*
* @returns Object mapping keys to Buffers
*/
toBuffer(): Record<string, Buffer>;
/**
* Convert all files to JSON representation.
*
* @returns Object with all items as JSON
*/
toJson(): Record<string, any>;
/**
* Get the total file size of all media files.
*
* @param unit - Unit to return the size in
* @returns Total file size in the specified unit
*/
fileSize(unit?: 'bytes' | 'kb' | 'mb' | 'gb'): number;
/**
* Save all media files in the dictionary to a specified location.
*
* @param path - Target directory or file path
* @param createSubDirs - Whether to create subdirectories for nested containers
*
* Behavior:
* - Creates target directory if it doesn't exist
* - Handles filename conflicts with numeric suffixes
* - Preserves original extensions when saving to directory
* - Nested containers saved into subdirectories
*
* @example
* ```typescript
* // Save to directory
* await dict.save('/output/files');
*
* // Save with base filename
* await dict.save('/output/file.jpg');
* ```
*/
save(path?: string, createSubDirs?: boolean): Promise<void>;
/**
* Get a file by key.
*
* @param key - The key to retrieve
* @returns The file or value at that key
*/
get(key: string): any;
/**
* Set a file at a specific key.
*
* @param key - The key to set
* @param value - The value to set
*/
set(key: string, value: any): Promise<void>;
/**
* Delete a file by key.
*
* @param key - The key to delete
* @returns Whether the key existed and was deleted
*/
delete(key: string): boolean;
/**
* Check if a key exists.
*
* @param key - The key to check
* @returns Whether the key exists
*/
has(key: string): boolean;
/**
* Get all keys.
*
* @returns Array of all keys
*/
keys(): string[];
/**
* Get all values.
*
* @returns Array of all values
*/
values(): any[];
/**
* Get all entries.
*
* @returns Array of [key, value] pairs
*/
entries(): Array<[string, any]>;
/**
* Update the dictionary with new files.
*
* @param files - Dictionary of files to add or update
*/
update(files: Record<string, any> | MediaDict<T>): Promise<void>;
/**
* Clear all files from the dictionary.
*/
clear(): void;
/**
* Get the number of items in the dictionary.
*/
get length(): number;
/**
* Check if the dictionary is empty.
*
* @returns Whether the dictionary has no items
*/
isEmpty(): boolean;
/**
* Get information about the media dictionary.
*
* @returns Object with dictionary information
*/
getInfo(): {
fileName: string;
totalFiles: number;
mediaFiles: number;
urlFiles: number;
nonProcessableFiles: number;
containers: number;
totalSize: number;
};
/**
* Get the filename.
*/
getFileName(): string;
/**
* Set the filename.
*/
setFileName(fileName: string): void;
/**
* Get the content type.
*/
getContentType(): string;
/**
* Set the content type (not applicable for MediaDict).
*/
setContentType(_contentType: string): void;
/**
* Convert the MediaDict to a plain object.
*
* @returns Plain object with all items
*/
toDict(): Record<string, any>;
/**
* Implement iterator protocol to allow for...of loops.
* Iterates over keys.
*
* @returns Iterator for the dictionary keys
*/
[Symbol.iterator](): Iterator<string>;
}
import { MediaFile } from '../MediaFile';
import { IMediaContainer } from "./IMediaContainer";
/**
* Options for MediaList initialization.
*/
export interface MediaListOptions {
/**
* Initial list of files to process
*/
files?: any[];
/**
* Whether to automatically download files from URLs
* @default true
*/
downloadFiles?: boolean;
/**
* Whether to automatically read files from the file system
* @default true
*/
readSystemFiles?: boolean;
/**
* Name for this media list (used when saving)
* @default "MediaList"
*/
fileName?: string;
}
/**
* A flexible media file list that handles multiple file types and sources with configurable loading behaviors.
*
* Supports:
* - Multiple MediaFile types
* - Lazy loading configurations
* - Basic list operations (append, extend, pop, iterate, index)
* - Batch media processing
* - Generic type restrictions (e.g., MediaList<ImageFile>)
*
* @example
* ```typescript
* // Create a list with automatic downloads
* const list = new MediaList({
* files: ['https://example.com/image.jpg', '/path/to/local.png'],
* downloadFiles: true,
* readSystemFiles: true
* });
*
* // Get all processable files
* const processable = list.getProcessableFiles();
*
* // Convert all to base64
* const base64Array = list.toBase64();
*
* // Save all files
* await list.save('/output/directory');
* ```
*/
export declare class MediaList<T extends MediaFile = MediaFile> implements IMediaContainer<T> {
private _mediaFiles;
private _urlFiles;
private _nonProcessableFiles;
private _mediaContainers;
downloadFiles: boolean;
readSystemFiles: boolean;
fileName: string;
/**
* Initialize MediaList with optional files and configuration.
*
* @param options - Configuration options
*/
constructor(options?: MediaListOptions);
/**
* Initialize files synchronously (only for already-loaded MediaFile instances).
* For async loading from URLs/paths, use fromAny() or extend() instead.
*
* @private
*/
private _initializeFiles;
/**
* Load files from any supported data sources.
* This method processes files asynchronously.
*
* @param data - Array of data to load (URLs, paths, MediaFiles, etc.)
* @returns Promise resolving to this MediaList instance
*/
fromAny(data: any[]): Promise<MediaList<T>>;
/**
* Process a single file and automatically categorize it.
*
* @param file - File to process (URL, path, MediaFile, etc.)
* @returns Promise resolving to the processed file or original value
* @private
*/
private _processFile;
/**
* Add a MediaFile to the appropriate internal list.
*
* @param file - MediaFile to add
* @private
*/
private _addMediaFile;
/**
* Check if a file is a media container.
*
* @param file - File to check
* @returns Whether the file is a media container
* @private
*/
private _isMediaContainer;
/**
* Get all items in their original order.
*
* @private
*/
private get _allItems();
/**
* Get all leaf files (non-container media files) and their indices.
*
* @returns Object with files array and indices array
*/
getLeafFiles(): {
files: T[];
indices: number[];
};
/**
* Get all media containers from this list and their indices.
*
* @returns Object with containers array and indices array
*/
getMediaContainers(): {
containers: IMediaContainer<any>[];
indices: number[];
};
/**
* Get all processable files from the container.
* Validates that all files can be processed for batch operations.
*
* @param options - Processing options
* @returns New MediaList with processable files
*/
getProcessableFiles(options?: {
ignoreErrors?: boolean;
raiseException?: boolean;
silent?: boolean;
}): MediaList<T>;
/**
* Get all non-processed URL files.
*
* @returns Array of URL strings
*/
getUrlFiles(): string[];
/**
* Get all non-processed file path files.
*
* @returns Array of file path strings
*/
getFilePathFiles(): string[];
/**
* Get all non-file parameters from the container.
*
* @param includeUrls - Whether to include URL files in the result
* @returns Array of non-processable items
*/
getNonFileParams(includeUrls?: boolean): any[];
/**
* Convert all media files to base64 strings.
*
* @param includeDataUri - Whether to include the data URI prefix
* @returns Array of base64 strings
*/
toBase64(includeDataUri?: boolean): string[];
/**
* Convert all media files to Blob objects (browser only).
*
* @returns Array of Blob objects
*/
toBlob(): Blob[];
/**
* Convert all media files to ArrayBuffer objects.
*
* @returns Array of ArrayBuffer objects
*/
toArrayBuffer(): ArrayBuffer[];
/**
* Convert all media files to Uint8Array objects.
*
* @returns Array of Uint8Array objects
*/
toUint8Array(): Uint8Array[];
/**
* Convert all media files to Buffer objects (Node.js only).
*
* @returns Array of Buffer objects
*/
toBuffer(): Buffer[];
/**
* Convert all files to JSON representation.
*
* @returns Array of FileResult objects
*/
toJson(): any[];
/**
* Get the total file size of all media files.
*
* @param unit - Unit to return the size in
* @returns Total file size in the specified unit
*/
fileSize(unit?: 'bytes' | 'kb' | 'mb' | 'gb'): number;
/**
* Save all media files in the list to a specified location.
*
* @param path - Target directory path or file path pattern
*
* Behavior:
* - Creates the target directory if it doesn't exist
* - Handles filename conflicts by appending numbers (_1, _2, etc.)
* - Preserves original file extensions
* - If path includes a filename, applies that name to all files with their extensions
* - If path is just a directory, each file keeps its original filename
*
* @example
* ```typescript
* // Save with original filenames
* await list.save('/tmp/videos');
*
* // Save all files with a base name
* await list.save('/tmp/output.mp4');
* ```
*/
save(path?: string): Promise<void>;
/**
* Append a single file to the list.
*
* @param file - File to append
*/
append(file: any): Promise<void>;
/**
* Extend the list with multiple files.
*
* @param files - Array of files to add
*/
extend(files: any[]): Promise<void>;
/**
* Remove and return the file at the specified index.
*
* @param index - Index of the file to remove (defaults to -1, last item)
* @returns The removed file
*/
pop(index?: number): any;
/**
* Get an item by index.
*
* @param index - Index of the item to get
* @returns The item at the specified index
*/
get(index: number): any;
/**
* Convert the MediaList to a plain array.
*
* @returns Array of all items
*/
toList(): any[];
/**
* Get the number of items in the list.
*/
get length(): number;
/**
* Check if the list is empty.
*
* @returns Whether the list has no items
*/
isEmpty(): boolean;
/**
* Get information about the media list.
*
* @returns Object with list information
*/
getInfo(): {
fileName: string;
totalFiles: number;
mediaFiles: number;
urlFiles: number;
nonProcessableFiles: number;
totalSize: number;
};
/**
* Get the filename.
*/
getFileName(): string;
/**
* Set the filename.
*/
setFileName(fileName: string): void;
/**
* Get the content type (returns 'application/x-media-list' for containers).
*/
getContentType(): string;
/**
* Set the content type (not applicable for MediaList).
*/
setContentType(_contentType: string): void;
/**
* Implement iterator protocol to allow for...of loops.
*
* @returns Iterator for the list items
*/
[Symbol.iterator](): Iterator<any>;
}
import { FileResult } from './types';
import { IMediaFile } from './types';
/**
* A class for standardized file handling across browser and Node.js environments.
* Provides methods to load files from various sources and convert between formats.
*/
export declare class MediaFile implements IMediaFile {
protected content_type: string;
protected file_name: string;
protected _content: ArrayBuffer | null;
/**
* Creates a new MediaFile instance.
*
* @param file_name - Default filename to use
* @param content_type - Default content type to use
*/
constructor(file_name?: string, content_type?: string);
/**
* Factory method to create a MediaFile from any supported data type.
* This is kept for backward compatibility. New code should use MediaFileFactory.create().
*
* @param data - Data to load (file path, URL, base64 string, etc.)
* @returns Promise resolving to a MediaFile instance or specialized subclass
* @deprecated Use MediaFileFactory.create() instead
*/
static create(data: any): Promise<MediaFile>;
/**
* Load a file from any supported data type.
*
* @param data - Data to load (file path, URL, base64 string, etc.)
* @param websafe - Prevents loading from file paths and malformatted base64 strings.
* @returns Promise resolving to a MediaFile instance or null
*/
fromAny(data: any): Promise<MediaFile>;
/**
* Load file from a file path (Node.js only).
*
* @param filePath - Path to the file
* @returns Promise resolving to the MediaFile instance
*/
fromFile(filePath: string): Promise<MediaFile>;
/**
* Load file from a URL.
*
* @param url - URL to fetch the file from
* @param headers - Optional headers for the request
* @returns Promise resolving to the MediaFile instance
*/
fromUrl(url: string, headers?: Record<string, string>): Promise<MediaFile>;
/**
* Load file from base64 encoded string.
*
* @param base64Data - Base64 encoded string, optionally with data URI prefix
* @returns The MediaFile instance
*/
fromBase64(base64Data: string): MediaFile;
/**
* Load file from binary data.
*
* @param data - ArrayBuffer, Buffer, or Uint8Array containing the file data
* @returns The MediaFile instance
*/
fromBytes(data: ArrayBuffer | Buffer | ArrayBufferLike | SharedArrayBuffer | Uint8Array): MediaFile;
/**
* Load file from a FileResult object.
*
* @param fileResult - FileResult object with file metadata and base64 content
* @returns The MediaFile instance
*/
fromDict(fileResult: FileResult): Promise<MediaFile>;
/**
* Convert the file to a Blob (browser only).
*
* @returns Blob object representing the file
*/
toBlob(): Blob;
/**
* Convert the file to an ArrayBuffer.
*
* @returns ArrayBuffer containing the file data
*/
toArrayBuffer(): ArrayBuffer;
/**
* Convert the file to a Uint8Array.
*
* @returns Uint8Array containing the file data
*/
toUint8Array(): Uint8Array;
/**
* Convert the file to a Node.js Buffer (Node.js only).
*
* @returns Buffer containing the file data
*/
toBuffer(): Buffer;
/**
* Convert the file to a base64 encoded string.
*
* @param includeDataUri - Whether to include the data URI prefix
* @returns Base64 encoded string of the file data
*/
toBase64(includeDataUri?: boolean): string;
/**
* Convert the file to a FileResult object.
*
* @returns FileResult object with file metadata and base64 content
*/
toJson(): FileResult;
/**
* Save the file to disk (Node.js) or trigger download (browser).
*
* @param filePath - Optional file path (Node.js) or filename (browser)
* @returns Promise that resolves when the file is saved
*/
save(filePath?: string): Promise<void>;
/**
* Get the file size in bytes.
*
* @param unit - Unit to return the size in ('bytes', 'kb', 'mb', or 'gb')
* @returns File size in the specified unit
*/
fileSize(unit?: 'bytes' | 'kb' | 'mb' | 'gb'): number;
/**
* Get the file extension based on the content type or filename.
*
* @returns File extension without the leading dot, or null if it cannot be determined
*/
get extension(): string | null;
/**
* Get the filename.
*/
getFileName(): string;
/**
* Set the filename.
*/
setFileName(fileName: string): void;
/**
* Get the content type.
*/
getContentType(): string;
/**
* Set the content type.
*/
setContentType(contentType: string): void;
/**
* Read raw file data.
*
* @returns ArrayBuffer containing the file data
*/
read(): ArrayBuffer;
/**
* Check if the file is empty.
*
* @returns Boolean indicating if the file has content
*/
isEmpty(): boolean;
/**
* Get info about the file.
*
* @returns Object with file information
*/
getInfo(): {
fileName: string;
contentType: string;
size: number;
extension: string | null;
};
/**
* Detect MIME type for the file based on file extension.
* Updates the content_type property.
*
* @private
*/
protected _setContentTypeFromFileName(): void;
/**
* Parse a base64 data URI into content and media type.
*
* @param data - Base64 string, potentially with data URI prefix
* @returns Object containing the parsed data and media type
* @private
*/
protected _parseBase64Uri(data: string): {
data: string;
mediaType: string | null;
};
/**
* Ensure content exists before operating on it.
*
* @private
*/
protected _ensureContent(): void;
/**
* Check if an object is a Buffer.
*
* @param obj - Object to check
* @returns Whether the object is a Buffer
* @private
*/
protected _isBuffer(obj: any): boolean;
/**
* Decode base64 string in Node.js environment.
*
* @param base64 - Base64 string to decode
* @returns ArrayBuffer containing the decoded data
* @private
*/
protected _decodeBase64NodeJs(base64: string): ArrayBuffer;
/**
* Decode base64 string in browser environment.
*
* @param base64 - Base64 string to decode
* @returns ArrayBuffer containing the decoded data
* @private
*/
protected _decodeBase64Browser(base64: string): ArrayBuffer;
/**
* Convert a Node.js Buffer to an ArrayBuffer.
*
* @param buffer - Buffer to convert
* @returns ArrayBuffer containing the data
* @private
*/
private _bufferToArrayBuffer;
}
export interface IMediaFile {
fromAny(data: any): Promise<IMediaFile>;
getContentType(): string | null;
}
/**
* Interface representing a file result with metadata and content.
* Used for serialization and deserialization of MediaFile objects.
*/
export interface FileResult {
/**
* The name of the file
*/
file_name: string;
/**
* The MIME type of the file content
*/
content_type: string;
/**
* The file content, typically as a base64 encoded string,
* but can also be provided as other formats like ArrayBuffer,
* Blob, or URL that will be processed by MediaFile
*/
content: string | ArrayBuffer | Blob | any;
}
import { MediaFile } from './MediaFile';
/**
* A specialized MediaFile class for handling video files.
* Provides methods specific to video processing and playback.
*/
export declare class VideoFile extends MediaFile {
/**
* Creates a new VideoFile instance.
*
* @param file_name - Default filename to use
* @param content_type - Default content type to use (defaults to video/mp4)
*/
constructor(file_name?: string, content_type?: string);
/**
* Factory method to create a VideoFile from any supported data type.
*
* @param data - Data to load (file path, URL, base64 string, etc.)
* @returns Promise resolving to a VideoFile instance
*/
static create(data: any): Promise<VideoFile>;
/**
* Override fromAny to ensure the content type is a video type.
*
* @param data - Data to load
* @returns Promise resolving to a VideoFile instance
*/
fromAny(data: any): Promise<VideoFile>;
/**
* Creates an HTML video element from the video data.
*
* @returns HTMLVideoElement that can be used for playback
*/
toVideoElement(): HTMLVideoElement;
/**
* Play the video (browser only).
*
* @returns Promise that resolves when video playback starts
*/
play(): Promise<void>;
/**
* Get duration of the video file in seconds (browser only).
*
* @returns Promise resolving to the duration in seconds
*/
getDuration(): Promise<number>;
/**
* Get dimensions of the video (width and height).
*
* @returns Promise resolving to an object with width and height properties
*/
getDimensions(): Promise<{
width: number;
height: number;
}>;
/**
* Create a thumbnail from the video at a specific time point.
*
* @param timeSeconds - Time in seconds for the thumbnail (defaults to 0)
* @returns Promise resolving to a Blob containing the thumbnail image
*/
createThumbnail(timeSeconds?: number): Promise<Blob>;
/**
* Create an embedded HTML video player.
*
* @param options - Options for the video player
* @returns HTML string containing a video element
*/
toHtmlPlayer(options?: {
controls?: boolean;
autoplay?: boolean;
loop?: boolean;
muted?: boolean;
width?: number;
height?: number;
poster?: string;
}): string;
/**
* Validate that the content type is a video type.
* If not, attempt to correct it based on file extension or magic bytes.
*
* @private
*/
private _validateVideoContentType;
}
import { MediaFile, ImageFile, AudioFile, VideoFile, Asset3DFile, MediaList, MediaDict } from './core';
export { MediaFile, ImageFile, AudioFile, VideoFile, Asset3DFile, MediaList, MediaDict };
export type { IMediaContainer } from './core/media_containers/IMediaContainer';
export type { MediaListOptions } from './core/media_containers/media_list';
export type { MediaDictOptions } from './core/media_containers/media_dict';
import { MediaFileFactory } from './MediaFileFactory';
export { MediaFileFactory };
export { parseSocaityAPIJobResult } from './utils';
export { detectContentType, isValidFilePath, isUrl, detectMimeTypeFromUrl, isFileReaderObject, isFileResult } from './core/content_detectors/ContentDetector';
export type { FileResult } from './core/types';
export * from './core/content_detectors/SupportedTypes';
import { MediaFile } from './core/MediaFile';
/**
* Factory class for creating appropriate MediaFile instances based on content type detection.
*/
export declare class MediaFileFactory {
/**
* Create a MediaFile or specialized subclass from any supported data type.
* Automatically detects data type and instantiates the appropriate class.
*
* @param data - Data to load (file path, URL, base64 string, etc.)
* @returns Promise resolving to a MediaFile instance or specialized subclass
*/
static create(data: any): Promise<MediaFile>;
}
import { FileResult } from './core/types';
import { MediaFile } from './core/MediaFile';
export declare const isNode: boolean;
/**
* Parses the result data from a Socaity API job.
* Handles nested arrays and FileResult objects.
* @param result - Result data to parse
*/
export declare function parseSocaityAPIJobResult(result: Array<string> | Array<FileResult> | FileResult | any): Promise<MediaFile | Array<MediaFile> | null | any>;