{"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/auth/types.ts","../src/telemetry/logger.ts","../src/telemetry/otel-types.ts","../src/telemetry/traces.ts","../src/types.ts","../src/client.ts","../src/telemetry/metrics.ts","../src/rest/manager.ts","../src/plugin.ts","../src/rest/bucket.ts","../src/rest/quota.ts","../src/rest/strategy.ts","../src/rest/types.ts","../src/result.ts"],"sourcesContent":["/**\n * Hierarchical error code for all unified-live SDK errors.\n *\n * Categories: NOT_FOUND, AUTHENTICATION_*, RATE_LIMIT_*, QUOTA_*,\n * NETWORK_*, PARSE_*, VALIDATION_*, PLATFORM_*, INTERNAL.\n *\n * @category Errors\n */\nexport type ErrorCode =\n  | \"NOT_FOUND\"\n  | \"AUTHENTICATION_INVALID\"\n  | \"AUTHENTICATION_EXPIRED\"\n  | \"RATE_LIMIT_EXCEEDED\"\n  | \"QUOTA_EXHAUSTED\"\n  | \"NETWORK_TIMEOUT\"\n  | \"NETWORK_CONNECTION\"\n  | \"NETWORK_DNS\"\n  | \"NETWORK_ABORT\"\n  | \"PARSE_JSON\"\n  | \"PARSE_RESPONSE\"\n  | \"VALIDATION_INVALID_URL\"\n  | \"VALIDATION_INVALID_INPUT\"\n  | \"PLATFORM_NOT_FOUND\"\n  | \"INTERNAL\";\n\n/**\n * Companion object for the ErrorCode type.\n * Provides category helpers for error classification in monitoring and alerting.\n *\n * @example\n * ```ts\n * if (ErrorCode.isNetwork(error.code)) { ... }\n * ```\n * @category Errors\n */\nexport const ErrorCode = {\n  /**\n   * Whether the error code represents a network-level failure.\n   *\n   * @param code - the error code to check\n   * @returns true if the code is a network error\n   */\n  isNetwork: (code: ErrorCode): boolean =>\n    code === \"NETWORK_TIMEOUT\" ||\n    code === \"NETWORK_CONNECTION\" ||\n    code === \"NETWORK_DNS\" ||\n    code === \"NETWORK_ABORT\",\n\n  /**\n   * Whether the error code represents an authentication failure.\n   *\n   * @param code - the error code to check\n   * @returns true if the code is an auth error\n   */\n  isAuth: (code: ErrorCode): boolean =>\n    code === \"AUTHENTICATION_INVALID\" || code === \"AUTHENTICATION_EXPIRED\",\n\n  /**\n   * Whether the error code represents a client-side error (validation, not found).\n   *\n   * @param code - the error code to check\n   * @returns true if the code is a client error\n   */\n  isClientError: (code: ErrorCode): boolean =>\n    code === \"NOT_FOUND\" ||\n    code === \"VALIDATION_INVALID_URL\" ||\n    code === \"VALIDATION_INVALID_INPUT\" ||\n    code === \"PLATFORM_NOT_FOUND\",\n\n  /**\n   * Whether the error code represents a rate limiting issue.\n   *\n   * @param code - the error code to check\n   * @returns true if the code is a rate limit error\n   */\n  isRateLimit: (code: ErrorCode): boolean =>\n    code === \"RATE_LIMIT_EXCEEDED\" || code === \"QUOTA_EXHAUSTED\",\n} as const;\n\n/**\n * Structured metadata attached to every SDK error.\n *\n * @postcondition platform is always present\n * @category Errors\n */\nexport type ErrorContext = {\n  /** Platform name (always present). */\n  platform: string;\n  /** HTTP method if the error occurred during a request. */\n  method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n  /** Request path (e.g., \"/videos\"). */\n  path?: string;\n  /** HTTP status code from the response. */\n  status?: number;\n  /** Resource ID that was being accessed. */\n  resourceId?: string;\n};\n\n/**\n * Base error for all unified-live SDK errors.\n *\n * @precondition message is a non-empty string\n * @precondition code is a valid ErrorCode\n * @precondition context.platform is a non-empty string\n * @postcondition instanceof UnifiedLiveError === true for all SDK errors\n * @idempotency constructing with the same arguments yields equivalent errors\n * @category Errors\n */\nexport class UnifiedLiveError extends Error {\n  readonly code: ErrorCode;\n  readonly context: ErrorContext;\n\n  constructor(\n    message: string,\n    code: ErrorCode,\n    context: ErrorContext,\n    options?: { cause?: Error },\n  ) {\n    super(message, { cause: options?.cause });\n    this.name = \"UnifiedLiveError\";\n    this.code = code;\n    this.context = context;\n  }\n\n  /**\n   * Backward-compatible getter for context.platform.\n   *\n   * @returns the platform name\n   */\n  get platform(): string {\n    return this.context.platform;\n  }\n\n  get [Symbol.toStringTag](): string {\n    return this.name;\n  }\n\n  /**\n   * Structured representation for JSON.stringify and structured logging.\n   *\n   * @returns a plain object with error details including cause chain\n   * @postcondition returned object is JSON-serializable\n   */\n  toJSON(): Record<string, unknown> {\n    const serializeCause = (err: unknown, depth = 0): Record<string, unknown> | undefined => {\n      if (!(err instanceof Error) || depth > 10) return undefined;\n      return {\n        name: err.name,\n        message: err.message,\n        ...(err.cause ? { cause: serializeCause(err.cause, depth + 1) } : {}),\n      };\n    };\n\n    return {\n      name: this.name,\n      message: this.message,\n      code: this.code,\n      context: this.context,\n      ...(this.cause ? { cause: serializeCause(this.cause) } : {}),\n    };\n  }\n\n  /**\n   * Whether this error is transient and the operation may succeed on retry.\n   *\n   * @returns true for rate limits, network issues, and server errors\n   * @postcondition auth errors, not found, validation, and parse errors return false\n   */\n  get retryable(): boolean {\n    return RETRYABLE_CODES.has(this.code);\n  }\n}\n\nconst RETRYABLE_CODES: ReadonlySet<ErrorCode> = new Set<ErrorCode>([\n  \"RATE_LIMIT_EXCEEDED\",\n  \"QUOTA_EXHAUSTED\",\n  \"NETWORK_TIMEOUT\",\n  \"NETWORK_CONNECTION\",\n  \"NETWORK_DNS\",\n]);\n\n/**\n * Resource not found on platform.\n *\n * @category Errors\n */\nexport class NotFoundError extends UnifiedLiveError {\n  declare readonly code: \"NOT_FOUND\";\n\n  constructor(platform: string, resourceId: string, options?: { cause?: Error }) {\n    super(\n      `Resource \"${resourceId}\" not found on ${platform}`,\n      \"NOT_FOUND\",\n      { platform, resourceId },\n      options,\n    );\n    this.name = \"NotFoundError\";\n  }\n}\n\ntype AuthenticationCode = \"AUTHENTICATION_INVALID\" | \"AUTHENTICATION_EXPIRED\";\n\n/**\n * Credentials invalid or expired.\n *\n * @category Errors\n */\nexport class AuthenticationError extends UnifiedLiveError {\n  declare readonly code: AuthenticationCode;\n\n  constructor(\n    platform: string,\n    options?: {\n      code?: AuthenticationCode;\n      message?: string;\n      cause?: Error;\n    },\n  ) {\n    super(\n      options?.message ?? \"Authentication failed\",\n      options?.code ?? \"AUTHENTICATION_INVALID\",\n      { platform },\n      { cause: options?.cause },\n    );\n    this.name = \"AuthenticationError\";\n  }\n}\n\n/**\n * Rate limit exceeded after max retries.\n *\n * @category Errors\n */\nexport class RateLimitError extends UnifiedLiveError {\n  declare readonly code: \"RATE_LIMIT_EXCEEDED\";\n  readonly retryAfter?: number;\n\n  constructor(platform: string, options?: { retryAfter?: number; cause?: Error }) {\n    super(\n      options?.retryAfter ? `Rate limited, retry after ${options.retryAfter}s` : \"Rate limited\",\n      \"RATE_LIMIT_EXCEEDED\",\n      { platform },\n      { cause: options?.cause },\n    );\n    this.name = \"RateLimitError\";\n    this.retryAfter = options?.retryAfter;\n  }\n\n  override toJSON(): Record<string, unknown> {\n    return {\n      ...super.toJSON(),\n      retryAfter: this.retryAfter,\n    };\n  }\n}\n\n/** @category Errors */\nexport type QuotaDetails = {\n  consumed: number;\n  limit: number;\n  resetsAt: Date;\n  requestedCost: number;\n};\n\n/**\n * YouTube daily quota exhausted.\n *\n * @category Errors\n */\nexport class QuotaExhaustedError extends UnifiedLiveError {\n  declare readonly code: \"QUOTA_EXHAUSTED\";\n  readonly details: QuotaDetails;\n\n  constructor(platform: string, details: QuotaDetails, options?: { cause?: Error }) {\n    super(\n      `Quota exhausted: ${details.consumed}/${details.limit} used, resets at ${details.resetsAt.toISOString()}`,\n      \"QUOTA_EXHAUSTED\",\n      { platform },\n      options,\n    );\n    this.name = \"QuotaExhaustedError\";\n    this.details = details;\n  }\n\n  override toJSON(): Record<string, unknown> {\n    return {\n      ...super.toJSON(),\n      details: {\n        ...this.details,\n        resetsAt: this.details.resetsAt.toISOString(),\n      },\n    };\n  }\n}\n\n/** @category Errors */\nexport type NetworkCode =\n  | \"NETWORK_TIMEOUT\"\n  | \"NETWORK_CONNECTION\"\n  | \"NETWORK_DNS\"\n  | \"NETWORK_ABORT\";\n\n/**\n * Fetch-level network failure.\n *\n * @category Errors\n */\nexport class NetworkError extends UnifiedLiveError {\n  declare readonly code: NetworkCode;\n\n  constructor(\n    platform: string,\n    code: NetworkCode,\n    options?: {\n      message?: string;\n      path?: string;\n      method?: ErrorContext[\"method\"];\n      status?: number;\n      cause?: Error;\n    },\n  ) {\n    super(\n      options?.message ?? `Network error: ${code}`,\n      code,\n      { platform, path: options?.path, method: options?.method, status: options?.status },\n      { cause: options?.cause },\n    );\n    this.name = \"NetworkError\";\n  }\n}\n\ntype ParseCode = \"PARSE_JSON\" | \"PARSE_RESPONSE\";\n\n/**\n * Response parsing failure.\n *\n * @category Errors\n */\nexport class ParseError extends UnifiedLiveError {\n  declare readonly code: ParseCode;\n\n  constructor(\n    platform: string,\n    code: ParseCode,\n    options?: {\n      message?: string;\n      path?: string;\n      status?: number;\n      cause?: Error;\n    },\n  ) {\n    super(\n      options?.message ?? `Parse error: ${code}`,\n      code,\n      { platform, path: options?.path, status: options?.status },\n      { cause: options?.cause },\n    );\n    this.name = \"ParseError\";\n  }\n}\n\ntype ValidationCode = \"VALIDATION_INVALID_URL\" | \"VALIDATION_INVALID_INPUT\";\n\n/**\n * Input validation failure.\n *\n * @category Errors\n */\nexport class ValidationError extends UnifiedLiveError {\n  declare readonly code: ValidationCode;\n\n  constructor(\n    code: ValidationCode,\n    message: string,\n    options?: { platform?: string; cause?: Error },\n  ) {\n    super(message, code, { platform: options?.platform ?? \"unknown\" }, { cause: options?.cause });\n    this.name = \"ValidationError\";\n  }\n}\n\n/**\n * Platform not registered in client.\n *\n * @category Errors\n */\nexport class PlatformNotFoundError extends UnifiedLiveError {\n  declare readonly code: \"PLATFORM_NOT_FOUND\";\n\n  constructor(platform: string) {\n    super(`Platform \"${platform}\" is not registered`, \"PLATFORM_NOT_FOUND\", {\n      platform,\n    });\n    this.name = \"PlatformNotFoundError\";\n  }\n}\n\n/**\n * Classify a fetch error into a specific NetworkCode.\n *\n * @param error - the caught fetch exception\n * @returns the classified network error code\n * @precondition error is a caught fetch exception\n * @postcondition returns one of NETWORK_ABORT, NETWORK_TIMEOUT, NETWORK_DNS, NETWORK_CONNECTION\n * @idempotency same error always produces same code\n * @category Errors\n */\nexport const classifyNetworkError = (error: Error): NetworkCode => {\n  const msg = error.message.toLowerCase();\n  if (error.name === \"AbortError\" || msg.includes(\"abort\")) return \"NETWORK_ABORT\";\n  if (msg.includes(\"timeout\") || error.name === \"TimeoutError\") return \"NETWORK_TIMEOUT\";\n  if (msg.includes(\"dns\") || msg.includes(\"getaddrinfo\")) return \"NETWORK_DNS\";\n  return \"NETWORK_CONNECTION\";\n};\n","import { AuthenticationError } from \"../errors\";\n\n/**\n * Manages authentication credentials for a platform.\n *\n * @precondition An implementation must be provided per platform\n * @postcondition getAuthHeader always returns a valid Authorization header value\n * @category Plugin Development\n */\nexport type TokenManager = {\n  /** Returns a valid auth header value (e.g., \"Bearer <token>\"). */\n  getAuthHeader(): Promise<string>;\n  /** Invalidate current token (called on 401 response). */\n  invalidate(): void;\n};\n\n/**\n * Companion object for the TokenManager type.\n * Provides factory utilities for common auth patterns.\n *\n * @category Plugin Development\n * @example\n * ```ts\n * const tm = TokenManager.static(\"Bearer my-token\");\n * ```\n */\nexport const TokenManager = {\n  /**\n   * Creates a TokenManager for static credentials that never change.\n   *\n   * @param header - auth header value (e.g., \"Basic abc123\")\n   * @param platform - platform identifier for error messages\n   * @returns a TokenManager with fixed credentials\n   * @precondition header is a non-empty auth header value (e.g., \"Basic abc123\")\n   * @postcondition getAuthHeader always returns the same header\n   * @postcondition invalidate always throws AuthenticationError\n   * @idempotency Safe — no side effects\n   */\n  static(header: string, platform?: string): TokenManager {\n    return {\n      getAuthHeader: () => Promise.resolve(header),\n      invalidate() {\n        throw new AuthenticationError(platform ?? \"unknown\", {\n          code: \"AUTHENTICATION_EXPIRED\",\n          message: \"Static token invalidated. Check credentials.\",\n        });\n      },\n    };\n  },\n\n  /**\n   * Type guard for TokenManager.\n   *\n   * @param value - the value to check\n   * @returns true if value implements TokenManager interface\n   * @postcondition returns true if value has getAuthHeader and invalidate methods\n   */\n  is(value: unknown): value is TokenManager {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string | symbol, unknown>;\n    return typeof obj.getAuthHeader === \"function\" && typeof obj.invalidate === \"function\";\n  },\n} as const;\n","/** @category Observability */\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/** @category Observability */\nexport type Logger = {\n  log(level: LogLevel, message: string, fields?: Record<string, unknown>): void;\n};\n\n/** @category Observability */\nexport type LoggerProvider = {\n  getLogger(name: string): Logger;\n};\n\nlet globalLoggerProvider: LoggerProvider | undefined;\n\n/**\n * Set or clear the global logger provider for SDK internal logging.\n * @param provider - the LoggerProvider to install globally, or `undefined` to clear\n * @precondition none\n * @postcondition SDK internal log calls will be routed to the provider if set, or no-op if cleared\n * @idempotency Safe — last call wins\n * @category Observability\n */\nexport const setLoggerProvider = (provider: LoggerProvider | undefined): void => {\n  globalLoggerProvider = provider;\n};\n\n/**\n * Get a logger instance. Returns no-op logger when no provider is set.\n * @param name - the logger name (typically the module or component name)\n * @returns a Logger instance (possibly no-op)\n * @precondition none\n * @postcondition returns a Logger (possibly no-op)\n * @idempotency Safe\n * @category Observability\n */\nexport const getLogger = (name: string): Logger => {\n  if (globalLoggerProvider) return globalLoggerProvider.getLogger(name);\n  return { log: () => {} };\n};\n","/**\n * No-op OpenTelemetry implementations.\n *\n * Types are re-exported from @opentelemetry/api (type-only imports, stripped\n * at build time) so we automatically track upstream changes.\n * Only the no-op runtime stubs live here — no runtime import from\n * @opentelemetry/api exists in the production bundle.\n *\n * @module\n * @internal\n */\nimport type { Meter, MeterProvider, Span, Tracer, TracerProvider } from \"@opentelemetry/api\";\n\n// ---------------------------------------------------------------------------\n// Re-export types from @opentelemetry/api (compile-time only)\n// ---------------------------------------------------------------------------\n\nexport type { Meter, MeterProvider, Span, Tracer, TracerProvider };\n\n// ---------------------------------------------------------------------------\n// OTel spec constants (avoid importing @opentelemetry/api at runtime)\n// ---------------------------------------------------------------------------\n\n/** SpanKind.CLIENT = 2 per OTel spec */\nexport const SPAN_KIND_CLIENT = 2;\n\n/** SpanStatusCode.ERROR = 2 per OTel spec */\nexport const SPAN_STATUS_ERROR = 2;\n\n// ---------------------------------------------------------------------------\n// No-op implementations\n// ---------------------------------------------------------------------------\n\nconst noopSpan: Span = {\n  spanContext: () => ({\n    traceId: \"\",\n    spanId: \"\",\n    traceFlags: 0,\n  }),\n  setAttribute: () => noopSpan,\n  setAttributes: () => noopSpan,\n  setStatus: () => noopSpan,\n  updateName: () => noopSpan,\n  recordException: () => {},\n  addEvent: () => noopSpan,\n  addLink: () => noopSpan,\n  addLinks: () => noopSpan,\n  isRecording: () => false,\n  end: () => {},\n};\n\nconst noopTracer: Tracer = {\n  startSpan: () => noopSpan,\n  startActiveSpan: ((_name: string, ...args: unknown[]): unknown => {\n    const fn = args[args.length - 1] as (span: Span) => unknown;\n    return fn(noopSpan);\n  }) as Tracer[\"startActiveSpan\"],\n};\n\n/** @internal */\nexport const noopTracerProvider: TracerProvider = {\n  getTracer: () => noopTracer,\n};\n\nconst noop = () => {};\n\nconst noopMeter: Meter = {\n  createHistogram: () => ({ record: noop }) as ReturnType<Meter[\"createHistogram\"]>,\n  createCounter: () => ({ add: noop }) as ReturnType<Meter[\"createCounter\"]>,\n  createUpDownCounter: () => ({ add: noop }) as ReturnType<Meter[\"createUpDownCounter\"]>,\n  createGauge: () => ({ record: noop }) as ReturnType<Meter[\"createGauge\"]>,\n  createObservableGauge: () =>\n    ({ addCallback: noop, removeCallback: noop }) as ReturnType<Meter[\"createObservableGauge\"]>,\n  createObservableCounter: () =>\n    ({ addCallback: noop, removeCallback: noop }) as ReturnType<Meter[\"createObservableCounter\"]>,\n  createObservableUpDownCounter: () =>\n    ({\n      addCallback: noop,\n      removeCallback: noop,\n    }) as ReturnType<Meter[\"createObservableUpDownCounter\"]>,\n  addBatchObservableCallback: noop,\n  removeBatchObservableCallback: noop,\n};\n\n/** @internal */\nexport const noopMeterProvider: MeterProvider = {\n  getMeter: () => noopMeter,\n};\n","import type { Tracer, TracerProvider } from \"@opentelemetry/api\";\nimport { SPAN_STATUS_ERROR, noopTracerProvider } from \"./otel-types\";\n\ndeclare const __SDK_VERSION__: string;\n\nconst TRACER_NAME = \"unified-live\";\nconst TRACER_VERSION = __SDK_VERSION__;\n\n/**\n * Returns the SDK tracer instance.\n * When no provider is passed, returns a no-op tracer with zero overhead.\n * Pass the global `trace` object from @opentelemetry/api for real tracing.\n *\n * @param provider - optional TracerProvider (e.g., `trace` from @opentelemetry/api)\n * @returns the SDK tracer instance\n * @precondition none\n * @postcondition returns a Tracer instance (possibly no-op)\n * @idempotency Safe — always returns the same tracer for the same provider\n * @category Observability\n */\nexport const getTracer = (provider?: TracerProvider): Tracer => {\n  const tp = provider ?? noopTracerProvider;\n  return tp.getTracer(TRACER_NAME, TRACER_VERSION);\n};\n\n/**\n * Standard span attribute keys used by the SDK.\n *\n * @category Observability\n */\nexport const SpanAttributes = {\n  // Platform attributes\n  PLATFORM: \"unified_live.platform\",\n\n  // HTTP semantic conventions (stable)\n  HTTP_METHOD: \"http.request.method\",\n  URL_PATH: \"url.path\",\n  HTTP_STATUS: \"http.response.status_code\",\n  SERVER_ADDRESS: \"server.address\",\n  SERVER_PORT: \"server.port\",\n\n  // HTTP semantic conventions (opt-in)\n  URL_FULL: \"url.full\",\n  URL_SCHEME: \"url.scheme\",\n\n  // Rate limit attributes\n  RATE_LIMIT_REMAINING: \"unified_live.rate_limit.remaining\",\n  RATE_LIMIT_LIMIT: \"unified_live.rate_limit.limit\",\n\n  // Error attributes (namespaced to avoid OTel convention collision)\n  ERROR_CODE: \"unified_live.error.code\",\n  ERROR_TYPE: \"error.type\",\n  ERROR_HAS_CAUSE: \"unified_live.error.has_cause\",\n\n  // Retry attributes\n  RETRY_COUNT: \"unified_live.retry.count\",\n\n  // Client-level span attributes\n  OPERATION: \"unified_live.operation\",\n  BATCH_SIZE: \"unified_live.batch.size\",\n} as const;\n\n/**\n * Wrap an async operation in an OTel span with attributes and automatic error recording.\n * @param tracer - a valid Tracer instance (real OTel or no-op)\n * @param name - the span name\n * @param attrs - key-value attributes to set on the span\n * @param fn - async function to execute within the span\n * @returns the result of fn\n * @precondition tracer is a valid Tracer instance\n * @postcondition span is ended after fn completes or throws\n * @idempotency Safe — creates a new span per call\n * @category Observability\n */\nexport const withSpan = async <T>(\n  tracer: Tracer,\n  name: string,\n  attrs: Record<string, string | number | boolean>,\n  fn: () => Promise<T>,\n): Promise<T> => {\n  return tracer.startActiveSpan(name, async (span) => {\n    for (const [k, v] of Object.entries(attrs)) span.setAttribute(k, v);\n    try {\n      const result = await fn();\n      span.end();\n      return result;\n    } catch (error) {\n      span.setStatus({\n        code: SPAN_STATUS_ERROR,\n        message: error instanceof Error ? error.message : String(error),\n      });\n      span.recordException(error instanceof Error ? error : new Error(String(error)));\n      span.end();\n      throw error;\n    }\n  });\n};\n","import type { UnifiedLiveError } from \"./errors\";\n\n/**\n * Image thumbnail with URL and dimensions in pixels.\n *\n * @category Types\n */\nexport type Thumbnail = {\n  url: string;\n  width: number;\n  height: number;\n};\n\n/**\n * Lightweight channel reference embedded in content objects.\n *\n * @category Types\n */\nexport type ChannelRef = {\n  id: string;\n  name: string;\n  url: string;\n};\n\ntype ContentBase = {\n  id: string;\n  platform: string;\n  title: string;\n  description: string;\n  tags: string[];\n  url: string;\n  thumbnail: Thumbnail;\n  channel: ChannelRef;\n  sessionId?: string;\n  raw: unknown;\n  languageCode?: string;\n};\n\n/**\n * A currently-active broadcast on any supported platform.\n * Discriminated by `type: \"broadcast\"`. Use `Content.isBroadcast()` to narrow from Content.\n *\n * @category Types\n */\nexport type Broadcast = ContentBase & {\n  type: \"broadcast\";\n  viewerCount: number;\n  startedAt: Date;\n  endedAt?: Date;\n};\n\n/**\n * An archived broadcast recording on any supported platform.\n * Discriminated by `type: \"archive\"`. Use `Content.isArchive()` to narrow from Content.\n *\n * @category Types\n */\nexport type Archive = ContentBase & {\n  type: \"archive\";\n  duration: number;\n  viewCount: number;\n  publishedAt: Date;\n  startedAt?: Date;\n  endedAt?: Date;\n};\n\n/**\n * A scheduled (upcoming) broadcast on any supported platform.\n * Discriminated by `type: \"scheduled\"`. Use `Content.isScheduledBroadcast()` to narrow from Content.\n *\n * @category Types\n */\nexport type ScheduledBroadcast = ContentBase & {\n  type: \"scheduled\";\n  scheduledStartAt: Date;\n};\n\n/**\n * A short clip extracted from a broadcast or archive on any supported platform.\n * Discriminated by `type: \"clip\"`. Use `Content.isClip()` to narrow from Content.\n *\n * @category Types\n */\nexport type Clip = ContentBase & {\n  type: \"clip\";\n  duration: number;\n  viewCount: number;\n  createdAt: Date;\n  clipCreator?: { id: string; name: string };\n  embedUrl?: string;\n  vodOffset?: number;\n  isFeatured?: boolean;\n  gameId?: string;\n};\n\n/**\n * A piece of content (broadcast, archive, scheduled broadcast, or clip) on any supported platform.\n * Use `Content.isBroadcast()` / `Content.isArchive()` / `Content.isScheduledBroadcast()` / `Content.isClip()` to narrow.\n *\n * @category Types\n */\nexport type Content = Broadcast | Archive | ScheduledBroadcast | Clip;\n\n/**\n * A streaming channel or user account on any supported platform.\n *\n * @category Types\n */\nexport type Channel = {\n  id: string;\n  platform: string;\n  name: string;\n  url: string;\n  thumbnail?: Thumbnail;\n  description?: string;\n  subscriberCount?: number;\n  publishedAt?: Date;\n};\n\n/**\n * Links a broadcast to its eventual archive.\n * `contentIds` maps between the broadcast ID and archive ID.\n *\n * @category Types\n */\nexport type BroadcastSession = {\n  sessionId: string;\n  platform: string;\n  channel: ChannelRef;\n  startedAt: Date;\n  endedAt?: Date;\n  contentIds: {\n    broadcastId?: string;\n    archiveId?: string;\n  };\n};\n\n/**\n * Cursor-based pagination wrapper.\n * `hasMore` indicates whether additional pages exist.\n * Pass `cursor` to the next call to fetch the next page.\n *\n * @category Types\n */\nexport type Page<T> = {\n  items: T[];\n  cursor?: string;\n  total?: number;\n  hasMore: boolean;\n};\n\n/**\n * Companion object for the Page type.\n * Provides transformation and factory utilities.\n *\n * @example\n * ```ts\n * const mapped = Page.map(page, (item) => item.id);\n * const empty = Page.empty<Archive>();\n * ```\n * @category Types\n */\nexport const Page = {\n  /**\n   * Transform items in a page while preserving pagination metadata.\n   *\n   * @param page - the source page\n   * @param fn - mapping function applied to each item\n   * @returns a new Page with transformed items\n   * @postcondition cursor, total, and hasMore are preserved\n   * @idempotency Safe — pure function\n   */\n  map: <T, U>(page: Page<T>, fn: (item: T) => U): Page<U> => ({\n    items: page.items.map(fn),\n    cursor: page.cursor,\n    total: page.total,\n    hasMore: page.hasMore,\n  }),\n\n  /**\n   * Create an empty page with no items.\n   *\n   * @returns an empty Page with hasMore=false\n   * @idempotency Safe — pure function\n   */\n  empty: <T>(): Page<T> => ({\n    items: [],\n    hasMore: false,\n  }),\n} as const;\n\n/**\n * Result of a batch operation. Contains successful results and per-item errors.\n * Request-level errors (rate limit, auth) are thrown, not stored here.\n *\n * @category Types\n */\nexport type BatchResult<T> = {\n  readonly values: ReadonlyMap<string, T>;\n  readonly errors: ReadonlyMap<string, UnifiedLiveError>;\n};\n\n/**\n * Companion object for the BatchResult type.\n * Provides factory utilities.\n *\n * @example\n * ```ts\n * const empty = BatchResult.empty<Content>();\n * ```\n * @category Types\n */\nexport const BatchResult = {\n  /**\n   * Create an empty BatchResult with no values or errors.\n   *\n   * @returns an empty BatchResult\n   * @idempotency Safe — pure function\n   */\n  empty: <T>(): BatchResult<T> => ({\n    values: new Map(),\n    errors: new Map(),\n  }),\n} as const;\n\n/**\n * Options for search operations across platforms.\n * All fields are optional at the type level, but `UnifiedClient.search()`\n * requires at least one of `query`, `status`, or `channelId` to be provided.\n *\n * @category Types\n */\nexport type SearchOptions = {\n  query?: string;\n  status?: \"live\" | \"upcoming\" | \"ended\";\n  channelId?: string;\n  order?: \"relevance\" | \"date\" | \"rating\" | \"title\" | \"videoCount\" | \"viewCount\";\n  limit?: number;\n  cursor?: string;\n  safeSearch?: \"moderate\" | \"none\" | \"strict\";\n  languageCode?: string;\n};\n\n/**\n * Options for archive listing operations.\n *\n * @category Types\n */\nexport type ArchiveListOptions = {\n  period?: \"all\" | \"day\" | \"week\" | \"month\";\n  sort?: \"time\" | \"trending\" | \"views\";\n  videoType?: string;\n};\n\n/**\n * Options for clip retrieval operations.\n *\n * @category Types\n */\nexport type ClipOptions = {\n  startedAt?: Date;\n  endedAt?: Date;\n  limit?: number;\n  cursor?: string;\n  isFeatured?: boolean;\n};\n\n/**\n * Known supported platform identifiers.\n *\n * @category Types\n */\nexport const knownPlatforms = [\"youtube\", \"twitch\", \"twitcasting\"] as const;\n\n/**\n * A known supported platform identifier.\n *\n * @category Types\n */\nexport type KnownPlatform = (typeof knownPlatforms)[number];\n\n/**\n * Result of resolving a platform URL without network calls.\n * Contains detected platform, resource type, and platform-specific ID.\n *\n * @category Types\n */\nexport type ResolvedUrl = {\n  platform: string;\n  type: \"content\" | \"channel\";\n  id: string;\n};\n\n/**\n * Companion object for the Broadcast type.\n * Provides lightweight structural type guard.\n *\n * @example\n * ```ts\n * if (Broadcast.is(value)) { ... }\n * ```\n * @category Types\n */\nexport const Broadcast = {\n  /**\n   * Structural type guard for Broadcast.\n   *\n   * @param value - the value to check\n   * @returns true if value has the Broadcast shape (type === \"broadcast\")\n   */\n  is: (value: unknown): value is Broadcast => {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string, unknown>;\n    return (\n      obj.type === \"broadcast\" && typeof obj.id === \"string\" && typeof obj.platform === \"string\"\n    );\n  },\n} as const;\n\n/**\n * Companion object for the ScheduledBroadcast type.\n * Provides lightweight structural type guard.\n *\n * @example\n * ```ts\n * if (ScheduledBroadcast.is(value)) { ... }\n * ```\n * @category Types\n */\nexport const ScheduledBroadcast = {\n  /**\n   * Structural type guard for ScheduledBroadcast.\n   *\n   * @param value - the value to check\n   * @returns true if value has the ScheduledBroadcast shape (type === \"scheduled\")\n   */\n  is: (value: unknown): value is ScheduledBroadcast => {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string, unknown>;\n    return (\n      obj.type === \"scheduled\" && typeof obj.id === \"string\" && typeof obj.platform === \"string\"\n    );\n  },\n} as const;\n\n/**\n * Companion object for the Archive type.\n * Provides lightweight structural type guard.\n *\n * @example\n * ```ts\n * if (Archive.is(value)) { ... }\n * ```\n * @category Types\n */\nexport const Archive = {\n  /**\n   * Structural type guard for Archive.\n   *\n   * @param value - the value to check\n   * @returns true if value has the Archive shape (type === \"archive\")\n   */\n  is: (value: unknown): value is Archive => {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string, unknown>;\n    return obj.type === \"archive\" && typeof obj.id === \"string\" && typeof obj.platform === \"string\";\n  },\n} as const;\n\n/**\n * Companion object for the Channel type.\n * Provides lightweight structural type guard.\n *\n * @example\n * ```ts\n * if (Channel.is(value)) { ... }\n * ```\n * @category Types\n */\nexport const Channel = {\n  /**\n   * Structural type guard for Channel.\n   *\n   * @param value - the value to check\n   * @returns true if value has the Channel shape\n   */\n  is: (value: unknown): value is Channel => {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string, unknown>;\n    return (\n      typeof obj.id === \"string\" && typeof obj.platform === \"string\" && typeof obj.name === \"string\"\n    );\n  },\n} as const;\n\n/**\n * Companion object for the Clip type.\n * Provides lightweight structural type guard.\n *\n * @example\n * ```ts\n * if (Clip.is(value)) { ... }\n * ```\n * @category Types\n */\nexport const Clip = {\n  /**\n   * Structural type guard for Clip.\n   *\n   * @param value - the value to check\n   * @returns true if value has the Clip shape (type === \"clip\")\n   */\n  is: (value: unknown): value is Clip => {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string, unknown>;\n    return obj.type === \"clip\" && typeof obj.id === \"string\" && typeof obj.platform === \"string\";\n  },\n} as const;\n\n/**\n * Companion object for the BroadcastSession type.\n * Provides lightweight structural type guard.\n *\n * @example\n * ```ts\n * if (BroadcastSession.is(value)) { ... }\n * ```\n * @category Types\n */\nexport const BroadcastSession = {\n  /**\n   * Structural type guard for BroadcastSession.\n   *\n   * @param value - the value to check\n   * @returns true if value has the BroadcastSession shape\n   */\n  is: (value: unknown): value is BroadcastSession => {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string, unknown>;\n    return typeof obj.sessionId === \"string\" && typeof obj.platform === \"string\";\n  },\n} as const;\n\n/**\n * Type guard namespace for Content discriminated union.\n *\n * @precondition content must be a valid Content value\n * @postcondition narrows to Broadcast, Archive, ScheduledBroadcast, or Clip\n * @category Types\n */\nexport const Content = {\n  isBroadcast: (content: Content): content is Broadcast => content.type === \"broadcast\",\n  isScheduledBroadcast: (content: Content): content is ScheduledBroadcast =>\n    content.type === \"scheduled\",\n  isArchive: (content: Content): content is Archive => content.type === \"archive\",\n  isClip: (content: Content): content is Clip => content.type === \"clip\",\n} as const;\n","import type { TracerProvider } from \"@opentelemetry/api\";\nimport {\n  AuthenticationError,\n  NetworkError,\n  PlatformNotFoundError,\n  QuotaExhaustedError,\n  RateLimitError,\n  UnifiedLiveError,\n  ValidationError,\n} from \"./errors\";\nimport type { PlatformPlugin } from \"./plugin\";\nimport { getLogger } from \"./telemetry/logger\";\nimport { getTracer, SpanAttributes, withSpan } from \"./telemetry/traces\";\nimport { BatchResult, Page } from \"./types\";\nimport type {\n  Archive,\n  ArchiveListOptions,\n  Broadcast,\n  Channel,\n  Clip,\n  ClipOptions,\n  Content,\n  ResolvedUrl,\n  SearchOptions,\n} from \"./types\";\n\n/** @category Client */\nexport type UnifiedClientOptions = {\n  plugins?: PlatformPlugin[];\n  tracerProvider?: TracerProvider;\n};\n\n/** @category Client */\nexport type UnifiedClient = {\n  /**\n   * Register a platform plugin.\n   *\n   * @param plugin - the platform plugin to register\n   * @precondition plugin.name is unique across registered plugins\n   * @postcondition plugin is available for URL matching and API calls\n   * @idempotency Re-registering the same name overwrites the previous plugin\n   */\n  register(plugin: PlatformPlugin): void;\n\n  /**\n   * Resolve a URL to content. Automatically routes to the correct plugin.\n   *\n   * @param url - content URL to resolve and fetch\n   * @returns the resolved content (Broadcast, ScheduledBroadcast, or Archive)\n   * @precondition url matches a registered plugin\n   * @postcondition returns Content (Broadcast, ScheduledBroadcast, or Archive)\n   * @throws PlatformNotFoundError if no plugin matches the URL\n   */\n  resolve(url: string): Promise<Content>;\n\n  /**\n   * Retrieve content by platform name and ID.\n   *\n   * @param platform - platform name\n   * @param id - content identifier\n   * @returns the resolved content (Broadcast, ScheduledBroadcast, or Archive)\n   * @precondition platform is registered\n   * @postcondition returns Content (Broadcast, ScheduledBroadcast, or Archive)\n   * @throws PlatformNotFoundError if platform is not registered\n   */\n  getContent(platform: string, id: string): Promise<Content>;\n\n  /**\n   * List currently active broadcasts for a channel.\n   *\n   * @param platform - platform name\n   * @param channelId - channel identifier\n   * @returns active broadcasts for the channel\n   * @precondition platform is registered\n   * @throws PlatformNotFoundError if platform is not registered\n   */\n  listBroadcasts(platform: string, channelId: string): Promise<Broadcast[]>;\n\n  /**\n   * List archives for a channel with cursor-based pagination.\n   *\n   * @param platform - platform name\n   * @param channelId - channel identifier\n   * @param cursor - pagination cursor\n   * @param pageSize - number of items per page\n   * @param options - optional archive filter options (period, sort, videoType)\n   * @returns paginated list of archives\n   * @precondition platform is registered\n   * @throws PlatformNotFoundError if platform is not registered\n   */\n  listArchives(\n    platform: string,\n    channelId: string,\n    cursor?: string,\n    pageSize?: number,\n    options?: ArchiveListOptions,\n  ): Promise<Page<Archive>>;\n\n  /**\n   * Retrieve channel information.\n   *\n   * @param platform - platform name\n   * @param id - channel identifier\n   * @returns channel information\n   * @precondition platform is registered\n   * @throws PlatformNotFoundError if platform is not registered\n   */\n  getChannel(platform: string, id: string): Promise<Channel>;\n\n  /**\n   * Batch retrieve content by platform and IDs.\n   *\n   * @param platform - platform name\n   * @param ids - content identifiers\n   * @returns batch result with values and per-item errors\n   * @precondition platform is registered\n   * @postcondition request-level errors (rate limit, auth, network) are thrown, per-item errors go to errors map\n   * @throws PlatformNotFoundError if platform is not registered\n   */\n  batchGetContents(platform: string, ids: string[]): Promise<BatchResult<Content>>;\n\n  /**\n   * Batch retrieve broadcasts by platform and channel IDs.\n   *\n   * @param platform - platform name\n   * @param channelIds - channel identifiers\n   * @returns batch result with values (Broadcast[] per channel) and per-item errors\n   * @precondition platform is registered\n   * @postcondition request-level errors (rate limit, auth, network) are thrown, per-item errors go to errors map\n   * @throws PlatformNotFoundError if platform is not registered\n   */\n  batchGetBroadcasts(platform: string, channelIds: string[]): Promise<BatchResult<Broadcast[]>>;\n\n  /**\n   * Search content on a platform. At least one of query/status/channelId required.\n   *\n   * @param platform - platform name\n   * @param options - search options (query, status, channelId, order, limit, cursor)\n   * @returns paginated search results\n   * @precondition platform is registered and supports search\n   * @precondition at least one of options.query, options.status, or options.channelId is provided\n   * @throws PlatformNotFoundError if platform is not registered\n   * @throws ValidationError if no query, status, or channelId provided, or platform doesn't support search\n   */\n  search(platform: string, options: SearchOptions): Promise<Page<Content>>;\n\n  /**\n   * List clips for a channel on a platform.\n   *\n   * @param platform - platform name\n   * @param channelId - channel identifier\n   * @param options - optional clip query options (date range, limit, cursor)\n   * @returns paginated list of clips\n   * @precondition platform is registered and supports clips\n   * @throws PlatformNotFoundError if platform is not registered\n   * @throws ValidationError if platform doesn't support clips\n   */\n  listClips(platform: string, channelId: string, options?: ClipOptions): Promise<Page<Clip>>;\n\n  /**\n   * Batch retrieve channels by platform and IDs.\n   *\n   * @param platform - platform name\n   * @param ids - channel identifiers\n   * @returns batch result with values and per-item errors\n   * @precondition platform is registered\n   * @postcondition request-level errors (rate limit, auth, network) are thrown, per-item errors go to errors map\n   * @throws PlatformNotFoundError if platform is not registered\n   */\n  batchGetChannels(platform: string, ids: string[]): Promise<BatchResult<Channel>>;\n\n  /**\n   * Batch retrieve clips by platform and IDs.\n   *\n   * @param platform - platform name\n   * @param ids - clip identifiers\n   * @returns batch result with values and per-item errors\n   * @precondition platform is registered and supports clips\n   * @throws PlatformNotFoundError if platform is not registered\n   * @throws ValidationError if platform doesn't support clip retrieval by IDs\n   */\n  batchGetClips(platform: string, ids: string[]): Promise<BatchResult<Clip>>;\n\n  /**\n   * Fetch broadcasts from all specified platforms in parallel.\n   *\n   * @param channels - mapping of platform name to channel ID arrays\n   * @returns mapping of platform name to batch result of broadcasts; failed platforms get empty BatchResult\n   * @postcondition all platforms are represented in the result, even on failure\n   * @idempotency Safe — read-only aggregation\n   */\n  crossListBroadcasts(\n    channels: Record<string, string[]>,\n  ): Promise<Record<string, BatchResult<Broadcast[]>>>;\n\n  /**\n   * Search across all registered plugins that support search.\n   *\n   * @param options - search options (query, status, channelId, order, limit, cursor)\n   * @returns mapping of platform name to paginated search results; failed platforms get empty Page\n   * @postcondition all searchable platforms are represented in the result, even on failure\n   * @idempotency Safe — read-only aggregation\n   */\n  crossSearch(options: SearchOptions): Promise<Record<string, Page<Content>>>;\n\n  /**\n   * Access a specific platform plugin.\n   *\n   * @param name - platform name to look up\n   * @returns the registered platform plugin\n   * @throws PlatformNotFoundError if platform is not registered\n   */\n  platform(name: string): PlatformPlugin;\n\n  /**\n   * Parse a URL to determine which platform and resource it refers to.\n   * No network calls.\n   *\n   * @param url - URL to match against registered plugins\n   * @returns resolved URL info, or null if no plugin matches\n   * @postcondition returns ResolvedUrl or null if no plugin matches\n   */\n  match(url: string): ResolvedUrl | null;\n\n  /**\n   * Returns the names of all registered platforms.\n   *\n   * @returns array of platform name strings\n   * @postcondition returns a snapshot of currently registered platform names\n   */\n  platforms(): string[];\n};\n\n/**\n * Companion object for the UnifiedClient type.\n * Provides factory utility.\n *\n * @category Client\n * @example\n * ```ts\n * const client = UnifiedClient.create({ plugins: [twitchPlugin] });\n * ```\n */\nexport const UnifiedClient = {\n  /**\n   * Creates the main SDK client that manages plugins and routes requests.\n   *\n   * @param options - client configuration with optional plugins\n   * @returns a new UnifiedClient instance\n   * @precondition none\n   * @postcondition returns a fully functional UnifiedClient\n   * @idempotency Not idempotent — each call creates a new client\n   */\n  create(options?: UnifiedClientOptions): UnifiedClient {\n    const plugins = new Map<string, PlatformPlugin>();\n    const tracer = getTracer(options?.tracerProvider);\n\n    if (options?.plugins) {\n      for (const plugin of options.plugins) {\n        plugins.set(plugin.name, plugin);\n      }\n    }\n\n    const getPlugin = (name: string): PlatformPlugin => {\n      const plugin = plugins.get(name);\n      if (!plugin) {\n        throw new PlatformNotFoundError(name);\n      }\n      return plugin;\n    };\n\n    const isRequestLevelError = (error: unknown): boolean => {\n      if (error instanceof RateLimitError) return true;\n      if (error instanceof QuotaExhaustedError) return true;\n      if (error instanceof AuthenticationError) return true;\n      if (error instanceof NetworkError) return true;\n      return false;\n    };\n\n    const batchFallback = async <T>(\n      fn: (id: string) => Promise<T>,\n      ids: string[],\n      platform: string,\n    ): Promise<BatchResult<T>> => {\n      const CONCURRENCY = 10;\n      const values = new Map<string, T>();\n      const errors = new Map<string, UnifiedLiveError>();\n\n      for (let i = 0; i < ids.length; i += CONCURRENCY) {\n        const chunk = ids.slice(i, i + CONCURRENCY);\n        const settled = await Promise.allSettled(\n          chunk.map(async (id) => ({ id, value: await fn(id) })),\n        );\n        for (const [j, result] of settled.entries()) {\n          if (result.status === \"fulfilled\") {\n            values.set(result.value.id, result.value.value);\n          } else {\n            if (isRequestLevelError(result.reason)) throw result.reason;\n            const id = chunk[j] as string;\n            errors.set(\n              id,\n              result.reason instanceof UnifiedLiveError\n                ? result.reason\n                : new UnifiedLiveError(result.reason?.message ?? \"Unknown error\", \"INTERNAL\", {\n                    platform,\n                    resourceId: id,\n                  }),\n            );\n          }\n        }\n      }\n\n      return { values, errors };\n    };\n\n    const matchUrl = (url: string): ResolvedUrl | null => {\n      for (const plugin of plugins.values()) {\n        const resolved = plugin.match(url);\n        if (resolved) {\n          return resolved;\n        }\n      }\n      return null;\n    };\n\n    const withClientSpan = async <T>(\n      operationName: string,\n      attrs: Record<string, string | number>,\n      fn: () => Promise<T>,\n    ): Promise<T> => {\n      return withSpan(\n        tracer,\n        `unified-live.client ${operationName}`,\n        {\n          [SpanAttributes.OPERATION]: operationName,\n          ...attrs,\n        },\n        fn,\n      );\n    };\n\n    const client: UnifiedClient = {\n      register(plugin: PlatformPlugin): void {\n        plugins.set(plugin.name, plugin);\n      },\n\n      async resolve(url: string): Promise<Content> {\n        if (!url) {\n          throw new ValidationError(\"VALIDATION_INVALID_INPUT\", \"URL must be a non-empty string\");\n        }\n        const resolved = matchUrl(url);\n        if (!resolved) {\n          throw new ValidationError(\n            \"VALIDATION_INVALID_URL\",\n            `No registered plugin matches URL: \"${url}\"`,\n          );\n        }\n        return withClientSpan(\"resolve\", { [SpanAttributes.PLATFORM]: resolved.platform }, () => {\n          const plugin = getPlugin(resolved.platform);\n          return plugin.getContent(resolved.id);\n        });\n      },\n\n      async getContent(platform: string, id: string): Promise<Content> {\n        return withClientSpan(\"getContent\", { [SpanAttributes.PLATFORM]: platform }, () => {\n          const plugin = getPlugin(platform);\n          return plugin.getContent(id);\n        });\n      },\n\n      async listBroadcasts(platform: string, channelId: string): Promise<Broadcast[]> {\n        return withClientSpan(\"listBroadcasts\", { [SpanAttributes.PLATFORM]: platform }, () => {\n          const plugin = getPlugin(platform);\n          return plugin.listBroadcasts(channelId);\n        });\n      },\n\n      async listArchives(\n        platform: string,\n        channelId: string,\n        cursor?: string,\n        pageSize?: number,\n        options?: ArchiveListOptions,\n      ): Promise<Page<Archive>> {\n        return withClientSpan(\"listArchives\", { [SpanAttributes.PLATFORM]: platform }, () => {\n          const plugin = getPlugin(platform);\n          return plugin.listArchives(channelId, cursor, pageSize, options);\n        });\n      },\n\n      async getChannel(platform: string, id: string): Promise<Channel> {\n        return withClientSpan(\"getChannel\", { [SpanAttributes.PLATFORM]: platform }, () => {\n          const plugin = getPlugin(platform);\n          return plugin.getChannel(id);\n        });\n      },\n\n      async batchGetContents(platform: string, ids: string[]): Promise<BatchResult<Content>> {\n        if (ids.length === 0) return BatchResult.empty();\n        return withClientSpan(\n          \"batchGetContents\",\n          {\n            [SpanAttributes.PLATFORM]: platform,\n            [SpanAttributes.BATCH_SIZE]: ids.length,\n          },\n          () => {\n            const plugin = getPlugin(platform);\n            const uniqueIds = [...new Set(ids)];\n            if (plugin.batchGetContents) {\n              return plugin.batchGetContents(uniqueIds);\n            }\n            return batchFallback((id) => plugin.getContent(id), uniqueIds, platform);\n          },\n        );\n      },\n\n      async batchGetBroadcasts(\n        platform: string,\n        channelIds: string[],\n      ): Promise<BatchResult<Broadcast[]>> {\n        if (channelIds.length === 0) return BatchResult.empty();\n        return withClientSpan(\n          \"batchGetBroadcasts\",\n          {\n            [SpanAttributes.PLATFORM]: platform,\n            [SpanAttributes.BATCH_SIZE]: channelIds.length,\n          },\n          () => {\n            const plugin = getPlugin(platform);\n            const uniqueIds = [...new Set(channelIds)];\n            if (plugin.batchGetBroadcasts) {\n              return plugin.batchGetBroadcasts(uniqueIds);\n            }\n            return batchFallback((id) => plugin.listBroadcasts(id), uniqueIds, platform);\n          },\n        );\n      },\n\n      async search(platform: string, searchOptions: SearchOptions): Promise<Page<Content>> {\n        return withClientSpan(\"search\", { [SpanAttributes.PLATFORM]: platform }, () => {\n          const plugin = getPlugin(platform);\n          if (!searchOptions.query && !searchOptions.status && !searchOptions.channelId) {\n            throw new ValidationError(\n              \"VALIDATION_INVALID_INPUT\",\n              \"search requires at least one of 'query', 'status', or 'channelId'\",\n            );\n          }\n          if (!plugin.search) {\n            throw new ValidationError(\n              \"VALIDATION_INVALID_INPUT\",\n              `Platform '${platform}' does not support search`,\n            );\n          }\n          return plugin.search(searchOptions);\n        });\n      },\n\n      async listClips(\n        platform: string,\n        channelId: string,\n        options?: ClipOptions,\n      ): Promise<Page<Clip>> {\n        return withClientSpan(\"listClips\", { [SpanAttributes.PLATFORM]: platform }, () => {\n          const plugin = getPlugin(platform);\n          if (!plugin.listClips) {\n            throw new ValidationError(\n              \"VALIDATION_INVALID_INPUT\",\n              `Platform '${platform}' does not support clips`,\n            );\n          }\n          return plugin.listClips(channelId, options);\n        });\n      },\n\n      async batchGetChannels(platform: string, ids: string[]): Promise<BatchResult<Channel>> {\n        if (ids.length === 0) return BatchResult.empty();\n        return withClientSpan(\n          \"batchGetChannels\",\n          {\n            [SpanAttributes.PLATFORM]: platform,\n            [SpanAttributes.BATCH_SIZE]: ids.length,\n          },\n          () => {\n            const plugin = getPlugin(platform);\n            const uniqueIds = [...new Set(ids)];\n            if (plugin.batchGetChannels) {\n              return plugin.batchGetChannels(uniqueIds);\n            }\n            return batchFallback((id) => plugin.getChannel(id), uniqueIds, platform);\n          },\n        );\n      },\n\n      async batchGetClips(platform: string, ids: string[]): Promise<BatchResult<Clip>> {\n        if (ids.length === 0) return BatchResult.empty();\n        return withClientSpan(\n          \"batchGetClips\",\n          {\n            [SpanAttributes.PLATFORM]: platform,\n            [SpanAttributes.BATCH_SIZE]: ids.length,\n          },\n          () => {\n            const plugin = getPlugin(platform);\n            if (!plugin.batchGetClips) {\n              throw new ValidationError(\n                \"VALIDATION_INVALID_INPUT\",\n                `Platform '${platform}' does not support clip retrieval by IDs`,\n              );\n            }\n            const uniqueIds = [...new Set(ids)];\n            return plugin.batchGetClips(uniqueIds);\n          },\n        );\n      },\n\n      async crossListBroadcasts(\n        channels: Record<string, string[]>,\n      ): Promise<Record<string, BatchResult<Broadcast[]>>> {\n        return withClientSpan(\"crossListBroadcasts\", {}, async () => {\n          const entries = Object.entries(channels);\n          const settled = await Promise.allSettled(\n            entries.map(async ([platform, ids]) => ({\n              platform,\n              result: await client.batchGetBroadcasts(platform, ids),\n            })),\n          );\n          const out: Record<string, BatchResult<Broadcast[]>> = {};\n          for (const [i, s] of settled.entries()) {\n            if (s.status === \"fulfilled\") {\n              out[s.value.platform] = s.value.result;\n            } else {\n              out[entries[i]![0]] = BatchResult.empty();\n            }\n          }\n          return out;\n        });\n      },\n\n      async crossSearch(searchOptions: SearchOptions): Promise<Record<string, Page<Content>>> {\n        return withClientSpan(\"crossSearch\", {}, async () => {\n          if (!searchOptions.query && !searchOptions.status && !searchOptions.channelId) {\n            throw new ValidationError(\n              \"VALIDATION_INVALID_INPUT\",\n              \"crossSearch requires at least one of 'query', 'status', or 'channelId'\",\n            );\n          }\n          const searchablePlugins = [...plugins.entries()].filter(\n            ([, p]) => p.capabilities.supportsSearch && p.search,\n          );\n          const settled = await Promise.allSettled(\n            searchablePlugins.map(async ([name, p]) => ({\n              name,\n              result: await p.search!(searchOptions),\n            })),\n          );\n          const logger = getLogger(\"unified-live.client\");\n          const out: Record<string, Page<Content>> = {};\n          for (const [i, s] of settled.entries()) {\n            if (s.status === \"fulfilled\") {\n              out[s.value.name] = s.value.result;\n            } else {\n              const name = searchablePlugins[i]![0];\n              logger.log(\"warn\", `crossSearch failed for platform ${name}`, { error: s.reason });\n              out[name] = Page.empty();\n            }\n          }\n          return out;\n        });\n      },\n\n      platform(name: string): PlatformPlugin {\n        return getPlugin(name);\n      },\n\n      match(url: string): ResolvedUrl | null {\n        return matchUrl(url);\n      },\n\n      /**\n       * Returns the names of all registered platforms.\n       *\n       * @returns array of platform name strings\n       */\n      platforms(): string[] {\n        return [...plugins.keys()];\n      },\n    };\n\n    return client;\n  },\n\n  /**\n   * Type guard for UnifiedClient.\n   *\n   * @param value - the value to check\n   * @returns true if value implements UnifiedClient interface\n   * @postcondition returns true if value has all required UnifiedClient methods\n   */\n  is(value: unknown): value is UnifiedClient {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string | symbol, unknown>;\n    return (\n      typeof obj.register === \"function\" &&\n      typeof obj.resolve === \"function\" &&\n      typeof obj.getContent === \"function\" &&\n      typeof obj.listBroadcasts === \"function\" &&\n      typeof obj.listArchives === \"function\" &&\n      typeof obj.getChannel === \"function\" &&\n      typeof obj.batchGetContents === \"function\" &&\n      typeof obj.batchGetBroadcasts === \"function\" &&\n      typeof obj.batchGetChannels === \"function\" &&\n      typeof obj.search === \"function\" &&\n      typeof obj.listClips === \"function\" &&\n      typeof obj.batchGetClips === \"function\" &&\n      typeof obj.crossListBroadcasts === \"function\" &&\n      typeof obj.crossSearch === \"function\" &&\n      typeof obj.platform === \"function\" &&\n      typeof obj.match === \"function\" &&\n      typeof obj.platforms === \"function\"\n    );\n  },\n} as const;\n","import type { Meter, MeterProvider } from \"@opentelemetry/api\";\nimport { noopMeterProvider } from \"./otel-types\";\n\ndeclare const __SDK_VERSION__: string;\n\nconst METER_NAME = \"unified-live\";\nconst METER_VERSION = __SDK_VERSION__;\n\n/**\n * Returns the SDK meter instance.\n * When no provider is passed, returns a no-op meter with zero overhead.\n * Pass the global `metrics` object from @opentelemetry/api for real metrics.\n *\n * @param provider - optional MeterProvider (e.g., `metrics` from @opentelemetry/api)\n * @returns the SDK meter instance\n * @precondition none\n * @postcondition returns a Meter instance (possibly no-op)\n * @idempotency Safe — always returns the same meter for the same provider\n * @category Observability\n */\nexport const getMeter = (provider?: MeterProvider): Meter => {\n  const mp = provider ?? noopMeterProvider;\n  return mp.getMeter(METER_NAME, METER_VERSION);\n};\n\n/**\n * Standard metric names used by the SDK.\n *\n * @category Observability\n */\nexport const MetricNames = {\n  HTTP_CLIENT_REQUEST_DURATION: \"http.client.request.duration\",\n} as const;\n","import type { TokenManager } from \"../auth/types\";\nimport {\n  AuthenticationError,\n  classifyNetworkError,\n  NetworkError,\n  NotFoundError,\n  ParseError,\n  RateLimitError,\n  UnifiedLiveError,\n} from \"../errors\";\nimport { SPAN_KIND_CLIENT, SPAN_STATUS_ERROR } from \"../telemetry/otel-types\";\nimport { getMeter, MetricNames } from \"../telemetry/metrics\";\nimport { getTracer, SpanAttributes } from \"../telemetry/traces\";\nimport type { RateLimitStrategy } from \"./strategy\";\nimport type { RateLimitInfo, RestManagerOptions, RestRequest, RestResponse } from \"./types\";\n\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_BASE_DELAY = 1000;\nconst DEFAULT_RETRYABLE_STATUSES: ReadonlySet<number> = new Set([500, 502, 503, 504]);\n/** Client errors that should never be retried (408 is server-initiated timeout, not transient). */\nconst NON_RETRYABLE_CLIENT_STATUSES: ReadonlySet<number> = new Set([400, 408, 413, 415, 422]);\n\n/** @category Plugin Development */\nexport type RestManager = {\n  readonly platform: string;\n  readonly baseUrl: string;\n  readonly rateLimitStrategy: RateLimitStrategy;\n  readonly tokenManager: TokenManager | undefined;\n\n  /**\n   * Execute a full request lifecycle: rate limit → headers → fetch → retry → parse.\n   *\n   * @precondition rateLimitStrategy is initialized\n   * @postcondition returns parsed response or throws an error from the hierarchy\n   */\n  request: <T>(req: RestRequest) => Promise<RestResponse<T>>;\n\n  /**\n   * Build auth + custom headers for a request. Override to inject platform-specific headers.\n   *\n   * @precondition tokenManager (if set) is ready to provide auth headers\n   * @postcondition returns a headers record including Authorization if tokenManager is set\n   */\n  createHeaders: (req: RestRequest) => Promise<Record<string, string>>;\n\n  /**\n   * Execute a single fetch call. Override to add logging, metrics, or custom transport.\n   *\n   * @precondition url is a fully-qualified URL\n   * @postcondition returns the raw Response from the server\n   */\n  runRequest: (url: string, init: RequestInit) => Promise<Response>;\n\n  /**\n   * Parse the response body as JSON and construct a RestResponse.\n   * Throws UnifiedLiveError if the response is not valid JSON.\n   *\n   * @precondition response.ok or a handled status code\n   * @postcondition returns a RestResponse with parsed data and optional rate limit info\n   */\n  handleResponse: <T>(response: Response, req: RestRequest) => Promise<RestResponse<T>>;\n\n  /**\n   * Handle rate-limited responses (429, 403). Return true to retry.\n   * Override for platform-specific quota/rate limit detection.\n   *\n   * @precondition response has status 429 or 403\n   * @postcondition returns true if the request should be retried, false otherwise\n   */\n  handleRateLimit: (response: Response, req: RestRequest, attempt: number) => Promise<boolean>;\n\n  /**\n   * Extract rate limit info from response headers. Override per platform.\n   * Default returns undefined (no parsing).\n   *\n   * @postcondition returns RateLimitInfo if headers contain rate limit data, undefined otherwise\n   */\n  parseRateLimitHeaders: (headers: Headers) => RateLimitInfo | undefined;\n};\n\n/**\n * Creates a discordeno-style RestManager with overridable function properties.\n *\n * @param options - REST manager configuration\n * @returns a new RestManager instance\n * @precondition options.rateLimitStrategy is initialized\n * @postcondition returns a RestManager with all methods set\n * @idempotency Not idempotent — each call creates a new manager instance\n * @category Plugin Development\n */\nexport const createRestManager = (options: RestManagerOptions): RestManager => {\n  const maxRetries = options.retry?.maxRetries ?? DEFAULT_MAX_RETRIES;\n  const baseDelay = options.retry?.baseDelay ?? DEFAULT_BASE_DELAY;\n  const retryableStatuses: ReadonlySet<number> = options.retry?.retryableStatuses\n    ? new Set(options.retry.retryableStatuses)\n    : DEFAULT_RETRYABLE_STATUSES;\n  const timeout = options.retry?.timeout;\n  const fetchFn = options.fetch ?? globalThis.fetch;\n  const tracer = getTracer(options.tracerProvider);\n  const meter = getMeter(options.meterProvider);\n  const requestDuration = meter.createHistogram(MetricNames.HTTP_CLIENT_REQUEST_DURATION, {\n    description: \"Duration of HTTP client requests\",\n    unit: \"s\",\n  });\n  // Cache parsed base URL components for OTel attributes (avoids parsing on every request)\n  let cachedUrl: { hostname: string; port: number; scheme: string } | undefined;\n  try {\n    const parsed = new URL(options.baseUrl);\n    const scheme = parsed.protocol.replace(\":\", \"\");\n    cachedUrl = {\n      hostname: parsed.hostname,\n      port: parsed.port ? Number.parseInt(parsed.port, 10) : scheme === \"https\" ? 443 : 80,\n      scheme,\n    };\n  } catch {\n    // ignore invalid URL\n  }\n\n  // Pre-compute base metric attributes that don't change per-request\n  const baseMetricAttrs: Record<string, string | number> = {};\n  if (cachedUrl) {\n    baseMetricAttrs[SpanAttributes.SERVER_ADDRESS] = cachedUrl.hostname;\n    baseMetricAttrs[SpanAttributes.SERVER_PORT] = cachedUrl.port;\n  }\n\n  const baseHeaders: Record<string, string> = {\n    Accept: \"application/json\",\n    ...options.headers,\n  };\n\n  const manager: RestManager = {\n    platform: options.platform,\n    baseUrl: options.baseUrl,\n    rateLimitStrategy: options.rateLimitStrategy,\n    tokenManager: options.tokenManager,\n\n    request: async <T>(req: RestRequest): Promise<RestResponse<T>> => {\n      return tracer.startActiveSpan(req.method, { kind: SPAN_KIND_CLIENT }, async (span) => {\n        span.setAttribute(SpanAttributes.PLATFORM, manager.platform);\n        span.setAttribute(SpanAttributes.HTTP_METHOD, req.method);\n        span.setAttribute(SpanAttributes.URL_PATH, req.path);\n\n        if (cachedUrl) {\n          span.setAttribute(SpanAttributes.SERVER_ADDRESS, cachedUrl.hostname);\n          span.setAttribute(SpanAttributes.SERVER_PORT, cachedUrl.port);\n          span.setAttribute(SpanAttributes.URL_SCHEME, cachedUrl.scheme);\n        }\n\n        const handle = await manager.rateLimitStrategy.acquire(req);\n        const startTime = performance.now();\n        let lastStatusCode: number | undefined;\n\n        try {\n          // Hoist invariants out of the retry loop\n          // Ensure baseUrl path is preserved and avoid treating req.path as an absolute URL.\n          const reqUrl = new URL(manager.baseUrl);\n          const basePath = reqUrl.pathname.endsWith(\"/\") ? reqUrl.pathname : `${reqUrl.pathname}/`;\n          const relativePath = req.path.startsWith(\"/\") ? req.path.slice(1) : req.path;\n          reqUrl.pathname = `${basePath}${relativePath}`;\n          if (req.query) {\n            for (const [key, value] of Object.entries(req.query)) {\n              if (Array.isArray(value)) {\n                for (const v of value) {\n                  reqUrl.searchParams.append(key, v);\n                }\n              } else {\n                reqUrl.searchParams.set(key, value);\n              }\n            }\n          }\n          const url = reqUrl.toString();\n          span.setAttribute(SpanAttributes.URL_FULL, url);\n          const timeoutSignal = timeout && !req.signal ? AbortSignal.timeout(timeout) : undefined;\n          const signal = req.signal ?? timeoutSignal;\n          const serializedBody =\n            req.body !== undefined && req.bodyType !== \"raw\" ? JSON.stringify(req.body) : undefined;\n\n          for (let attempt = 0; attempt <= maxRetries; attempt++) {\n            const headers = await manager.createHeaders(req);\n\n            const init: RequestInit = {\n              method: req.method,\n              headers: { ...headers, ...req.headers },\n              signal,\n            };\n\n            if (req.body !== undefined) {\n              if (req.bodyType === \"raw\") {\n                init.body = req.body as RequestInit[\"body\"];\n              } else {\n                init.body = serializedBody;\n                (init.headers as Record<string, string>)[\"Content-Type\"] = \"application/json\";\n              }\n            }\n\n            let response: Response;\n            try {\n              response = await manager.runRequest(url, init);\n            } catch (e) {\n              const err = e instanceof Error ? e : new Error(String(e));\n              const code = classifyNetworkError(err);\n              throw new NetworkError(manager.platform, code, {\n                path: req.path,\n                method: req.method,\n                cause: err,\n              });\n            }\n            lastStatusCode = response.status;\n            span.setAttribute(SpanAttributes.HTTP_STATUS, response.status);\n\n            // Rate limit handling (429 or 403)\n            if (response.status === 429 || response.status === 403) {\n              const shouldRetry = await manager.handleRateLimit(response, req, attempt);\n              if (shouldRetry && attempt < maxRetries) {\n                span.addEvent(\"retry\", {\n                  \"unified_live.retry.attempt\": attempt + 1,\n                  \"unified_live.retry.reason\": \"rate_limit\",\n                  [SpanAttributes.HTTP_STATUS]: response.status,\n                });\n                continue;\n              }\n              const retryAfterSec = parseRetryAfter(response.headers.get(\"Retry-After\"));\n              throw new RateLimitError(manager.platform, {\n                retryAfter: retryAfterSec > 0 ? retryAfterSec : undefined,\n              });\n            }\n\n            // Auth error (401)\n            if (response.status === 401) {\n              manager.tokenManager?.invalidate();\n              if (attempt < maxRetries) {\n                span.addEvent(\"retry\", {\n                  \"unified_live.retry.attempt\": attempt + 1,\n                  \"unified_live.retry.reason\": \"auth_refresh\",\n                  [SpanAttributes.HTTP_STATUS]: response.status,\n                });\n                continue;\n              }\n              throw new AuthenticationError(manager.platform, {\n                code: \"AUTHENTICATION_EXPIRED\",\n              });\n            }\n\n            // Not found (404)\n            if (response.status === 404) {\n              throw new NotFoundError(manager.platform, req.path);\n            }\n\n            // Non-retryable client errors — fail immediately without retry\n            if (NON_RETRYABLE_CLIENT_STATUSES.has(response.status)) {\n              throw new UnifiedLiveError(\n                `Request to ${req.path} failed with status ${response.status}`,\n                response.status === 408 ? \"NETWORK_TIMEOUT\" : \"INTERNAL\",\n                {\n                  platform: manager.platform,\n                  method: req.method,\n                  path: req.path,\n                  status: response.status,\n                },\n              );\n            }\n\n            // Retryable server errors (5xx)\n            if (retryableStatuses.has(response.status)) {\n              if (attempt < maxRetries) {\n                const jitter = 0.5 + Math.random();\n                await sleep(baseDelay * 2 ** attempt * jitter);\n                span.addEvent(\"retry\", {\n                  \"unified_live.retry.attempt\": attempt + 1,\n                  [SpanAttributes.HTTP_STATUS]: response.status,\n                });\n                continue;\n              }\n              throw new NetworkError(manager.platform, \"NETWORK_CONNECTION\", {\n                message: `${req.method} ${req.path} failed with status ${response.status} after ${maxRetries + 1} attempts`,\n                path: req.path,\n                method: req.method,\n                status: response.status,\n              });\n            }\n\n            const result = await manager.handleResponse<T>(response, req);\n\n            if (result.rateLimit) {\n              span.setAttribute(SpanAttributes.RATE_LIMIT_REMAINING, result.rateLimit.remaining);\n              span.setAttribute(SpanAttributes.RATE_LIMIT_LIMIT, result.rateLimit.limit);\n            }\n\n            if (attempt > 0) {\n              span.setAttribute(SpanAttributes.RETRY_COUNT, attempt);\n            }\n\n            const duration = (performance.now() - startTime) / 1000;\n            requestDuration.record(duration, {\n              ...baseMetricAttrs,\n              [SpanAttributes.HTTP_METHOD]: req.method,\n              [SpanAttributes.HTTP_STATUS]: response.status,\n            });\n\n            handle.complete(response.headers);\n            span.end();\n            return result;\n          }\n\n          throw new NetworkError(manager.platform, \"NETWORK_CONNECTION\", {\n            message: `${req.method} ${req.path} failed after ${maxRetries + 1} attempts`,\n            path: req.path,\n            method: req.method,\n          });\n        } catch (error) {\n          // Per semconv: use status code string for HTTP errors, exception name otherwise\n          const errorType =\n            lastStatusCode !== undefined && lastStatusCode >= 400\n              ? String(lastStatusCode)\n              : error instanceof Error\n                ? error.name\n                : \"unknown\";\n          span.setAttribute(SpanAttributes.ERROR_TYPE, errorType);\n\n          if (error instanceof UnifiedLiveError) {\n            span.setAttribute(SpanAttributes.ERROR_CODE, error.code);\n            span.setAttribute(SpanAttributes.ERROR_HAS_CAUSE, !!error.cause);\n          }\n\n          const duration = (performance.now() - startTime) / 1000;\n          requestDuration.record(duration, {\n            ...baseMetricAttrs,\n            [SpanAttributes.HTTP_METHOD]: req.method,\n            [SpanAttributes.ERROR_TYPE]: errorType,\n            ...(lastStatusCode !== undefined && {\n              [SpanAttributes.HTTP_STATUS]: lastStatusCode,\n            }),\n          });\n\n          span.setStatus({\n            code: SPAN_STATUS_ERROR,\n            message: error instanceof Error ? error.message : String(error),\n          });\n          span.recordException(error instanceof Error ? error : new Error(String(error)));\n          handle.release();\n          span.end();\n          throw error;\n        }\n      });\n    },\n\n    createHeaders: async (_req: RestRequest): Promise<Record<string, string>> => {\n      const headers: Record<string, string> = { ...baseHeaders };\n\n      if (manager.tokenManager) {\n        headers.Authorization = await manager.tokenManager.getAuthHeader();\n      }\n\n      return headers;\n    },\n\n    runRequest: async (url: string, init: RequestInit): Promise<Response> => {\n      return fetchFn(url, init);\n    },\n\n    handleResponse: async <T>(response: Response, req: RestRequest): Promise<RestResponse<T>> => {\n      let data: T;\n      try {\n        data = (await response.json()) as T;\n      } catch (e) {\n        const err = e instanceof Error ? e : new Error(String(e));\n        throw new ParseError(manager.platform, \"PARSE_JSON\", {\n          message: `Failed to parse JSON response from ${req.path}`,\n          path: req.path,\n          status: response.status,\n          cause: err,\n        });\n      }\n      const rateLimit = manager.parseRateLimitHeaders(response.headers);\n      return {\n        status: response.status,\n        headers: response.headers,\n        data,\n        rateLimit,\n      };\n    },\n\n    handleRateLimit: async (\n      response: Response,\n      _req: RestRequest,\n      attempt: number,\n    ): Promise<boolean> => {\n      if (response.status === 429) {\n        const retryAfter = parseRetryAfter(response.headers.get(\"Retry-After\"), 1);\n        await sleep(retryAfter * 1000);\n        return attempt < maxRetries;\n      }\n      return false;\n    },\n\n    parseRateLimitHeaders: (_headers: Headers): RateLimitInfo | undefined => {\n      // Default: no parsing. Plugins override this.\n      return undefined;\n    },\n  };\n\n  // Prevent accidental deletion of function properties\n  for (const prop of [\n    \"request\",\n    \"createHeaders\",\n    \"runRequest\",\n    \"handleResponse\",\n    \"handleRateLimit\",\n    \"parseRateLimitHeaders\",\n  ] as const) {\n    Object.defineProperty(manager, prop, {\n      value: manager[prop],\n      writable: true,\n      enumerable: true,\n      configurable: false,\n    });\n  }\n  return manager;\n};\n\nconst sleep = (ms: number): Promise<void> => {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n};\n\n/**\n * Companion object for the RestManager type.\n * Provides type guard utility.\n *\n * @category Plugin Development\n */\nexport const RestManager = {\n  /**\n   * Type guard for RestManager.\n   *\n   * @param value - the value to check\n   * @returns true if value implements RestManager interface\n   */\n  is(value: unknown): value is RestManager {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string | symbol, unknown>;\n    return (\n      typeof obj.platform === \"string\" &&\n      typeof obj.baseUrl === \"string\" &&\n      typeof obj.request === \"function\" &&\n      typeof obj.createHeaders === \"function\" &&\n      typeof obj.runRequest === \"function\" &&\n      typeof obj.handleResponse === \"function\" &&\n      typeof obj.handleRateLimit === \"function\" &&\n      typeof obj.parseRateLimitHeaders === \"function\"\n    );\n  },\n} as const;\n\n/**\n * Parse a Retry-After header value into a bounded number of seconds.\n * Returns fallback if the header is missing, NaN, or out of bounds.\n *\n * @param header - raw Retry-After header value (may be null)\n * @param fallback - default seconds if header is missing or invalid\n * @returns seconds in range [0, 120], or fallback if header is missing/invalid\n * @category Plugin Development\n */\nexport const parseRetryAfter = (header: string | null, fallback = 1): number => {\n  if (!header) return Math.min(Math.max(fallback, 0), 120);\n  const parsed = Number.parseInt(header, 10);\n  if (Number.isNaN(parsed) || parsed < 0) return Math.min(Math.max(fallback, 0), 120);\n  return Math.min(parsed, 120);\n};\n","import type { TokenManager } from \"./auth/types\";\nimport { ValidationError } from \"./errors\";\nimport { createRestManager, type RestManager } from \"./rest/manager\";\nimport type { RateLimitStrategy } from \"./rest/strategy\";\nimport type { RateLimitInfo, RestRequest, RetryConfig } from \"./rest/types\";\nimport type {\n  Archive,\n  ArchiveListOptions,\n  BatchResult,\n  Broadcast,\n  Channel,\n  Clip,\n  ClipOptions,\n  Content,\n  Page,\n  ResolvedUrl,\n  SearchOptions,\n} from \"./types\";\n\n/** @category Plugins */\nexport type PluginCapabilities = {\n  /** Whether the plugin supports broadcast detection */\n  supportsBroadcasts: boolean;\n  /** Whether the plugin supports archive resolution (broadcast -> archive) */\n  supportsArchiveResolution: boolean;\n  /** Authentication model used by this plugin */\n  authModel: \"apiKey\" | \"oauth2\" | \"basic\" | \"none\";\n  /** Rate limiting model */\n  rateLimitModel: \"quota\" | \"tokenBucket\";\n  /** Whether the plugin supports batch content retrieval */\n  supportsBatchContent: boolean;\n  /** Whether the plugin supports batch broadcast retrieval */\n  supportsBatchBroadcasts: boolean;\n  /** Whether the plugin supports search */\n  supportsSearch: boolean;\n  /** Whether the plugin supports clip retrieval */\n  supportsClips: boolean;\n};\n\n/**\n * Declarative configuration for creating a PlatformPlugin via `PlatformPlugin.create()`.\n * Plugin authors provide this instead of manually wiring RestManager overrides.\n *\n * @category Plugins\n */\nexport type PluginDefinition = {\n  /** Platform identifier (e.g., \"youtube\", \"twitch\"). */\n  name: string;\n\n  /** Base URL for the platform's API. */\n  baseUrl: string;\n\n  /** Rate limiting strategy instance. */\n  rateLimitStrategy: RateLimitStrategy;\n\n  /** Token manager for auth (optional — some platforms use query param auth). */\n  tokenManager?: TokenManager;\n\n  /** URL matcher — pure function, no network calls. */\n  matchUrl: (url: string) => ResolvedUrl | null;\n\n  /** Transform requests before sending (e.g., inject API key, add headers). */\n  transformRequest?: (req: RestRequest) => RestRequest;\n\n  /** Additional default headers for all requests. */\n  headers?: Record<string, string>;\n\n  /** Platform-specific rate limit handling (e.g., YouTube 403 quota detection). */\n  handleRateLimit?: (response: Response, req: RestRequest, attempt: number) => Promise<boolean>;\n\n  /** Parse rate limit info from response headers. */\n  parseRateLimitHeaders?: (headers: Headers) => RateLimitInfo | undefined;\n\n  /** Override fetch for testing. */\n  fetch?: typeof globalThis.fetch;\n\n  /** Retry configuration. */\n  retry?: RetryConfig;\n\n  /** Plugin capability metadata. */\n  capabilities?: PluginCapabilities;\n};\n\n/**\n * Platform-specific data access methods.\n * Separated from PluginDefinition because they need access to the constructed RestManager.\n * Methods receive `rest` as the first argument — pure functions that are easier to test and compose.\n *\n * @category Plugins\n */\nexport type PluginMethods = {\n  /** Retrieve content by ID. */\n  getContent: (rest: RestManager, id: string) => Promise<Content>;\n\n  /** Retrieve channel by ID. */\n  getChannel: (rest: RestManager, id: string) => Promise<Channel>;\n\n  /** List currently active broadcasts for a channel. */\n  listBroadcasts: (rest: RestManager, channelId: string) => Promise<Broadcast[]>;\n\n  /** List archives for a channel with pagination. */\n  listArchives: (\n    rest: RestManager,\n    channelId: string,\n    cursor?: string,\n    pageSize?: number,\n    options?: ArchiveListOptions,\n  ) => Promise<Page<Archive>>;\n\n  /** Resolve the archive for a broadcast (optional). */\n  resolveArchive?: (rest: RestManager, live: Broadcast) => Promise<Archive | null>;\n\n  /** Batch-retrieve content by IDs (optional). */\n  batchGetContents?: (rest: RestManager, ids: string[]) => Promise<BatchResult<Content>>;\n\n  /** Batch-retrieve broadcasts by channel IDs (optional). */\n  batchGetBroadcasts?: (\n    rest: RestManager,\n    channelIds: string[],\n  ) => Promise<BatchResult<Broadcast[]>>;\n\n  /** Search for content (optional). */\n  search?: (rest: RestManager, options: SearchOptions) => Promise<Page<Content>>;\n\n  /** List clips for a channel (optional). */\n  listClips?: (rest: RestManager, channelId: string, options?: ClipOptions) => Promise<Page<Clip>>;\n\n  /** Batch-retrieve clips by IDs (optional). */\n  batchGetClips?: (rest: RestManager, ids: string[]) => Promise<BatchResult<Clip>>;\n\n  /** Batch-retrieve channels by IDs (optional). */\n  batchGetChannels?: (rest: RestManager, ids: string[]) => Promise<BatchResult<Channel>>;\n};\n\n/**\n * A platform-specific plugin that implements data retrieval for a single streaming platform.\n *\n * @precondition Each plugin instance is bound to a single platform\n * @postcondition All returned data conforms to the unified Content/Channel types\n * @category Plugins\n */\nexport type PlatformPlugin = {\n  /** Platform identifier (e.g., \"youtube\", \"twitch\", \"twitcasting\"). */\n  readonly name: string;\n\n  /** The underlying RestManager for this plugin. */\n  readonly rest: RestManager;\n\n  /** Plugin capability metadata. */\n  readonly capabilities: PluginCapabilities;\n\n  /**\n   * Test whether a URL belongs to this platform.\n   * Returns a ResolvedUrl if matched, or null if not.\n   * No network calls.\n   */\n  match(url: string): ResolvedUrl | null;\n\n  /** Retrieve content (broadcast or archive) by ID. */\n  getContent(id: string): Promise<Content>;\n\n  /** Retrieve channel information by ID. */\n  getChannel(id: string): Promise<Channel>;\n\n  /** List currently active broadcasts for a channel. */\n  listBroadcasts(channelId: string): Promise<Broadcast[]>;\n\n  /** List archives for a channel with cursor-based pagination. */\n  listArchives(\n    channelId: string,\n    cursor?: string,\n    pageSize?: number,\n    options?: ArchiveListOptions,\n  ): Promise<Page<Archive>>;\n\n  /** Resolve the archive for a broadcast (platform-specific). */\n  resolveArchive?(live: Broadcast): Promise<Archive | null>;\n\n  /** Batch-retrieve content by IDs (platform-specific). */\n  batchGetContents?(ids: string[]): Promise<BatchResult<Content>>;\n\n  /** Batch-retrieve broadcasts by channel IDs (platform-specific). */\n  batchGetBroadcasts?(channelIds: string[]): Promise<BatchResult<Broadcast[]>>;\n\n  /** Search for content (platform-specific). */\n  search?(options: SearchOptions): Promise<Page<Content>>;\n\n  /** List clips for a channel (platform-specific). */\n  listClips?(channelId: string, options?: ClipOptions): Promise<Page<Clip>>;\n\n  /** Batch-retrieve clips by IDs (platform-specific). */\n  batchGetClips?(ids: string[]): Promise<BatchResult<Clip>>;\n\n  /** Batch-retrieve channels by IDs (platform-specific). */\n  batchGetChannels?(ids: string[]): Promise<BatchResult<Channel>>;\n};\n\n/**\n * Companion object for the PlatformPlugin type.\n * Provides factory and type guard utilities.\n *\n * @category Plugins\n * @example\n * ```ts\n * const plugin = PlatformPlugin.create(definition, methods);\n * if (PlatformPlugin.is(unknown)) { ... }\n * ```\n */\nexport const PlatformPlugin = {\n  /**\n   * Create a PlatformPlugin from a declarative definition and methods.\n   *\n   * @param definition - declarative plugin configuration\n   * @param methods - platform-specific data access implementations\n   * @returns a fully wired PlatformPlugin\n   * @precondition definition.rateLimitStrategy is initialized\n   * @postcondition returns a fully functional PlatformPlugin with wired RestManager\n   */\n  create(definition: PluginDefinition, methods: PluginMethods): PlatformPlugin {\n    let parsedBaseUrl: URL;\n    try {\n      parsedBaseUrl = new URL(definition.baseUrl);\n    } catch {\n      throw new ValidationError(\n        \"VALIDATION_INVALID_URL\",\n        `Plugin \"${definition.name}\" baseUrl is not a valid URL (got \"${definition.baseUrl}\")`,\n        { platform: definition.name },\n      );\n    }\n    if (parsedBaseUrl.protocol !== \"https:\") {\n      throw new ValidationError(\n        \"VALIDATION_INVALID_URL\",\n        `Plugin \"${definition.name}\" baseUrl must use HTTPS (got \"${definition.baseUrl}\")`,\n        { platform: definition.name },\n      );\n    }\n\n    const rest = createRestManager({\n      platform: definition.name,\n      baseUrl: definition.baseUrl,\n      rateLimitStrategy: definition.rateLimitStrategy,\n      tokenManager: definition.tokenManager,\n      headers: definition.headers,\n      fetch: definition.fetch,\n      retry: definition.retry,\n    });\n\n    if (definition.transformRequest) {\n      const origRequest = rest.request;\n      const transform = definition.transformRequest;\n      rest.request = <T>(req: RestRequest) => {\n        return origRequest<T>(transform(req));\n      };\n    }\n\n    if (definition.handleRateLimit) {\n      rest.handleRateLimit = definition.handleRateLimit;\n    }\n\n    if (definition.parseRateLimitHeaders) {\n      rest.parseRateLimitHeaders = definition.parseRateLimitHeaders;\n    }\n\n    const plugin: PlatformPlugin = {\n      name: definition.name,\n      rest,\n      capabilities: definition.capabilities ?? {\n        supportsBroadcasts: true,\n        supportsArchiveResolution: !!methods.resolveArchive,\n        authModel: \"apiKey\",\n        rateLimitModel: \"tokenBucket\",\n        supportsBatchContent: !!methods.batchGetContents,\n        supportsBatchBroadcasts: !!methods.batchGetBroadcasts,\n        supportsSearch: !!methods.search,\n        supportsClips: !!methods.listClips,\n      },\n      match: definition.matchUrl,\n      getContent: (id) => methods.getContent(rest, id),\n      getChannel: (id) => methods.getChannel(rest, id),\n      listBroadcasts: (channelId) => methods.listBroadcasts(rest, channelId),\n      listArchives: (channelId, cursor, pageSize, options) =>\n        methods.listArchives(rest, channelId, cursor, pageSize, options),\n      resolveArchive: methods.resolveArchive\n        ? (live) => methods.resolveArchive!(rest, live)\n        : undefined,\n      batchGetContents: methods.batchGetContents\n        ? (ids) => methods.batchGetContents!(rest, ids)\n        : undefined,\n      batchGetBroadcasts: methods.batchGetBroadcasts\n        ? (channelIds) => methods.batchGetBroadcasts!(rest, channelIds)\n        : undefined,\n      search: methods.search ? (options) => methods.search!(rest, options) : undefined,\n      listClips: methods.listClips\n        ? (channelId, options) => methods.listClips!(rest, channelId, options)\n        : undefined,\n      batchGetClips: methods.batchGetClips ? (ids) => methods.batchGetClips!(rest, ids) : undefined,\n      batchGetChannels: methods.batchGetChannels\n        ? (ids) => methods.batchGetChannels!(rest, ids)\n        : undefined,\n    };\n\n    return plugin;\n  },\n\n  /**\n   * Type guard for PlatformPlugin.\n   *\n   * @param value - the value to check\n   * @returns true if value implements PlatformPlugin\n   * @postcondition returns true if value has all required PlatformPlugin properties\n   */\n  is(value: unknown): value is PlatformPlugin {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string | symbol, unknown>;\n    return (\n      typeof obj.name === \"string\" &&\n      typeof obj.match === \"function\" &&\n      typeof obj.getContent === \"function\" &&\n      typeof obj.getChannel === \"function\" &&\n      typeof obj.listBroadcasts === \"function\" &&\n      typeof obj.listArchives === \"function\" &&\n      obj.rest !== undefined &&\n      typeof obj.capabilities === \"object\" &&\n      obj.capabilities !== null\n    );\n  },\n} as const;\n","import { RateLimitError } from \"../errors\";\nimport type { RateLimitHandle, RateLimitStatus, RateLimitStrategy } from \"./strategy\";\nimport type { RateLimitInfo, RestRequest } from \"./types\";\n\n/** @category Plugin Development */\nexport type TokenBucketConfig = {\n  global: { requests: number; perMs: number };\n  parseHeaders: (headers: Headers) => RateLimitInfo | undefined;\n  platform: string;\n};\n\n/**\n * Creates a header-driven token bucket strategy (used by Twitch, TwitCasting).\n * Uses lazy refill: tokens are recalculated from elapsed time on each acquire() call.\n * No timers, no cleanup needed.\n *\n * @param config - token bucket configuration with limits, header parser, and platform name\n * @returns a RateLimitStrategy backed by a token bucket\n * @precondition global.requests > 0 and global.perMs > 0\n * @postcondition acquire() rejects with RateLimitError when no tokens are available\n * @idempotency Not idempotent — each acquire() consumes a token\n * @category Plugin Development\n */\nexport const createTokenBucketStrategy = (config: TokenBucketConfig): RateLimitStrategy => {\n  let remaining = config.global.requests;\n  const limit = config.global.requests;\n  let lastRefillTime = Date.now();\n  let resetsAt = new Date(lastRefillTime + config.global.perMs);\n\n  const refill = (): void => {\n    if (Date.now() >= resetsAt.getTime()) {\n      remaining = limit;\n      lastRefillTime = Date.now();\n      resetsAt = new Date(lastRefillTime + config.global.perMs);\n    }\n  };\n\n  return {\n    acquire(_req: RestRequest): Promise<RateLimitHandle> {\n      refill();\n\n      if (remaining <= 0) {\n        const retryAfterMs = resetsAt.getTime() - Date.now();\n        const retryAfter = Math.max(1, Math.ceil(retryAfterMs / 1000));\n        return Promise.reject(new RateLimitError(config.platform, { retryAfter }));\n      }\n\n      remaining--;\n      const handle: RateLimitHandle = {\n        complete(headers: Headers) {\n          const info = config.parseHeaders(headers);\n          if (info) {\n            remaining = info.remaining;\n            resetsAt = info.resetsAt;\n          }\n        },\n        release() {\n          remaining = Math.min(remaining + 1, limit);\n        },\n      };\n      return Promise.resolve(handle);\n    },\n\n    getStatus(): RateLimitStatus {\n      return {\n        remaining,\n        limit,\n        resetsAt,\n        queued: 0,\n      };\n    },\n  };\n};\n","import { QuotaExhaustedError } from \"../errors\";\nimport type { RateLimitHandle, RateLimitStatus, RateLimitStrategy } from \"./strategy\";\nimport type { RestRequest } from \"./types\";\n\n/** @category Plugin Development */\nexport type QuotaBudgetConfig = {\n  dailyLimit?: number;\n  costMap: Record<string, number>;\n  defaultCost?: number;\n  platform?: string;\n};\n\n/**\n * Pacific time midnight (Google's quota reset schedule).\n *\n * @returns the next midnight PT as a Date\n */\n/** Reusable formatter for Pacific time — Intl.DateTimeFormat construction is expensive. */\nconst ptFormatter = new Intl.DateTimeFormat(\"en-US\", {\n  timeZone: \"America/Los_Angeles\",\n  year: \"numeric\",\n  month: \"2-digit\",\n  day: \"2-digit\",\n  hour: \"2-digit\",\n  minute: \"2-digit\",\n  second: \"2-digit\",\n  hour12: false,\n});\n\nconst nextResetTime = (): Date => {\n  const now = new Date();\n  const parts = ptFormatter.formatToParts(now);\n  const get = (type: Intl.DateTimeFormatPartTypes) => {\n    const part = parts.find((p) => p.type === type);\n    return Number.parseInt(part?.value ?? \"0\", 10);\n  };\n\n  const ptYear = get(\"year\");\n  const ptMonth = get(\"month\") - 1;\n  const ptDay = get(\"day\");\n  const ptHour = get(\"hour\");\n  const ptMinute = get(\"minute\");\n  const ptSecond = get(\"second\");\n\n  // Build \"now\" and \"tomorrow midnight\" as local Dates for offset computation\n  const ptNow = new Date(ptYear, ptMonth, ptDay, ptHour, ptMinute, ptSecond);\n  const ptMidnight = new Date(ptYear, ptMonth, ptDay + 1, 0, 0, 0, 0);\n  const offset = ptNow.getTime() - now.getTime();\n  return new Date(ptMidnight.getTime() - offset);\n};\n\n/**\n * Creates a cost-based daily quota strategy (used by YouTube).\n *\n * @param config - quota budget configuration with limits and cost map\n * @returns a RateLimitStrategy backed by daily quota tracking\n * @precondition costMap maps bucketId strings to their quota costs\n * @postcondition acquire() throws QuotaExhaustedError when quota is exceeded\n * @idempotency Not idempotent — each acquire() consumes quota\n * @category Plugin Development\n */\nexport const createQuotaBudgetStrategy = (config: QuotaBudgetConfig): RateLimitStrategy => {\n  const dailyLimit = config.dailyLimit ?? 10_000;\n  const defaultCost = config.defaultCost ?? 1;\n  const platform = config.platform ?? \"unknown\";\n\n  for (const [key, cost] of Object.entries(config.costMap)) {\n    if (cost < 0) {\n      throw new Error(`Invalid cost map: \"${key}\" has negative cost ${cost}`);\n    }\n  }\n\n  let consumed = 0;\n  let resetsAt = nextResetTime();\n\n  return {\n    acquire(req: RestRequest): Promise<RateLimitHandle> {\n      // Lazy reset: if past reset time, reset quota inline\n      if (Date.now() >= resetsAt.getTime()) {\n        consumed = 0;\n        resetsAt = nextResetTime();\n      }\n\n      const cost: number =\n        req.bucketId !== undefined ? (config.costMap[req.bucketId] ?? defaultCost) : defaultCost;\n\n      if (consumed + cost > dailyLimit) {\n        return Promise.reject(\n          new QuotaExhaustedError(platform, {\n            consumed,\n            limit: dailyLimit,\n            resetsAt,\n            requestedCost: cost,\n          }),\n        );\n      }\n\n      consumed += cost;\n\n      const handle: RateLimitHandle = {\n        complete() {\n          // YouTube doesn't provide quota info in headers — no-op.\n        },\n        release() {\n          consumed = Math.max(0, consumed - cost);\n        },\n      };\n\n      return Promise.resolve(handle);\n    },\n\n    getStatus(): RateLimitStatus {\n      return {\n        remaining: dailyLimit - consumed,\n        limit: dailyLimit,\n        resetsAt,\n        queued: 0,\n      };\n    },\n  };\n};\n","import type { RestRequest } from \"./types\";\n\n/**\n * Handle returned by a rate limit strategy after acquiring a slot.\n * Callers must invoke either complete() or release() — never both.\n *\n * @postcondition complete() is called on success, release() on error\n * @category Plugin Development\n */\nexport type RateLimitHandle = {\n  /** Called after successful response — updates state from response headers. */\n  complete(headers: Headers): void;\n  /** Called on retry — returns the consumed token/quota. */\n  release(): void;\n};\n\n/**\n * Snapshot of a rate limit strategy's current state for telemetry.\n *\n * @category Plugin Development\n */\nexport type RateLimitStatus = {\n  remaining: number;\n  limit: number;\n  resetsAt: Date;\n  queued: number;\n};\n\n/**\n * Controls request throughput for a platform's rate limiting scheme.\n *\n * @precondition One strategy instance per platform\n * @postcondition acquire() resolves when it's safe to proceed with the request\n * @category Plugin Development\n */\nexport type RateLimitStrategy = {\n  /**\n   * Called before each request.\n   * Consumes a token/quota unit and returns a handle.\n   * May block (await) if tokens are exhausted.\n   */\n  acquire(req: RestRequest): Promise<RateLimitHandle>;\n  /** Current rate limit status (for telemetry). */\n  getStatus(): RateLimitStatus;\n};\n\n/**\n * Companion object for the RateLimitStrategy type.\n * Provides type guard utility.\n *\n * @example\n * ```ts\n * if (RateLimitStrategy.is(unknown)) { ... }\n * ```\n * @category Plugin Development\n */\nexport const RateLimitStrategy = {\n  /**\n   * Type guard for RateLimitStrategy.\n   *\n   * @param value - the value to check\n   * @returns true if value implements RateLimitStrategy interface\n   * @postcondition returns true if value has acquire and getStatus methods\n   */\n  is(value: unknown): value is RateLimitStrategy {\n    if (typeof value !== \"object\" || value === null) return false;\n    const obj = value as Record<string | symbol, unknown>;\n    return typeof obj.acquire === \"function\" && typeof obj.getStatus === \"function\";\n  },\n} as const;\n","import type { MeterProvider, TracerProvider } from \"@opentelemetry/api\";\nimport type { TokenManager } from \"../auth/types\";\nimport type { RateLimitStrategy } from \"./strategy\";\n\n/**\n * Describes an outgoing HTTP request to a platform API.\n *\n * @precondition path is a relative path (e.g., \"/videos\")\n * @postcondition query values are URL-encoded by the RestManager\n * @category Plugin Development\n */\nexport type RestRequest = {\n  method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n  path: string;\n  query?: Record<string, string | string[]>;\n  body?: unknown;\n  /**\n   * Body serialization format.\n   * - \"json\" (default): JSON.stringify the body and set Content-Type: application/json\n   * - \"raw\": pass body directly to fetch (e.g., for FormData, URLSearchParams, ReadableStream)\n   */\n  bodyType?: \"json\" | \"raw\";\n  headers?: Record<string, string>;\n  /** AbortSignal to cancel the request. */\n  signal?: AbortSignal;\n  /** Rate limit bucket key (e.g., \"videos:list\", \"search:list\"). */\n  bucketId?: string;\n};\n\n/**\n * Parsed response from a platform API request.\n *\n * @postcondition data contains the parsed JSON response body\n * @category Plugin Development\n */\nexport type RestResponse<T = unknown> = {\n  status: number;\n  headers: Headers;\n  data: T;\n  rateLimit?: RateLimitInfo;\n};\n\n/**\n * Rate limit metadata extracted from response headers.\n *\n * @category Plugin Development\n */\nexport type RateLimitInfo = {\n  limit: number;\n  remaining: number;\n  resetsAt: Date;\n  bucket?: string;\n};\n\n/**\n * Configuration options for creating a RestManager.\n *\n * @precondition baseUrl must use HTTPS\n * @precondition rateLimitStrategy must be initialized\n * @category Plugin Development\n */\nexport type RestManagerOptions = {\n  platform: string;\n  baseUrl: string;\n  headers?: Record<string, string>;\n  rateLimitStrategy: RateLimitStrategy;\n  tokenManager?: TokenManager;\n  fetch?: typeof globalThis.fetch;\n  retry?: RetryConfig;\n  tracerProvider?: TracerProvider;\n  meterProvider?: MeterProvider;\n};\n\n/**\n * Configuration for request retry behavior.\n *\n * @category Plugin Development\n */\nexport type RetryConfig = {\n  maxRetries?: number;\n  baseDelay?: number;\n  retryableStatuses?: number[];\n  /** Request timeout in milliseconds. Applied when no user-provided signal exists. */\n  timeout?: number;\n};\n\n/**\n * Creates a rate limit header parser from header name mappings.\n * Eliminates duplication across plugins that use standard limit/remaining/reset headers.\n *\n * @param headerNames - mapping of header names for limit, remaining, and reset\n * @returns a parser function that extracts rate limit info from headers\n * @idempotency Safe — returns a pure function\n * @category Plugin Development\n */\nexport const createRateLimitHeaderParser = (headerNames: {\n  limit: string;\n  remaining: string;\n  reset: string;\n}): ((headers: Headers) => RateLimitInfo | undefined) => {\n  return (headers: Headers) => {\n    const limit = headers.get(headerNames.limit);\n    const remaining = headers.get(headerNames.remaining);\n    const reset = headers.get(headerNames.reset);\n    if (!limit || !remaining || !reset) return undefined;\n    return {\n      limit: Number.parseInt(limit, 10),\n      remaining: Number.parseInt(remaining, 10),\n      resetsAt: new Date(Number.parseInt(reset, 10) * 1000),\n    };\n  };\n};\n","import type { UnifiedLiveError } from \"./errors\";\n\n/** @internal */\nexport type OkResult<V> = {\n  val: V;\n  err?: never;\n};\n\n/** @internal */\nexport type ErrResult<E extends UnifiedLiveError> = {\n  val?: never;\n  err: E;\n};\n\n/** @internal */\nexport type Result<V, E extends UnifiedLiveError = UnifiedLiveError> = OkResult<V> | ErrResult<E>;\n\n/** @internal */\nexport function Ok(): OkResult<never>;\n/** @internal */\nexport function Ok<V>(val: V): OkResult<V>;\n/**\n * @internal\n * @param val - the value to wrap\n * @returns an OkResult containing the value\n */\nexport function Ok<V>(val?: V): OkResult<V> {\n  return { val } as OkResult<V>;\n}\n\n/**\n * @internal\n * @param err - the error to wrap\n * @returns an ErrResult containing the error\n */\nexport const Err = <E extends UnifiedLiveError>(err: E): ErrResult<E> => {\n  return { err };\n};\n\n/**\n * Wrap a promise into a Result, catching thrown errors.\n *\n * @internal\n * @param p - the promise to wrap\n * @param errorFactory - converts caught errors into UnifiedLiveError subclasses\n * @returns Ok on success, Err on failure\n * @precondition errorFactory converts any caught Error into a UnifiedLiveError subclass\n * @postcondition returns Ok on success, Err on failure — never throws\n * @idempotency Safe — pure wrapper\n */\nexport const wrap = async <T, E extends UnifiedLiveError>(\n  p: Promise<T>,\n  errorFactory: (err: Error) => E,\n): Promise<Result<T, E>> => {\n  try {\n    return Ok(await p);\n  } catch (e) {\n    return Err(errorFactory(e as Error));\n  }\n};\n\n/**\n * Unwrap a Result — returns the value or throws the error.\n * Use at public API boundaries to convert Result back to thrown exceptions.\n *\n * @internal\n * @param result - the Result to unwrap\n * @returns the contained value\n * @precondition result is a valid Result\n * @postcondition returns val if Ok, throws err if Err\n */\nexport const unwrap = <V, E extends UnifiedLiveError>(result: Result<V, E>): V => {\n  if (result.err) {\n    throw result.err;\n  }\n  return result.val as V;\n};\n"],"mappings":"AAmCA,MAAa,EAAY,CAOvB,UAAY,GACV,IAAS,mBACT,IAAS,sBACT,IAAS,eACT,IAAS,gBAQX,OAAS,GACP,IAAS,0BAA4B,IAAS,yBAQhD,cAAgB,GACd,IAAS,aACT,IAAS,0BACT,IAAS,4BACT,IAAS,qBAQX,YAAc,GACZ,IAAS,uBAAyB,IAAS,kBAC9C,CA+BD,IAAa,EAAb,cAAsC,KAAM,CAC1C,KACA,QAEA,YACE,EACA,EACA,EACA,EACA,CACA,MAAM,EAAS,CAAE,MAAO,GAAS,MAAO,CAAC,CACzC,KAAK,KAAO,mBACZ,KAAK,KAAO,EACZ,KAAK,QAAU,EAQjB,IAAI,UAAmB,CACrB,OAAO,KAAK,QAAQ,SAGtB,IAAK,OAAO,cAAuB,CACjC,OAAO,KAAK,KASd,QAAkC,CAChC,IAAM,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