import { Meter, MeterProvider, Tracer, TracerProvider } from "@opentelemetry/api"; //#region src/auth/types.d.ts /** * Manages authentication credentials for a platform. * * @precondition An implementation must be provided per platform * @postcondition getAuthHeader always returns a valid Authorization header value * @category Plugin Development */ type TokenManager = { /** Returns a valid auth header value (e.g., "Bearer "). */getAuthHeader(): Promise; /** Invalidate current token (called on 401 response). */ invalidate(): void; }; /** * Companion object for the TokenManager type. * Provides factory utilities for common auth patterns. * * @category Plugin Development * @example * ```ts * const tm = TokenManager.static("Bearer my-token"); * ``` */ declare const TokenManager: { /** * Creates a TokenManager for static credentials that never change. * * @param header - auth header value (e.g., "Basic abc123") * @param platform - platform identifier for error messages * @returns a TokenManager with fixed credentials * @precondition header is a non-empty auth header value (e.g., "Basic abc123") * @postcondition getAuthHeader always returns the same header * @postcondition invalidate always throws AuthenticationError * @idempotency Safe — no side effects */ readonly static: (header: string, platform?: string) => TokenManager; /** * Type guard for TokenManager. * * @param value - the value to check * @returns true if value implements TokenManager interface * @postcondition returns true if value has getAuthHeader and invalidate methods */ readonly is: (value: unknown) => value is TokenManager; }; //#endregion //#region src/rest/types.d.ts /** * Describes an outgoing HTTP request to a platform API. * * @precondition path is a relative path (e.g., "/videos") * @postcondition query values are URL-encoded by the RestManager * @category Plugin Development */ type RestRequest = { method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; path: string; query?: Record; body?: unknown; /** * Body serialization format. * - "json" (default): JSON.stringify the body and set Content-Type: application/json * - "raw": pass body directly to fetch (e.g., for FormData, URLSearchParams, ReadableStream) */ bodyType?: "json" | "raw"; headers?: Record; /** AbortSignal to cancel the request. */ signal?: AbortSignal; /** Rate limit bucket key (e.g., "videos:list", "search:list"). */ bucketId?: string; }; /** * Parsed response from a platform API request. * * @postcondition data contains the parsed JSON response body * @category Plugin Development */ type RestResponse = { status: number; headers: Headers; data: T; rateLimit?: RateLimitInfo; }; /** * Rate limit metadata extracted from response headers. * * @category Plugin Development */ type RateLimitInfo = { limit: number; remaining: number; resetsAt: Date; bucket?: string; }; /** * Configuration options for creating a RestManager. * * @precondition baseUrl must use HTTPS * @precondition rateLimitStrategy must be initialized * @category Plugin Development */ type RestManagerOptions = { platform: string; baseUrl: string; headers?: Record; rateLimitStrategy: RateLimitStrategy; tokenManager?: TokenManager; fetch?: typeof globalThis.fetch; retry?: RetryConfig; tracerProvider?: TracerProvider; meterProvider?: MeterProvider; }; /** * Configuration for request retry behavior. * * @category Plugin Development */ type RetryConfig = { maxRetries?: number; baseDelay?: number; retryableStatuses?: number[]; /** Request timeout in milliseconds. Applied when no user-provided signal exists. */ timeout?: number; }; /** * Creates a rate limit header parser from header name mappings. * Eliminates duplication across plugins that use standard limit/remaining/reset headers. * * @param headerNames - mapping of header names for limit, remaining, and reset * @returns a parser function that extracts rate limit info from headers * @idempotency Safe — returns a pure function * @category Plugin Development */ declare const createRateLimitHeaderParser: (headerNames: { limit: string; remaining: string; reset: string; }) => ((headers: Headers) => RateLimitInfo | undefined); //#endregion //#region src/rest/strategy.d.ts /** * Handle returned by a rate limit strategy after acquiring a slot. * Callers must invoke either complete() or release() — never both. * * @postcondition complete() is called on success, release() on error * @category Plugin Development */ type RateLimitHandle = { /** Called after successful response — updates state from response headers. */complete(headers: Headers): void; /** Called on retry — returns the consumed token/quota. */ release(): void; }; /** * Snapshot of a rate limit strategy's current state for telemetry. * * @category Plugin Development */ type RateLimitStatus = { remaining: number; limit: number; resetsAt: Date; queued: number; }; /** * Controls request throughput for a platform's rate limiting scheme. * * @precondition One strategy instance per platform * @postcondition acquire() resolves when it's safe to proceed with the request * @category Plugin Development */ type RateLimitStrategy = { /** * Called before each request. * Consumes a token/quota unit and returns a handle. * May block (await) if tokens are exhausted. */ acquire(req: RestRequest): Promise; /** Current rate limit status (for telemetry). */ getStatus(): RateLimitStatus; }; /** * Companion object for the RateLimitStrategy type. * Provides type guard utility. * * @example * ```ts * if (RateLimitStrategy.is(unknown)) { ... } * ``` * @category Plugin Development */ declare const RateLimitStrategy: { /** * Type guard for RateLimitStrategy. * * @param value - the value to check * @returns true if value implements RateLimitStrategy interface * @postcondition returns true if value has acquire and getStatus methods */ readonly is: (value: unknown) => value is RateLimitStrategy; }; //#endregion //#region src/rest/manager.d.ts /** @category Plugin Development */ type RestManager = { readonly platform: string; readonly baseUrl: string; readonly rateLimitStrategy: RateLimitStrategy; readonly tokenManager: TokenManager | undefined; /** * Execute a full request lifecycle: rate limit → headers → fetch → retry → parse. * * @precondition rateLimitStrategy is initialized * @postcondition returns parsed response or throws an error from the hierarchy */ request: (req: RestRequest) => Promise>; /** * Build auth + custom headers for a request. Override to inject platform-specific headers. * * @precondition tokenManager (if set) is ready to provide auth headers * @postcondition returns a headers record including Authorization if tokenManager is set */ createHeaders: (req: RestRequest) => Promise>; /** * Execute a single fetch call. Override to add logging, metrics, or custom transport. * * @precondition url is a fully-qualified URL * @postcondition returns the raw Response from the server */ runRequest: (url: string, init: RequestInit) => Promise; /** * Parse the response body as JSON and construct a RestResponse. * Throws UnifiedLiveError if the response is not valid JSON. * * @precondition response.ok or a handled status code * @postcondition returns a RestResponse with parsed data and optional rate limit info */ handleResponse: (response: Response, req: RestRequest) => Promise>; /** * Handle rate-limited responses (429, 403). Return true to retry. * Override for platform-specific quota/rate limit detection. * * @precondition response has status 429 or 403 * @postcondition returns true if the request should be retried, false otherwise */ handleRateLimit: (response: Response, req: RestRequest, attempt: number) => Promise; /** * Extract rate limit info from response headers. Override per platform. * Default returns undefined (no parsing). * * @postcondition returns RateLimitInfo if headers contain rate limit data, undefined otherwise */ parseRateLimitHeaders: (headers: Headers) => RateLimitInfo | undefined; }; /** * Creates a discordeno-style RestManager with overridable function properties. * * @param options - REST manager configuration * @returns a new RestManager instance * @precondition options.rateLimitStrategy is initialized * @postcondition returns a RestManager with all methods set * @idempotency Not idempotent — each call creates a new manager instance * @category Plugin Development */ declare const createRestManager: (options: RestManagerOptions) => RestManager; /** * Companion object for the RestManager type. * Provides type guard utility. * * @category Plugin Development */ declare const RestManager: { /** * Type guard for RestManager. * * @param value - the value to check * @returns true if value implements RestManager interface */ readonly is: (value: unknown) => value is RestManager; }; /** * Parse a Retry-After header value into a bounded number of seconds. * Returns fallback if the header is missing, NaN, or out of bounds. * * @param header - raw Retry-After header value (may be null) * @param fallback - default seconds if header is missing or invalid * @returns seconds in range [0, 120], or fallback if header is missing/invalid * @category Plugin Development */ declare const parseRetryAfter: (header: string | null, fallback?: number) => number; //#endregion //#region src/errors.d.ts /** * Hierarchical error code for all unified-live SDK errors. * * Categories: NOT_FOUND, AUTHENTICATION_*, RATE_LIMIT_*, QUOTA_*, * NETWORK_*, PARSE_*, VALIDATION_*, PLATFORM_*, INTERNAL. * * @category Errors */ type ErrorCode = "NOT_FOUND" | "AUTHENTICATION_INVALID" | "AUTHENTICATION_EXPIRED" | "RATE_LIMIT_EXCEEDED" | "QUOTA_EXHAUSTED" | "NETWORK_TIMEOUT" | "NETWORK_CONNECTION" | "NETWORK_DNS" | "NETWORK_ABORT" | "PARSE_JSON" | "PARSE_RESPONSE" | "VALIDATION_INVALID_URL" | "VALIDATION_INVALID_INPUT" | "PLATFORM_NOT_FOUND" | "INTERNAL"; /** * Companion object for the ErrorCode type. * Provides category helpers for error classification in monitoring and alerting. * * @example * ```ts * if (ErrorCode.isNetwork(error.code)) { ... } * ``` * @category Errors */ declare const ErrorCode: { /** * Whether the error code represents a network-level failure. * * @param code - the error code to check * @returns true if the code is a network error */ readonly isNetwork: (code: ErrorCode) => boolean; /** * Whether the error code represents an authentication failure. * * @param code - the error code to check * @returns true if the code is an auth error */ readonly isAuth: (code: ErrorCode) => boolean; /** * Whether the error code represents a client-side error (validation, not found). * * @param code - the error code to check * @returns true if the code is a client error */ readonly isClientError: (code: ErrorCode) => boolean; /** * Whether the error code represents a rate limiting issue. * * @param code - the error code to check * @returns true if the code is a rate limit error */ readonly isRateLimit: (code: ErrorCode) => boolean; }; /** * Structured metadata attached to every SDK error. * * @postcondition platform is always present * @category Errors */ type ErrorContext = { /** Platform name (always present). */platform: string; /** HTTP method if the error occurred during a request. */ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; /** Request path (e.g., "/videos"). */ path?: string; /** HTTP status code from the response. */ status?: number; /** Resource ID that was being accessed. */ resourceId?: string; }; /** * Base error for all unified-live SDK errors. * * @precondition message is a non-empty string * @precondition code is a valid ErrorCode * @precondition context.platform is a non-empty string * @postcondition instanceof UnifiedLiveError === true for all SDK errors * @idempotency constructing with the same arguments yields equivalent errors * @category Errors */ declare class UnifiedLiveError extends Error { readonly code: ErrorCode; readonly context: ErrorContext; constructor(message: string, code: ErrorCode, context: ErrorContext, options?: { cause?: Error; }); /** * Backward-compatible getter for context.platform. * * @returns the platform name */ get platform(): string; get [Symbol.toStringTag](): string; /** * Structured representation for JSON.stringify and structured logging. * * @returns a plain object with error details including cause chain * @postcondition returned object is JSON-serializable */ toJSON(): Record; /** * Whether this error is transient and the operation may succeed on retry. * * @returns true for rate limits, network issues, and server errors * @postcondition auth errors, not found, validation, and parse errors return false */ get retryable(): boolean; } /** * Resource not found on platform. * * @category Errors */ declare class NotFoundError extends UnifiedLiveError { readonly code: "NOT_FOUND"; constructor(platform: string, resourceId: string, options?: { cause?: Error; }); } type AuthenticationCode = "AUTHENTICATION_INVALID" | "AUTHENTICATION_EXPIRED"; /** * Credentials invalid or expired. * * @category Errors */ declare class AuthenticationError extends UnifiedLiveError { readonly code: AuthenticationCode; constructor(platform: string, options?: { code?: AuthenticationCode; message?: string; cause?: Error; }); } /** * Rate limit exceeded after max retries. * * @category Errors */ declare class RateLimitError extends UnifiedLiveError { readonly code: "RATE_LIMIT_EXCEEDED"; readonly retryAfter?: number; constructor(platform: string, options?: { retryAfter?: number; cause?: Error; }); toJSON(): Record; } /** @category Errors */ type QuotaDetails = { consumed: number; limit: number; resetsAt: Date; requestedCost: number; }; /** * YouTube daily quota exhausted. * * @category Errors */ declare class QuotaExhaustedError extends UnifiedLiveError { readonly code: "QUOTA_EXHAUSTED"; readonly details: QuotaDetails; constructor(platform: string, details: QuotaDetails, options?: { cause?: Error; }); toJSON(): Record; } /** @category Errors */ type NetworkCode = "NETWORK_TIMEOUT" | "NETWORK_CONNECTION" | "NETWORK_DNS" | "NETWORK_ABORT"; /** * Fetch-level network failure. * * @category Errors */ declare class NetworkError extends UnifiedLiveError { readonly code: NetworkCode; constructor(platform: string, code: NetworkCode, options?: { message?: string; path?: string; method?: ErrorContext["method"]; status?: number; cause?: Error; }); } type ParseCode = "PARSE_JSON" | "PARSE_RESPONSE"; /** * Response parsing failure. * * @category Errors */ declare class ParseError extends UnifiedLiveError { readonly code: ParseCode; constructor(platform: string, code: ParseCode, options?: { message?: string; path?: string; status?: number; cause?: Error; }); } type ValidationCode = "VALIDATION_INVALID_URL" | "VALIDATION_INVALID_INPUT"; /** * Input validation failure. * * @category Errors */ declare class ValidationError extends UnifiedLiveError { readonly code: ValidationCode; constructor(code: ValidationCode, message: string, options?: { platform?: string; cause?: Error; }); } /** * Platform not registered in client. * * @category Errors */ declare class PlatformNotFoundError extends UnifiedLiveError { readonly code: "PLATFORM_NOT_FOUND"; constructor(platform: string); } /** * Classify a fetch error into a specific NetworkCode. * * @param error - the caught fetch exception * @returns the classified network error code * @precondition error is a caught fetch exception * @postcondition returns one of NETWORK_ABORT, NETWORK_TIMEOUT, NETWORK_DNS, NETWORK_CONNECTION * @idempotency same error always produces same code * @category Errors */ declare const classifyNetworkError: (error: Error) => NetworkCode; //#endregion //#region src/types.d.ts /** * Image thumbnail with URL and dimensions in pixels. * * @category Types */ type Thumbnail = { url: string; width: number; height: number; }; /** * Lightweight channel reference embedded in content objects. * * @category Types */ type ChannelRef = { id: string; name: string; url: string; }; type ContentBase = { id: string; platform: string; title: string; description: string; tags: string[]; url: string; thumbnail: Thumbnail; channel: ChannelRef; sessionId?: string; raw: unknown; languageCode?: string; }; /** * A currently-active broadcast on any supported platform. * Discriminated by `type: "broadcast"`. Use `Content.isBroadcast()` to narrow from Content. * * @category Types */ type Broadcast = ContentBase & { type: "broadcast"; viewerCount: number; startedAt: Date; endedAt?: Date; }; /** * An archived broadcast recording on any supported platform. * Discriminated by `type: "archive"`. Use `Content.isArchive()` to narrow from Content. * * @category Types */ type Archive = ContentBase & { type: "archive"; duration: number; viewCount: number; publishedAt: Date; startedAt?: Date; endedAt?: Date; }; /** * A scheduled (upcoming) broadcast on any supported platform. * Discriminated by `type: "scheduled"`. Use `Content.isScheduledBroadcast()` to narrow from Content. * * @category Types */ type ScheduledBroadcast = ContentBase & { type: "scheduled"; scheduledStartAt: Date; }; /** * A short clip extracted from a broadcast or archive on any supported platform. * Discriminated by `type: "clip"`. Use `Content.isClip()` to narrow from Content. * * @category Types */ type Clip = ContentBase & { type: "clip"; duration: number; viewCount: number; createdAt: Date; clipCreator?: { id: string; name: string; }; embedUrl?: string; vodOffset?: number; isFeatured?: boolean; gameId?: string; }; /** * A piece of content (broadcast, archive, scheduled broadcast, or clip) on any supported platform. * Use `Content.isBroadcast()` / `Content.isArchive()` / `Content.isScheduledBroadcast()` / `Content.isClip()` to narrow. * * @category Types */ type Content = Broadcast | Archive | ScheduledBroadcast | Clip; /** * A streaming channel or user account on any supported platform. * * @category Types */ type Channel = { id: string; platform: string; name: string; url: string; thumbnail?: Thumbnail; description?: string; subscriberCount?: number; publishedAt?: Date; }; /** * Links a broadcast to its eventual archive. * `contentIds` maps between the broadcast ID and archive ID. * * @category Types */ type BroadcastSession = { sessionId: string; platform: string; channel: ChannelRef; startedAt: Date; endedAt?: Date; contentIds: { broadcastId?: string; archiveId?: string; }; }; /** * Cursor-based pagination wrapper. * `hasMore` indicates whether additional pages exist. * Pass `cursor` to the next call to fetch the next page. * * @category Types */ type Page = { items: T[]; cursor?: string; total?: number; hasMore: boolean; }; /** * Companion object for the Page type. * Provides transformation and factory utilities. * * @example * ```ts * const mapped = Page.map(page, (item) => item.id); * const empty = Page.empty(); * ``` * @category Types */ declare const Page: { /** * Transform items in a page while preserving pagination metadata. * * @param page - the source page * @param fn - mapping function applied to each item * @returns a new Page with transformed items * @postcondition cursor, total, and hasMore are preserved * @idempotency Safe — pure function */ readonly map: (page: Page, fn: (item: T) => U) => Page; /** * Create an empty page with no items. * * @returns an empty Page with hasMore=false * @idempotency Safe — pure function */ readonly empty: () => Page; }; /** * Result of a batch operation. Contains successful results and per-item errors. * Request-level errors (rate limit, auth) are thrown, not stored here. * * @category Types */ type BatchResult = { readonly values: ReadonlyMap; readonly errors: ReadonlyMap; }; /** * Companion object for the BatchResult type. * Provides factory utilities. * * @example * ```ts * const empty = BatchResult.empty(); * ``` * @category Types */ declare const BatchResult: { /** * Create an empty BatchResult with no values or errors. * * @returns an empty BatchResult * @idempotency Safe — pure function */ readonly empty: () => BatchResult; }; /** * Options for search operations across platforms. * All fields are optional at the type level, but `UnifiedClient.search()` * requires at least one of `query`, `status`, or `channelId` to be provided. * * @category Types */ type SearchOptions = { query?: string; status?: "live" | "upcoming" | "ended"; channelId?: string; order?: "relevance" | "date" | "rating" | "title" | "videoCount" | "viewCount"; limit?: number; cursor?: string; safeSearch?: "moderate" | "none" | "strict"; languageCode?: string; }; /** * Options for archive listing operations. * * @category Types */ type ArchiveListOptions = { period?: "all" | "day" | "week" | "month"; sort?: "time" | "trending" | "views"; videoType?: string; }; /** * Options for clip retrieval operations. * * @category Types */ type ClipOptions = { startedAt?: Date; endedAt?: Date; limit?: number; cursor?: string; isFeatured?: boolean; }; /** * Known supported platform identifiers. * * @category Types */ declare const knownPlatforms: readonly ["youtube", "twitch", "twitcasting"]; /** * A known supported platform identifier. * * @category Types */ type KnownPlatform = (typeof knownPlatforms)[number]; /** * Result of resolving a platform URL without network calls. * Contains detected platform, resource type, and platform-specific ID. * * @category Types */ type ResolvedUrl = { platform: string; type: "content" | "channel"; id: string; }; /** * Companion object for the Broadcast type. * Provides lightweight structural type guard. * * @example * ```ts * if (Broadcast.is(value)) { ... } * ``` * @category Types */ declare const Broadcast: { /** * Structural type guard for Broadcast. * * @param value - the value to check * @returns true if value has the Broadcast shape (type === "broadcast") */ readonly is: (value: unknown) => value is Broadcast; }; /** * Companion object for the ScheduledBroadcast type. * Provides lightweight structural type guard. * * @example * ```ts * if (ScheduledBroadcast.is(value)) { ... } * ``` * @category Types */ declare const ScheduledBroadcast: { /** * Structural type guard for ScheduledBroadcast. * * @param value - the value to check * @returns true if value has the ScheduledBroadcast shape (type === "scheduled") */ readonly is: (value: unknown) => value is ScheduledBroadcast; }; /** * Companion object for the Archive type. * Provides lightweight structural type guard. * * @example * ```ts * if (Archive.is(value)) { ... } * ``` * @category Types */ declare const Archive: { /** * Structural type guard for Archive. * * @param value - the value to check * @returns true if value has the Archive shape (type === "archive") */ readonly is: (value: unknown) => value is Archive; }; /** * Companion object for the Channel type. * Provides lightweight structural type guard. * * @example * ```ts * if (Channel.is(value)) { ... } * ``` * @category Types */ declare const Channel: { /** * Structural type guard for Channel. * * @param value - the value to check * @returns true if value has the Channel shape */ readonly is: (value: unknown) => value is Channel; }; /** * Companion object for the Clip type. * Provides lightweight structural type guard. * * @example * ```ts * if (Clip.is(value)) { ... } * ``` * @category Types */ declare const Clip: { /** * Structural type guard for Clip. * * @param value - the value to check * @returns true if value has the Clip shape (type === "clip") */ readonly is: (value: unknown) => value is Clip; }; /** * Companion object for the BroadcastSession type. * Provides lightweight structural type guard. * * @example * ```ts * if (BroadcastSession.is(value)) { ... } * ``` * @category Types */ declare const BroadcastSession: { /** * Structural type guard for BroadcastSession. * * @param value - the value to check * @returns true if value has the BroadcastSession shape */ readonly is: (value: unknown) => value is BroadcastSession; }; /** * Type guard namespace for Content discriminated union. * * @precondition content must be a valid Content value * @postcondition narrows to Broadcast, Archive, ScheduledBroadcast, or Clip * @category Types */ declare const Content: { readonly isBroadcast: (content: Content) => content is Broadcast; readonly isScheduledBroadcast: (content: Content) => content is ScheduledBroadcast; readonly isArchive: (content: Content) => content is Archive; readonly isClip: (content: Content) => content is Clip; }; //#endregion //#region src/plugin.d.ts /** @category Plugins */ type PluginCapabilities = { /** Whether the plugin supports broadcast detection */supportsBroadcasts: boolean; /** Whether the plugin supports archive resolution (broadcast -> archive) */ supportsArchiveResolution: boolean; /** Authentication model used by this plugin */ authModel: "apiKey" | "oauth2" | "basic" | "none"; /** Rate limiting model */ rateLimitModel: "quota" | "tokenBucket"; /** Whether the plugin supports batch content retrieval */ supportsBatchContent: boolean; /** Whether the plugin supports batch broadcast retrieval */ supportsBatchBroadcasts: boolean; /** Whether the plugin supports search */ supportsSearch: boolean; /** Whether the plugin supports clip retrieval */ supportsClips: boolean; }; /** * Declarative configuration for creating a PlatformPlugin via `PlatformPlugin.create()`. * Plugin authors provide this instead of manually wiring RestManager overrides. * * @category Plugins */ type PluginDefinition = { /** Platform identifier (e.g., "youtube", "twitch"). */name: string; /** Base URL for the platform's API. */ baseUrl: string; /** Rate limiting strategy instance. */ rateLimitStrategy: RateLimitStrategy; /** Token manager for auth (optional — some platforms use query param auth). */ tokenManager?: TokenManager; /** URL matcher — pure function, no network calls. */ matchUrl: (url: string) => ResolvedUrl | null; /** Transform requests before sending (e.g., inject API key, add headers). */ transformRequest?: (req: RestRequest) => RestRequest; /** Additional default headers for all requests. */ headers?: Record; /** Platform-specific rate limit handling (e.g., YouTube 403 quota detection). */ handleRateLimit?: (response: Response, req: RestRequest, attempt: number) => Promise; /** Parse rate limit info from response headers. */ parseRateLimitHeaders?: (headers: Headers) => RateLimitInfo | undefined; /** Override fetch for testing. */ fetch?: typeof globalThis.fetch; /** Retry configuration. */ retry?: RetryConfig; /** Plugin capability metadata. */ capabilities?: PluginCapabilities; }; /** * Platform-specific data access methods. * Separated from PluginDefinition because they need access to the constructed RestManager. * Methods receive `rest` as the first argument — pure functions that are easier to test and compose. * * @category Plugins */ type PluginMethods = { /** Retrieve content by ID. */getContent: (rest: RestManager, id: string) => Promise; /** Retrieve channel by ID. */ getChannel: (rest: RestManager, id: string) => Promise; /** List currently active broadcasts for a channel. */ listBroadcasts: (rest: RestManager, channelId: string) => Promise; /** List archives for a channel with pagination. */ listArchives: (rest: RestManager, channelId: string, cursor?: string, pageSize?: number, options?: ArchiveListOptions) => Promise>; /** Resolve the archive for a broadcast (optional). */ resolveArchive?: (rest: RestManager, live: Broadcast) => Promise; /** Batch-retrieve content by IDs (optional). */ batchGetContents?: (rest: RestManager, ids: string[]) => Promise>; /** Batch-retrieve broadcasts by channel IDs (optional). */ batchGetBroadcasts?: (rest: RestManager, channelIds: string[]) => Promise>; /** Search for content (optional). */ search?: (rest: RestManager, options: SearchOptions) => Promise>; /** List clips for a channel (optional). */ listClips?: (rest: RestManager, channelId: string, options?: ClipOptions) => Promise>; /** Batch-retrieve clips by IDs (optional). */ batchGetClips?: (rest: RestManager, ids: string[]) => Promise>; /** Batch-retrieve channels by IDs (optional). */ batchGetChannels?: (rest: RestManager, ids: string[]) => Promise>; }; /** * A platform-specific plugin that implements data retrieval for a single streaming platform. * * @precondition Each plugin instance is bound to a single platform * @postcondition All returned data conforms to the unified Content/Channel types * @category Plugins */ type PlatformPlugin = { /** Platform identifier (e.g., "youtube", "twitch", "twitcasting"). */readonly name: string; /** The underlying RestManager for this plugin. */ readonly rest: RestManager; /** Plugin capability metadata. */ readonly capabilities: PluginCapabilities; /** * Test whether a URL belongs to this platform. * Returns a ResolvedUrl if matched, or null if not. * No network calls. */ match(url: string): ResolvedUrl | null; /** Retrieve content (broadcast or archive) by ID. */ getContent(id: string): Promise; /** Retrieve channel information by ID. */ getChannel(id: string): Promise; /** List currently active broadcasts for a channel. */ listBroadcasts(channelId: string): Promise; /** List archives for a channel with cursor-based pagination. */ listArchives(channelId: string, cursor?: string, pageSize?: number, options?: ArchiveListOptions): Promise>; /** Resolve the archive for a broadcast (platform-specific). */ resolveArchive?(live: Broadcast): Promise; /** Batch-retrieve content by IDs (platform-specific). */ batchGetContents?(ids: string[]): Promise>; /** Batch-retrieve broadcasts by channel IDs (platform-specific). */ batchGetBroadcasts?(channelIds: string[]): Promise>; /** Search for content (platform-specific). */ search?(options: SearchOptions): Promise>; /** List clips for a channel (platform-specific). */ listClips?(channelId: string, options?: ClipOptions): Promise>; /** Batch-retrieve clips by IDs (platform-specific). */ batchGetClips?(ids: string[]): Promise>; /** Batch-retrieve channels by IDs (platform-specific). */ batchGetChannels?(ids: string[]): Promise>; }; /** * Companion object for the PlatformPlugin type. * Provides factory and type guard utilities. * * @category Plugins * @example * ```ts * const plugin = PlatformPlugin.create(definition, methods); * if (PlatformPlugin.is(unknown)) { ... } * ``` */ declare const PlatformPlugin: { /** * Create a PlatformPlugin from a declarative definition and methods. * * @param definition - declarative plugin configuration * @param methods - platform-specific data access implementations * @returns a fully wired PlatformPlugin * @precondition definition.rateLimitStrategy is initialized * @postcondition returns a fully functional PlatformPlugin with wired RestManager */ readonly create: (definition: PluginDefinition, methods: PluginMethods) => PlatformPlugin; /** * Type guard for PlatformPlugin. * * @param value - the value to check * @returns true if value implements PlatformPlugin * @postcondition returns true if value has all required PlatformPlugin properties */ readonly is: (value: unknown) => value is PlatformPlugin; }; //#endregion //#region src/client.d.ts /** @category Client */ type UnifiedClientOptions = { plugins?: PlatformPlugin[]; tracerProvider?: TracerProvider; }; /** @category Client */ type UnifiedClient = { /** * Register a platform plugin. * * @param plugin - the platform plugin to register * @precondition plugin.name is unique across registered plugins * @postcondition plugin is available for URL matching and API calls * @idempotency Re-registering the same name overwrites the previous plugin */ register(plugin: PlatformPlugin): void; /** * Resolve a URL to content. Automatically routes to the correct plugin. * * @param url - content URL to resolve and fetch * @returns the resolved content (Broadcast, ScheduledBroadcast, or Archive) * @precondition url matches a registered plugin * @postcondition returns Content (Broadcast, ScheduledBroadcast, or Archive) * @throws PlatformNotFoundError if no plugin matches the URL */ resolve(url: string): Promise; /** * Retrieve content by platform name and ID. * * @param platform - platform name * @param id - content identifier * @returns the resolved content (Broadcast, ScheduledBroadcast, or Archive) * @precondition platform is registered * @postcondition returns Content (Broadcast, ScheduledBroadcast, or Archive) * @throws PlatformNotFoundError if platform is not registered */ getContent(platform: string, id: string): Promise; /** * List currently active broadcasts for a channel. * * @param platform - platform name * @param channelId - channel identifier * @returns active broadcasts for the channel * @precondition platform is registered * @throws PlatformNotFoundError if platform is not registered */ listBroadcasts(platform: string, channelId: string): Promise; /** * List archives for a channel with cursor-based pagination. * * @param platform - platform name * @param channelId - channel identifier * @param cursor - pagination cursor * @param pageSize - number of items per page * @param options - optional archive filter options (period, sort, videoType) * @returns paginated list of archives * @precondition platform is registered * @throws PlatformNotFoundError if platform is not registered */ listArchives(platform: string, channelId: string, cursor?: string, pageSize?: number, options?: ArchiveListOptions): Promise>; /** * Retrieve channel information. * * @param platform - platform name * @param id - channel identifier * @returns channel information * @precondition platform is registered * @throws PlatformNotFoundError if platform is not registered */ getChannel(platform: string, id: string): Promise; /** * Batch retrieve content by platform and IDs. * * @param platform - platform name * @param ids - content identifiers * @returns batch result with values and per-item errors * @precondition platform is registered * @postcondition request-level errors (rate limit, auth, network) are thrown, per-item errors go to errors map * @throws PlatformNotFoundError if platform is not registered */ batchGetContents(platform: string, ids: string[]): Promise>; /** * Batch retrieve broadcasts by platform and channel IDs. * * @param platform - platform name * @param channelIds - channel identifiers * @returns batch result with values (Broadcast[] per channel) and per-item errors * @precondition platform is registered * @postcondition request-level errors (rate limit, auth, network) are thrown, per-item errors go to errors map * @throws PlatformNotFoundError if platform is not registered */ batchGetBroadcasts(platform: string, channelIds: string[]): Promise>; /** * Search content on a platform. At least one of query/status/channelId required. * * @param platform - platform name * @param options - search options (query, status, channelId, order, limit, cursor) * @returns paginated search results * @precondition platform is registered and supports search * @precondition at least one of options.query, options.status, or options.channelId is provided * @throws PlatformNotFoundError if platform is not registered * @throws ValidationError if no query, status, or channelId provided, or platform doesn't support search */ search(platform: string, options: SearchOptions): Promise>; /** * List clips for a channel on a platform. * * @param platform - platform name * @param channelId - channel identifier * @param options - optional clip query options (date range, limit, cursor) * @returns paginated list of clips * @precondition platform is registered and supports clips * @throws PlatformNotFoundError if platform is not registered * @throws ValidationError if platform doesn't support clips */ listClips(platform: string, channelId: string, options?: ClipOptions): Promise>; /** * Batch retrieve channels by platform and IDs. * * @param platform - platform name * @param ids - channel identifiers * @returns batch result with values and per-item errors * @precondition platform is registered * @postcondition request-level errors (rate limit, auth, network) are thrown, per-item errors go to errors map * @throws PlatformNotFoundError if platform is not registered */ batchGetChannels(platform: string, ids: string[]): Promise>; /** * Batch retrieve clips by platform and IDs. * * @param platform - platform name * @param ids - clip identifiers * @returns batch result with values and per-item errors * @precondition platform is registered and supports clips * @throws PlatformNotFoundError if platform is not registered * @throws ValidationError if platform doesn't support clip retrieval by IDs */ batchGetClips(platform: string, ids: string[]): Promise>; /** * Fetch broadcasts from all specified platforms in parallel. * * @param channels - mapping of platform name to channel ID arrays * @returns mapping of platform name to batch result of broadcasts; failed platforms get empty BatchResult * @postcondition all platforms are represented in the result, even on failure * @idempotency Safe — read-only aggregation */ crossListBroadcasts(channels: Record): Promise>>; /** * Search across all registered plugins that support search. * * @param options - search options (query, status, channelId, order, limit, cursor) * @returns mapping of platform name to paginated search results; failed platforms get empty Page * @postcondition all searchable platforms are represented in the result, even on failure * @idempotency Safe — read-only aggregation */ crossSearch(options: SearchOptions): Promise>>; /** * Access a specific platform plugin. * * @param name - platform name to look up * @returns the registered platform plugin * @throws PlatformNotFoundError if platform is not registered */ platform(name: string): PlatformPlugin; /** * Parse a URL to determine which platform and resource it refers to. * No network calls. * * @param url - URL to match against registered plugins * @returns resolved URL info, or null if no plugin matches * @postcondition returns ResolvedUrl or null if no plugin matches */ match(url: string): ResolvedUrl | null; /** * Returns the names of all registered platforms. * * @returns array of platform name strings * @postcondition returns a snapshot of currently registered platform names */ platforms(): string[]; }; /** * Companion object for the UnifiedClient type. * Provides factory utility. * * @category Client * @example * ```ts * const client = UnifiedClient.create({ plugins: [twitchPlugin] }); * ``` */ declare const UnifiedClient: { /** * Creates the main SDK client that manages plugins and routes requests. * * @param options - client configuration with optional plugins * @returns a new UnifiedClient instance * @precondition none * @postcondition returns a fully functional UnifiedClient * @idempotency Not idempotent — each call creates a new client */ readonly create: (options?: UnifiedClientOptions) => UnifiedClient; /** * Type guard for UnifiedClient. * * @param value - the value to check * @returns true if value implements UnifiedClient interface * @postcondition returns true if value has all required UnifiedClient methods */ readonly is: (value: unknown) => value is UnifiedClient; }; //#endregion //#region src/rest/bucket.d.ts /** @category Plugin Development */ type TokenBucketConfig = { global: { requests: number; perMs: number; }; parseHeaders: (headers: Headers) => RateLimitInfo | undefined; platform: string; }; /** * Creates a header-driven token bucket strategy (used by Twitch, TwitCasting). * Uses lazy refill: tokens are recalculated from elapsed time on each acquire() call. * No timers, no cleanup needed. * * @param config - token bucket configuration with limits, header parser, and platform name * @returns a RateLimitStrategy backed by a token bucket * @precondition global.requests > 0 and global.perMs > 0 * @postcondition acquire() rejects with RateLimitError when no tokens are available * @idempotency Not idempotent — each acquire() consumes a token * @category Plugin Development */ declare const createTokenBucketStrategy: (config: TokenBucketConfig) => RateLimitStrategy; //#endregion //#region src/rest/quota.d.ts /** @category Plugin Development */ type QuotaBudgetConfig = { dailyLimit?: number; costMap: Record; defaultCost?: number; platform?: string; }; /** * Creates a cost-based daily quota strategy (used by YouTube). * * @param config - quota budget configuration with limits and cost map * @returns a RateLimitStrategy backed by daily quota tracking * @precondition costMap maps bucketId strings to their quota costs * @postcondition acquire() throws QuotaExhaustedError when quota is exceeded * @idempotency Not idempotent — each acquire() consumes quota * @category Plugin Development */ declare const createQuotaBudgetStrategy: (config: QuotaBudgetConfig) => RateLimitStrategy; //#endregion //#region src/result.d.ts /** @internal */ type OkResult = { val: V; err?: never; }; /** @internal */ type ErrResult = { val?: never; err: E; }; /** @internal */ type Result = OkResult | ErrResult; /** @internal */ declare function Ok(): OkResult; /** @internal */ declare function Ok(val: V): OkResult; /** * @internal * @param err - the error to wrap * @returns an ErrResult containing the error */ declare const Err: (err: E) => ErrResult; /** * Wrap a promise into a Result, catching thrown errors. * * @internal * @param p - the promise to wrap * @param errorFactory - converts caught errors into UnifiedLiveError subclasses * @returns Ok on success, Err on failure * @precondition errorFactory converts any caught Error into a UnifiedLiveError subclass * @postcondition returns Ok on success, Err on failure — never throws * @idempotency Safe — pure wrapper */ declare const wrap: (p: Promise, errorFactory: (err: Error) => E) => Promise>; /** * Unwrap a Result — returns the value or throws the error. * Use at public API boundaries to convert Result back to thrown exceptions. * * @internal * @param result - the Result to unwrap * @returns the contained value * @precondition result is a valid Result * @postcondition returns val if Ok, throws err if Err */ declare const unwrap: (result: Result) => V; //#endregion //#region src/telemetry/traces.d.ts /** * Returns the SDK tracer instance. * When no provider is passed, returns a no-op tracer with zero overhead. * Pass the global `trace` object from @opentelemetry/api for real tracing. * * @param provider - optional TracerProvider (e.g., `trace` from @opentelemetry/api) * @returns the SDK tracer instance * @precondition none * @postcondition returns a Tracer instance (possibly no-op) * @idempotency Safe — always returns the same tracer for the same provider * @category Observability */ declare const getTracer: (provider?: TracerProvider) => Tracer; /** * Standard span attribute keys used by the SDK. * * @category Observability */ declare const SpanAttributes: { readonly PLATFORM: "unified_live.platform"; readonly HTTP_METHOD: "http.request.method"; readonly URL_PATH: "url.path"; readonly HTTP_STATUS: "http.response.status_code"; readonly SERVER_ADDRESS: "server.address"; readonly SERVER_PORT: "server.port"; readonly URL_FULL: "url.full"; readonly URL_SCHEME: "url.scheme"; readonly RATE_LIMIT_REMAINING: "unified_live.rate_limit.remaining"; readonly RATE_LIMIT_LIMIT: "unified_live.rate_limit.limit"; readonly ERROR_CODE: "unified_live.error.code"; readonly ERROR_TYPE: "error.type"; readonly ERROR_HAS_CAUSE: "unified_live.error.has_cause"; readonly RETRY_COUNT: "unified_live.retry.count"; readonly OPERATION: "unified_live.operation"; readonly BATCH_SIZE: "unified_live.batch.size"; }; /** * Wrap an async operation in an OTel span with attributes and automatic error recording. * @param tracer - a valid Tracer instance (real OTel or no-op) * @param name - the span name * @param attrs - key-value attributes to set on the span * @param fn - async function to execute within the span * @returns the result of fn * @precondition tracer is a valid Tracer instance * @postcondition span is ended after fn completes or throws * @idempotency Safe — creates a new span per call * @category Observability */ declare const withSpan: (tracer: Tracer, name: string, attrs: Record, fn: () => Promise) => Promise; //#endregion //#region src/telemetry/metrics.d.ts /** * Returns the SDK meter instance. * When no provider is passed, returns a no-op meter with zero overhead. * Pass the global `metrics` object from @opentelemetry/api for real metrics. * * @param provider - optional MeterProvider (e.g., `metrics` from @opentelemetry/api) * @returns the SDK meter instance * @precondition none * @postcondition returns a Meter instance (possibly no-op) * @idempotency Safe — always returns the same meter for the same provider * @category Observability */ declare const getMeter: (provider?: MeterProvider) => Meter; /** * Standard metric names used by the SDK. * * @category Observability */ declare const MetricNames: { readonly HTTP_CLIENT_REQUEST_DURATION: "http.client.request.duration"; }; //#endregion //#region src/telemetry/logger.d.ts /** @category Observability */ type LogLevel = "debug" | "info" | "warn" | "error"; /** @category Observability */ type Logger = { log(level: LogLevel, message: string, fields?: Record): void; }; /** @category Observability */ type LoggerProvider = { getLogger(name: string): Logger; }; /** * Set or clear the global logger provider for SDK internal logging. * @param provider - the LoggerProvider to install globally, or `undefined` to clear * @precondition none * @postcondition SDK internal log calls will be routed to the provider if set, or no-op if cleared * @idempotency Safe — last call wins * @category Observability */ declare const setLoggerProvider: (provider: LoggerProvider | undefined) => void; /** * Get a logger instance. Returns no-op logger when no provider is set. * @param name - the logger name (typically the module or component name) * @returns a Logger instance (possibly no-op) * @precondition none * @postcondition returns a Logger (possibly no-op) * @idempotency Safe * @category Observability */ declare const getLogger: (name: string) => Logger; //#endregion export { Archive, type ArchiveListOptions, AuthenticationError, BatchResult, Broadcast, BroadcastSession, Channel, type ChannelRef, Clip, type ClipOptions, Content, Err, type ErrResult, ErrorCode, type ErrorContext, type KnownPlatform, type LogLevel, type Logger, type LoggerProvider, MetricNames, type NetworkCode, NetworkError, NotFoundError, Ok, type OkResult, Page, ParseError, PlatformNotFoundError, PlatformPlugin, type PluginCapabilities, type PluginDefinition, type PluginMethods, type QuotaBudgetConfig, type QuotaDetails, QuotaExhaustedError, RateLimitError, type RateLimitHandle, type RateLimitInfo, type RateLimitStatus, RateLimitStrategy, type ResolvedUrl, RestManager, type RestManagerOptions, type RestRequest, type RestResponse, type Result, type RetryConfig, ScheduledBroadcast, type SearchOptions, SpanAttributes, type Thumbnail, type TokenBucketConfig, TokenManager, UnifiedClient, type UnifiedClientOptions, UnifiedLiveError, ValidationError, classifyNetworkError, createQuotaBudgetStrategy, createRateLimitHeaderParser, createRestManager, createTokenBucketStrategy, getLogger, getMeter, getTracer, knownPlatforms, parseRetryAfter, setLoggerProvider, unwrap, withSpan, wrap }; //# sourceMappingURL=index.d.cts.map