{
  "version": 3,
  "sources": ["../src/logger.ts", "../src/time.ts", "../src/cache.ts", "../src/canonical-json.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bytes.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bases/base.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bases/base64.ts", "../src/type-utils.ts", "../src/convert.ts", "../src/cross-context-lock.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/bases/base36.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/varint.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/.bun/multiformats@14.0.3/node_modules/multiformats/src/cid.ts", "../src/multicodec.ts", "../src/network.ts", "../src/object.ts", "../src/stores.ts", "../src/stream.ts", "../src/url.ts"],
  "sourcesContent": ["/**\n * Enbox logger level.\n */\nexport enum LogLevel {\n  Debug = 'debug',\n  Silent = 'silent',\n}\n\n/**\n * Enbox logger interface.\n */\nexport interface LoggerInterface {\n\n  /**\n   * Sets the log verbose level.\n   */\n  setLogLevel(logLevel: LogLevel): void;\n\n  /**\n   * Same as `info()`.\n   * Logs an informational message.\n   */\n  log (message: string): void;\n\n  /**\n   * Logs an informational message.\n   */\n  info(message: string): void;\n\n  /**\n   * Logs an error message.\n   */\n  error(message: string): void;\n}\n\n/**\n * An Enbox logger implementation.\n */\nclass EnboxLogger implements LoggerInterface {\n  private logLevel: LogLevel = LogLevel.Silent; // Default to silent/no-op log level\n\n  setLogLevel(logLevel: LogLevel): void {\n    this.logLevel = logLevel;\n  }\n\n  public log(message: string): void {\n    this.info(message);\n  }\n\n  public info(message: string): void {\n    if (this.logLevel === LogLevel.Silent) { return; }\n\n    console.info(message);\n  }\n\n  public error(message: string): void {\n    if (this.logLevel === LogLevel.Silent) { return; }\n\n    console.error(message);\n  }\n}\n\n// Export a singleton logger instance\nexport const logger = new EnboxLogger();\n\n// Attach logger to the global window object in browser environment for easy access to the logger instance.\n// e.g. can call `enboxLogger.setLogLevel('debug');` directly in browser console.\ndeclare global {\n  interface Window { enboxLogger?: EnboxLogger }\n}\n\nif (typeof window !== 'undefined') {\n  window.enboxLogger = logger;\n}\n", "/**\n * Time-related helpers shared across packages.\n *\n * @module\n */\n\nimport { logger } from './logger.js';\n\nexport type TimedOptions = {\n  /** Receives the success/failure timing line. Defaults to the shared Enbox logger. */\n  log?: (message: string) => void;\n};\n\nconst durationUnitMultipliers = new Map<string, number>([\n  ['ms', 1],\n  ['msec', 1],\n  ['msecs', 1],\n  ['millisecond', 1],\n  ['milliseconds', 1],\n  ['s', 1000],\n  ['sec', 1000],\n  ['secs', 1000],\n  ['second', 1000],\n  ['seconds', 1000],\n  ['m', 60 * 1000],\n  ['min', 60 * 1000],\n  ['mins', 60 * 1000],\n  ['minute', 60 * 1000],\n  ['minutes', 60 * 1000],\n  ['h', 60 * 60 * 1000],\n  ['hr', 60 * 60 * 1000],\n  ['hrs', 60 * 60 * 1000],\n  ['hour', 60 * 60 * 1000],\n  ['hours', 60 * 60 * 1000],\n  ['d', 24 * 60 * 60 * 1000],\n  ['day', 24 * 60 * 60 * 1000],\n  ['days', 24 * 60 * 60 * 1000],\n  ['w', 7 * 24 * 60 * 60 * 1000],\n  ['week', 7 * 24 * 60 * 60 * 1000],\n  ['weeks', 7 * 24 * 60 * 60 * 1000],\n  ['y', 365.25 * 24 * 60 * 60 * 1000],\n  ['yr', 365.25 * 24 * 60 * 60 * 1000],\n  ['yrs', 365.25 * 24 * 60 * 60 * 1000],\n  ['year', 365.25 * 24 * 60 * 60 * 1000],\n  ['years', 365.25 * 24 * 60 * 60 * 1000],\n]);\n\n/**\n * Returns a high-resolution monotonic timestamp in milliseconds.\n *\n * Uses `performance.now()` when available so elapsed durations are not\n * affected by wall-clock changes. Falls back to `Date.now()` in runtimes\n * that do not expose `performance`.\n */\nexport function nowMs(): number {\n  if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n    return performance.now();\n  }\n\n  return Date.now();\n}\n\n/**\n * Parses a human-readable duration string into milliseconds.\n *\n * Accepted units: milliseconds (`ms`), seconds (`s`), minutes (`m`), hours (`h`),\n * days (`d`), weeks (`w`), and years (`y`), including their common long-form\n * aliases such as `minutes` and `hours`. A bare numeric string is treated as\n * milliseconds.\n *\n * @throws Error if the input is empty, negative, non-finite, or uses an unknown unit.\n */\nexport function parseDurationInMilliseconds(duration: string): number {\n  const match = /^((?:\\d+|\\d*\\.\\d+))\\s*([a-zA-Z]+)?$/.exec(duration.trim());\n  if (match === null) {\n    throw new Error(`Invalid duration: '${duration}'`);\n  }\n\n  const durationUnit = match[2]?.toLowerCase() ?? 'ms';\n  const multiplier = durationUnitMultipliers.get(durationUnit);\n  if (multiplier === undefined) {\n    throw new Error(`Invalid duration unit: '${durationUnit}'`);\n  }\n\n  const durationInMilliseconds = Number(match[1]) * multiplier;\n  if (!Number.isFinite(durationInMilliseconds)) {\n    throw new TypeError(`Invalid duration: '${duration}'`);\n  }\n\n  return durationInMilliseconds;\n}\n\n/**\n * Times an async operation and logs a single success/failure duration line.\n *\n * The label is intentionally caller-defined so packages can include their own\n * log namespace, e.g. `[connect.perf] response.sign`.\n */\nexport async function timed<T>(\n  label: string,\n  fn: () => Promise<T>,\n  { log = logger.log.bind(logger) }: TimedOptions = {}\n): Promise<T> {\n  const start = nowMs();\n  try {\n    const result = await fn();\n    const elapsed = nowMs() - start;\n    log(`${label} ok in ${elapsed.toFixed(1)}ms`);\n    return result;\n  } catch (err) {\n    const elapsed = nowMs() - start;\n    log(`${label} fail in ${elapsed.toFixed(1)}ms`);\n    throw err;\n  }\n}\n\n/** Largest delay accepted by the native timer APIs without overflow coercion. */\nexport const MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/**\n * Returns a promise that resolves after the given duration or rejects when\n * `signal` aborts. Long waits are split into native-timer-sized chunks so an\n * oversized delay cannot be coerced by the runtime into an immediate timer.\n *\n * Use this anywhere you would otherwise inline\n * `new Promise(resolve => setTimeout(resolve, ms))` \u2014 retry backoff,\n * polling intervals, throttled tests, etc. Centralizing the idiom keeps\n * call sites readable and ensures every retry/poll path has one obvious\n * primitive to reach for.\n *\n * Negative or zero durations resolve on the next macrotask via\n * `setTimeout(_, 0)`; they do not throw.\n *\n * @param durationInMilliseconds - How long to wait, in milliseconds.\n * @param signal - Optional cancellation signal for the wait.\n * @returns A promise that resolves after the duration elapses.\n *\n * @example\n * ```ts\n * import { sleep } from '@enbox/common';\n *\n * await sleep(250); // pause for 250ms\n * ```\n */\nexport function sleep(durationInMilliseconds: number, signal?: AbortSignal): Promise<void> {\n  if (!Number.isFinite(durationInMilliseconds)) {\n    return Promise.reject(new TypeError('sleep duration must be finite'));\n  }\n  if (signal?.aborted === true) {\n    return Promise.reject(signal.reason);\n  }\n\n  let remaining = Math.max(0, durationInMilliseconds);\n  return new Promise<void>((resolve, reject) => {\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const onAbort = (): void => {\n      if (timer !== undefined) {\n        clearTimeout(timer);\n      }\n      reject(signal?.reason);\n    };\n    const schedule = (): void => {\n      const delay = Math.min(remaining, MAX_TIMER_DELAY_MS);\n      timer = setTimeout((): void => {\n        remaining -= delay;\n        if (remaining > 0) {\n          schedule();\n          return;\n        }\n        signal?.removeEventListener('abort', onAbort);\n        resolve();\n      }, delay);\n    };\n\n    signal?.addEventListener('abort', onAbort, { once: true });\n    schedule();\n  });\n}\n", "import { MAX_TIMER_DELAY_MS } from './time.js';\n\ntype TtlCacheEntry<V> = {\n  expiresAt: number;\n  sequence: number;\n  value: V;\n};\n\ntype TtlCacheEvictionCandidate<K, V> = {\n  entry: TtlCacheEntry<V>;\n  expiresAt: number;\n  key: K;\n  sequence: number;\n};\n\ntype TtlCachePurgeState = {\n  purgedStale: boolean;\n};\n\ntype TtlCacheTimer = ReturnType<typeof setTimeout>;\n\nfunction now(): number {\n  return performance.now();\n}\n\nfunction isPositiveIntegerOrInfinity(value: number): boolean {\n  return value === Infinity || (Number.isInteger(value) && value > 0 && Number.isFinite(value));\n}\n\nfunction assertPositiveIntegerOrInfinity(value: number, name: string): void {\n  if (!isPositiveIntegerOrInfinity(value)) {\n    throw new TypeError(`${name} must be positive integer or Infinity`);\n  }\n}\n\nfunction assertTtl(ttl: number | undefined): asserts ttl is number {\n  if (ttl === undefined || !isPositiveIntegerOrInfinity(ttl)) {\n    throw new TypeError('ttl must be positive integer or Infinity');\n  }\n}\n\nfunction unrefTimer(timer: TtlCacheTimer): void {\n  if (typeof timer === 'object' && timer !== null && 'unref' in timer) {\n    const unrefableTimer = timer as TtlCacheTimer & { unref?: () => void };\n    unrefableTimer.unref?.();\n  }\n}\n\nconst entryCompare = <K, V>([, left]: [K, TtlCacheEntry<V>], [, right]: [K, TtlCacheEntry<V>]): number => {\n  if (left.expiresAt !== right.expiresAt) {\n    return left.expiresAt - right.expiresAt;\n  }\n\n  return left.sequence - right.sequence;\n};\n\n/**\n * Small in-memory TTL cache tailored to the cache API used by Enbox.\n *\n * Expired entries are purged by an unref'd background timer and are also checked on access. `cancelTimer()` only stops\n * the background timer; `get()` and `has()` still remove stale entries.\n */\nexport class TtlCache<K, V> implements Iterable<[K, V]> {\n  public max: number;\n  public noDisposeOnSet: boolean;\n  public noUpdateTTL: boolean;\n  public ttl?: number;\n  public updateAgeOnGet: boolean;\n\n  private readonly _data = new Map<K, TtlCacheEntry<V>>();\n  private readonly _dispose?: TtlCache.Disposer<K, V>;\n  private _sequence = 0;\n  private _timer?: TtlCacheTimer;\n  private _timerExpiresAt = Infinity;\n\n  public constructor(options: TtlCache.Options<K, V> = {}) {\n    const {\n      dispose,\n      max = Infinity,\n      noDisposeOnSet = false,\n      noUpdateTTL = false,\n      ttl,\n      updateAgeOnGet = false,\n    } = options;\n\n    if (ttl !== undefined) {\n      assertPositiveIntegerOrInfinity(ttl, 'ttl');\n    }\n\n    assertPositiveIntegerOrInfinity(max, 'max');\n\n    if (dispose !== undefined && typeof dispose !== 'function') {\n      throw new TypeError('dispose must be function if set');\n    }\n\n    this.max = max;\n    this.noDisposeOnSet = noDisposeOnSet;\n    this.noUpdateTTL = noUpdateTTL;\n    this.ttl = ttl;\n    this.updateAgeOnGet = updateAgeOnGet;\n    this._dispose = dispose;\n  }\n\n  /**\n   * Total entries currently held in the cache.\n   */\n  public get size(): number {\n    return this._data.size;\n  }\n\n  /**\n   * Store a value and assign the configured TTL.\n   */\n  public set(key: K, value: V, options: TtlCache.SetOptions = {}): this {\n    const ttl = options.ttl ?? this.ttl;\n    assertTtl(ttl);\n\n    const existing = this._data.get(key);\n    const noUpdateTTL = options.noUpdateTTL ?? this.noUpdateTTL;\n    const noDisposeOnSet = options.noDisposeOnSet ?? this.noDisposeOnSet;\n\n    if (existing !== undefined && this._isExpired(existing)) {\n      this._delete(key, 'stale');\n    }\n\n    const current = this._data.get(key);\n    const expiresAt = current !== undefined && noUpdateTTL ? current.expiresAt : this._expirationFromTtl(ttl);\n    const sequence = current !== undefined && noUpdateTTL ? current.sequence : ++this._sequence;\n    const shouldDispose = current !== undefined && current.value !== value && !noDisposeOnSet;\n\n    this._data.set(key, { expiresAt, sequence, value });\n    this._scheduleTimer(expiresAt);\n\n    if (shouldDispose) {\n      this._dispose?.(current.value, key, 'set');\n    }\n\n    this._purgeToCapacity();\n\n    return this;\n  }\n\n  /**\n   * Retrieve a cached value, optionally extending the entry age.\n   */\n  public get<T = V>(key: K, options: TtlCache.GetOptions = {}): T | undefined {\n    const entry = this._data.get(key);\n\n    if (entry === undefined) {\n      return undefined;\n    }\n\n    if (this._isExpired(entry)) {\n      this._delete(key, 'stale');\n      return undefined;\n    }\n\n    const updateAgeOnGet = options.updateAgeOnGet ?? this.updateAgeOnGet;\n\n    if (updateAgeOnGet) {\n      const ttl = options.ttl ?? this.ttl;\n\n      if (ttl !== undefined) {\n        assertTtl(ttl);\n        entry.expiresAt = this._expirationFromTtl(ttl);\n        entry.sequence = ++this._sequence;\n        this._scheduleTimer(entry.expiresAt);\n      }\n    }\n\n    return entry.value as unknown as T;\n  }\n\n  /**\n   * Check whether a live value exists for the given key.\n   */\n  public has(key: K): boolean {\n    const entry = this._data.get(key);\n\n    if (entry === undefined) {\n      return false;\n    }\n\n    if (this._isExpired(entry)) {\n      this._delete(key, 'stale');\n      return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Delete a cache entry.\n   */\n  public delete(key: K): boolean {\n    return this._delete(key, 'delete');\n  }\n\n  /**\n   * Clear all cache entries.\n   */\n  public clear(): void {\n    const entries = [...this._data.entries()];\n    this._data.clear();\n    this.cancelTimer();\n\n    for (const [key, entry] of entries) {\n      this._dispose?.(entry.value, key, 'delete');\n    }\n  }\n\n  /**\n   * Remove expired entries.\n   */\n  public purgeStale(): boolean {\n    const hadTimer = this._timer !== undefined;\n    const purged = this._purgeStale();\n\n    if (purged && hadTimer) {\n      this.cancelTimer();\n      this._scheduleNextTimer();\n    }\n\n    return purged;\n  }\n\n  /**\n   * Return the remaining TTL for a live entry.\n   */\n  public getRemainingTTL(key: K): number {\n    const entry = this._data.get(key);\n\n    if (entry === undefined) {\n      return 0;\n    }\n\n    if (entry.expiresAt === Infinity) {\n      return Infinity;\n    }\n\n    const remainingTtl = Math.ceil(entry.expiresAt - now());\n\n    if (remainingTtl <= 0) {\n      this._delete(key, 'stale');\n      return 0;\n    }\n\n    return remainingTtl;\n  }\n\n  /**\n   * Set a new TTL for an existing entry.\n   */\n  public setTTL(key: K, ttl: number | undefined = this.ttl): void {\n    assertTtl(ttl);\n\n    const entry = this._data.get(key);\n\n    if (entry === undefined) {\n      return;\n    }\n\n    if (this._isExpired(entry)) {\n      this._delete(key, 'stale');\n      return;\n    }\n\n    entry.expiresAt = this._expirationFromTtl(ttl);\n    entry.sequence = ++this._sequence;\n    this._scheduleTimer(entry.expiresAt);\n  }\n\n  /**\n   * Iterate over live entries from soonest to latest expiration.\n   */\n  public *entries(): Generator<[K, V]> {\n    this.purgeStale();\n\n    for (const [key, entry] of this._sortedEntries()) {\n      yield [key, entry.value];\n    }\n  }\n\n  /**\n   * Iterate over live keys from soonest to latest expiration.\n   */\n  public *keys(): Generator<K> {\n    for (const [key] of this.entries()) {\n      yield key;\n    }\n  }\n\n  /**\n   * Iterate over live values from soonest to latest expiration.\n   */\n  public *values(): Generator<V> {\n    for (const [, value] of this.entries()) {\n      yield value;\n    }\n  }\n\n  /**\n   * Cancel the background purge timer. Lazy expiry checks still run on access.\n   */\n  public cancelTimer(): void {\n    if (this._timer !== undefined) {\n      clearTimeout(this._timer);\n      this._timer = undefined;\n      this._timerExpiresAt = Infinity;\n    }\n  }\n\n  public [Symbol.iterator](): Iterator<[K, V]> {\n    return this.entries();\n  }\n\n  private _expirationFromTtl(ttl: number): number {\n    return ttl === Infinity ? Infinity : now() + ttl;\n  }\n\n  private _isExpired(entry: TtlCacheEntry<V>, currentTime: number = now()): boolean {\n    return entry.expiresAt !== Infinity && currentTime >= entry.expiresAt;\n  }\n\n  private _purgeToCapacity(): void {\n    if (this.max === Infinity || this._data.size <= this.max) {\n      return;\n    }\n\n    const hadTimer = this._timer !== undefined;\n    const purgeState = { purgedStale: false };\n\n    try {\n      while (this._data.size > this.max) {\n        const evictCandidate = this._purgeStaleAndSelectEviction(purgeState);\n\n        if (this._data.size <= this.max || evictCandidate === undefined) {\n          return;\n        }\n\n        const currentEntry = this._data.get(evictCandidate.key);\n\n        if (\n          currentEntry !== evictCandidate.entry ||\n          currentEntry.expiresAt !== evictCandidate.expiresAt ||\n          currentEntry.sequence !== evictCandidate.sequence\n        ) {\n          continue;\n        }\n\n        this._delete(evictCandidate.key, 'evict');\n      }\n    } finally {\n      if (purgeState.purgedStale && hadTimer) {\n        this.cancelTimer();\n        this._scheduleNextTimer();\n      }\n    }\n  }\n\n  private _purgeStaleAndSelectEviction(purgeState: TtlCachePurgeState): TtlCacheEvictionCandidate<K, V> | undefined {\n    const currentTime = now();\n    let evictKey: K | undefined;\n    let evictEntry: TtlCacheEntry<V> | undefined;\n    let evictExpiresAt: number | undefined;\n    let evictSequence: number | undefined;\n\n    for (const [key, entry] of this._data.entries()) {\n      if (this._isExpired(entry, currentTime)) {\n        purgeState.purgedStale = true;\n        this._delete(key, 'stale');\n        continue;\n      }\n\n      if (this._isEarlierEntry(entry, evictExpiresAt, evictSequence)) {\n        evictKey = key;\n        evictEntry = entry;\n        evictExpiresAt = entry.expiresAt;\n        evictSequence = entry.sequence;\n      }\n    }\n\n    if (evictKey === undefined || evictEntry === undefined || evictExpiresAt === undefined || evictSequence === undefined) {\n      return undefined;\n    }\n\n    return { entry: evictEntry, expiresAt: evictExpiresAt, key: evictKey, sequence: evictSequence };\n  }\n\n  private _isEarlierEntry(entry: TtlCacheEntry<V>, selectedExpiresAt: number | undefined, selectedSequence: number | undefined): boolean {\n    if (selectedExpiresAt === undefined || selectedSequence === undefined) {\n      return true;\n    }\n\n    if (entry.expiresAt !== selectedExpiresAt) {\n      return entry.expiresAt < selectedExpiresAt;\n    }\n\n    return entry.sequence < selectedSequence;\n  }\n\n  private _purgeStale(): boolean {\n    const currentTime = now();\n    let purged = false;\n\n    for (const [key, entry] of this._data.entries()) {\n      if (this._isExpired(entry, currentTime)) {\n        this._delete(key, 'stale');\n        purged = true;\n      }\n    }\n\n    return purged;\n  }\n\n  private _sortedEntries(): [K, TtlCacheEntry<V>][] {\n    return [...this._data.entries()].sort(entryCompare);\n  }\n\n  private _delete(key: K, reason: TtlCache.DisposeReason): boolean {\n    const entry = this._data.get(key);\n\n    if (entry === undefined) {\n      return false;\n    }\n\n    this._data.delete(key);\n\n    if (this._data.size === 0) {\n      this.cancelTimer();\n    }\n\n    this._dispose?.(entry.value, key, reason);\n\n    return true;\n  }\n\n  private _scheduleTimer(expiresAt: number): void {\n    if (expiresAt === Infinity || expiresAt >= this._timerExpiresAt) {\n      return;\n    }\n\n    this.cancelTimer();\n\n    const delay = Math.min(MAX_TIMER_DELAY_MS, Math.max(0, Math.ceil(expiresAt - now())));\n    const timer = setTimeout((): void => {\n      this._timer = undefined;\n      this._timerExpiresAt = Infinity;\n\n      try {\n        this._purgeStale();\n      } finally {\n        this._scheduleNextTimer();\n      }\n    }, delay);\n\n    unrefTimer(timer);\n\n    this._timer = timer;\n    this._timerExpiresAt = expiresAt;\n  }\n\n  private _scheduleNextTimer(): void {\n    let nextExpiration = Infinity;\n\n    for (const entry of this._data.values()) {\n      if (entry.expiresAt < nextExpiration) {\n        nextExpiration = entry.expiresAt;\n      }\n    }\n\n    this._scheduleTimer(nextExpiration);\n  }\n}\n\nexport namespace TtlCache {\n  export type DisposeReason = 'evict' | 'set' | 'delete' | 'stale';\n\n  export type Disposer<K, V> = (value: V, key: K, reason: DisposeReason) => void;\n\n  export type TTLOptions = {\n    noUpdateTTL?: boolean;\n    ttl?: number;\n  };\n\n  export type Options<K, V> = TTLOptions & {\n    dispose?: Disposer<K, V>;\n    max?: number;\n    noDisposeOnSet?: boolean;\n    updateAgeOnGet?: boolean;\n  };\n\n  export type SetOptions = {\n    noDisposeOnSet?: boolean;\n    noUpdateTTL?: boolean;\n    ttl?: number;\n  };\n\n  export type GetOptions = {\n    ttl?: number;\n    updateAgeOnGet?: boolean;\n  };\n}\n", "function compareUtf16(left: string, right: string): number {\n  if (left === right) {\n    return 0;\n  }\n  return left < right ? -1 : 1;\n}\n\n/**\n * Recursively canonicalizes a JSON-compatible value into a deterministic\n * shape: object keys are sorted by UTF-16 code unit and entries with\n * `undefined` values are dropped, matching `JSON.stringify` object semantics.\n * Returns a new value; the input is not mutated.\n */\nexport function canonicalizeJson(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map(canonicalizeJson);\n  }\n\n  if (value !== null && typeof value === 'object') {\n    const object = value as Record<string, unknown>;\n    const canonical: Record<string, unknown> = {};\n    for (const key of Object.keys(object).sort(compareUtf16)) {\n      const entry = object[key];\n      if (entry === undefined) {\n        continue;\n      }\n      canonical[key] = canonicalizeJson(entry);\n    }\n    return canonical;\n  }\n\n  return value;\n}\n\n/**\n * Deterministic JSON serialization with recursively sorted object keys.\n * Equality of the output strings is equivalent to deep JSON equality of the\n * inputs, regardless of key insertion order.\n */\nexport function canonicalJsonStringify(value: unknown): string {\n  return JSON.stringify(canonicalizeJson(value));\n}\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n  return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array<ArrayBuffer> {\n  const hexes = hex.match(/../g)\n  return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n  if (aa === bb) { return true }\n  if (aa.byteLength !== bb.byteLength) {\n    return false\n  }\n\n  for (let ii = 0; ii < aa.byteLength; ii++) {\n    if (aa[ii] !== bb[ii]) {\n      return false\n    }\n  }\n\n  return true\n}\n\n/**\n * Normalize binary input to a plain `Uint8Array` backed by an `ArrayBuffer`.\n *\n * Returns the input itself when it is already a plain `Uint8Array` over an\n * `ArrayBuffer`, otherwise a fresh view (or, for `SharedArrayBuffer`-backed\n * input, a copy) over the same bytes.\n *\n * Throws if input is not a recognised binary type.\n */\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array<ArrayBuffer> {\n  if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {\n    return toArrayBufferBackedArray(o)\n  }\n  if (o instanceof ArrayBuffer) {\n    return new Uint8Array(o)\n  }\n  if (ArrayBuffer.isView(o)) {\n    return toArrayBufferBackedArray(new Uint8Array(o.buffer, o.byteOffset, o.byteLength))\n  }\n  throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n  return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\n/**\n * Convert the passed string into a byte array, constraining each character\n * value to a single byte\n */\nexport function fromString (str: string): Uint8Array<ArrayBuffer> {\n  const output = new Uint8Array(str.length)\n\n  for (let i = 0; i < str.length; i++) {\n    output[i] = str.charCodeAt(i)\n  }\n\n  return output\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\n/**\n * Convert the passed byte array to a string, interpreting each byte as a single\n * character\n */\nexport function toString (b: Uint8Array): string {\n  const len = b.length\n\n  if (len <= MAX_ARGUMENTS_LENGTH) {\n    // @ts-expect-error cannot ordinarily apply a Uint8Array\n    return String.fromCharCode.apply(String, b) // avoid extra subarray()\n  }\n\n  // Decode in chunks to avoid \"call stack size exceeded\".\n  let res = ''\n  let i = 0\n  while (i < len) {\n    res += String.fromCharCode.apply(\n      String,\n      // @ts-expect-error cannot ordinarily apply a Uint8Array\n      b.subarray(i, i += MAX_ARGUMENTS_LENGTH)\n    )\n  }\n  return res\n}\n\nfunction isByteArrayWithArrayBuffer (b?: Uint8Array): b is Uint8Array<ArrayBuffer> {\n  return b?.buffer instanceof ArrayBuffer\n}\n\n/**\n * Ensures `b` is backed by an ArrayBuffer - if not a new Uint8Array will be\n * created and the contents of `b` copied into it.\n */\nexport function toArrayBufferBackedArray (b: Uint8Array): Uint8Array<ArrayBuffer> {\n  if (isByteArrayWithArrayBuffer(b)) {\n    return b\n  }\n\n  return b.slice()\n}\n", "/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n * @param {boolean} [caseInsensitive]\n */\nfunction base (ALPHABET, name, caseInsensitive) {\n  if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n  var BASE_MAP = new Uint8Array(256);\n  for (var j = 0; j < BASE_MAP.length; j++) {\n    BASE_MAP[j] = 255;\n  }\n  for (var i = 0; i < ALPHABET.length; i++) {\n    var x = ALPHABET.charAt(i);\n    var xc = x.charCodeAt(0);\n    if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n    BASE_MAP[xc] = i;\n    // For case-insensitive codecs, map the opposite case to the same index so\n    // differently cased input decodes without errors (multibase spec).\n    if (caseInsensitive) {\n      var xl = x.toLowerCase().charCodeAt(0);\n      var xu = x.toUpperCase().charCodeAt(0);\n      if (xl !== xc) { BASE_MAP[xl] = i; }\n      if (xu !== xc) { BASE_MAP[xu] = i; }\n    }\n  }\n  var BASE = ALPHABET.length;\n  var LEADER = ALPHABET.charAt(0);\n  var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n  var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n  /**\n   * @param {any[] | Iterable<number>} source\n   */\n  function encode (source) {\n    // @ts-ignore\n    if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n      source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n    } else if (Array.isArray(source)) {\n      source = Uint8Array.from(source);\n    }\n    if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n    if (source.length === 0) { return '' }\n        // Skip & count leading zeroes.\n    var zeroes = 0;\n    var length = 0;\n    var pbegin = 0;\n    var pend = source.length;\n    while (pbegin !== pend && source[pbegin] === 0) {\n      pbegin++;\n      zeroes++;\n    }\n        // Allocate enough space in big-endian base58 representation.\n    var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n    var b58 = new Uint8Array(size);\n        // Process the bytes.\n    while (pbegin !== pend) {\n      var carry = source[pbegin];\n            // Apply \"b58 = b58 * 256 + ch\".\n      var i = 0;\n      for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n        carry += (256 * b58[it1]) >>> 0;\n        b58[it1] = (carry % BASE) >>> 0;\n        carry = (carry / BASE) >>> 0;\n      }\n      if (carry !== 0) { throw new Error('Non-zero carry') }\n      length = i;\n      pbegin++;\n    }\n        // Skip leading zeroes in base58 result.\n    var it2 = size - length;\n    while (it2 !== size && b58[it2] === 0) {\n      it2++;\n    }\n        // Translate the result into a string.\n    var str = LEADER.repeat(zeroes);\n    for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n    return str\n  }\n  /**\n   * @param {string | string[]} source\n   */\n  function decodeUnsafe (source) {\n    if (typeof source !== 'string') { throw new TypeError('Expected String') }\n    if (source.length === 0) { return new Uint8Array() }\n    var psz = 0;\n        // Skip leading spaces.\n    if (source[psz] === ' ') { return }\n        // Skip and count leading '1's.\n    var zeroes = 0;\n    var length = 0;\n    while (source[psz] === LEADER) {\n      zeroes++;\n      psz++;\n    }\n        // Allocate enough space in big-endian base256 representation.\n    var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n    var b256 = new Uint8Array(size);\n        // Process the characters.\n    while (source[psz]) {\n            // Decode character\n      var carry = BASE_MAP[source.charCodeAt(psz)];\n            // Invalid character\n      if (carry === 255) { return }\n      var i = 0;\n      for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n        carry += (BASE * b256[it3]) >>> 0;\n        b256[it3] = (carry % 256) >>> 0;\n        carry = (carry / 256) >>> 0;\n      }\n      if (carry !== 0) { throw new Error('Non-zero carry') }\n      length = i;\n      psz++;\n    }\n        // Skip trailing spaces.\n    if (source[psz] === ' ') { return }\n        // Skip leading zeroes in b256.\n    var it4 = size - length;\n    while (it4 !== size && b256[it4] === 0) {\n      it4++;\n    }\n    var vch = new Uint8Array(zeroes + (size - it4));\n    var j = zeroes;\n    while (it4 !== size) {\n      vch[j++] = b256[it4++];\n    }\n    return vch\n  }\n  /**\n   * @param {string | string[]} string\n   */\n  function decode (string) {\n    var buffer = decodeUnsafe(string);\n    if (buffer) { return buffer }\n    throw new Error(`Non-${name} character`)\n  }\n  return {\n    encode: encode,\n    decodeUnsafe: decodeUnsafe,\n    decode: decode\n  }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.ts'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.ts'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array<ArrayBuffer> }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n  readonly name: Base\n  readonly prefix: Prefix\n  readonly baseEncode: EncodeFn\n\n  constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n    this.name = name\n    this.prefix = prefix\n    this.baseEncode = baseEncode\n  }\n\n  encode (bytes: Uint8Array): Multibase<Prefix> {\n    if (bytes instanceof Uint8Array) {\n      return `${this.prefix}${this.baseEncode(bytes)}`\n    } else {\n      throw Error('Unknown type, must be binary type')\n    }\n  }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n  readonly name: Base\n  readonly prefix: Prefix\n  readonly baseDecode: DecodeFn\n  private readonly prefixCodePoint: number\n\n  constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n    this.name = name\n    this.prefix = prefix\n    const prefixCodePoint = prefix.codePointAt(0)\n    /* c8 ignore next 3 */\n    if (prefixCodePoint === undefined) {\n      throw new Error('Invalid prefix character')\n    }\n    this.prefixCodePoint = prefixCodePoint\n    this.baseDecode = baseDecode\n  }\n\n  decode (text: string): Uint8Array<ArrayBuffer> {\n    if (typeof text === 'string') {\n      if (text.codePointAt(0) !== this.prefixCodePoint) {\n        throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n      }\n      return this.baseDecode(text.slice(this.prefix.length))\n    } else {\n      throw Error('Can only multibase decode strings')\n    }\n  }\n\n  or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n    return or(this, decoder)\n  }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n  readonly decoders: Decoders<Prefix>\n\n  constructor (decoders: Decoders<Prefix>) {\n    this.decoders = decoders\n  }\n\n  or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n    return or(this, decoder)\n  }\n\n  decode (input: string): Uint8Array<ArrayBuffer> {\n    const prefix = input[0] as Prefix\n    const decoder = this.decoders[prefix]\n    if (decoder != null) {\n      return decoder.decode(input)\n    } else {\n      throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n    }\n  }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n  return new ComposedDecoder({\n    ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n    ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n  } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n  readonly name: Base\n  readonly prefix: Prefix\n  readonly baseEncode: EncodeFn\n  readonly baseDecode: DecodeFn\n  readonly encoder: Encoder<Base, Prefix>\n  readonly decoder: Decoder<Base, Prefix>\n\n  constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n    this.name = name\n    this.prefix = prefix\n    this.baseEncode = baseEncode\n    this.baseDecode = baseDecode\n    this.encoder = new Encoder(name, prefix, baseEncode)\n    this.decoder = new Decoder(name, prefix, baseDecode)\n  }\n\n  encode (input: Uint8Array): string {\n    return this.encoder.encode(input)\n  }\n\n  decode (input: string): Uint8Array<ArrayBuffer> {\n    return this.decoder.decode(input)\n  }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n  return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet, caseInsensitive = false }: { name: Base, prefix: Prefix, alphabet: string, caseInsensitive?: boolean }): Codec<Base, Prefix> {\n  const { encode, decode } = basex(alphabet, name, caseInsensitive)\n  return from({\n    prefix,\n    name,\n    encode,\n    decode: (text: string): Uint8Array<ArrayBuffer> => coerce(decode(text))\n  })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array<ArrayBuffer> {\n  // Count the padding bytes:\n  let end = string.length\n  while (string[end - 1] === '=') {\n    --end\n  }\n\n  // Allocate the output:\n  const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n  // Parse the data:\n  let bits = 0 // Number of bits currently in the buffer\n  let buffer = 0 // Bits waiting to be written out, MSB first\n  let written = 0 // Next byte to write\n  for (let i = 0; i < end; ++i) {\n    // Read one character from the string:\n    const value = alphabetIdx[string[i]]\n    if (value === undefined) {\n      throw new SyntaxError(`Non-${name} character`)\n    }\n\n    // Append the bits to the buffer:\n    buffer = (buffer << bitsPerChar) | value\n    bits += bitsPerChar\n\n    // Write out some bits if the buffer has a byte's worth:\n    if (bits >= 8) {\n      bits -= 8\n      out[written++] = 0xff & (buffer >> bits)\n    }\n  }\n\n  // Verify that we have received just enough bits:\n  if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n    throw new SyntaxError('Unexpected end of data')\n  }\n\n  return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n  const pad = alphabet[alphabet.length - 1] === '='\n  const mask = (1 << bitsPerChar) - 1\n  let out = ''\n\n  let bits = 0 // Number of bits currently in the buffer\n  let buffer = 0 // Bits waiting to be written out, MSB first\n  for (let i = 0; i < data.length; ++i) {\n    // Slurp data into the buffer:\n    buffer = (buffer << 8) | data[i]\n    bits += 8\n\n    // Write out as much as we can:\n    while (bits > bitsPerChar) {\n      bits -= bitsPerChar\n      out += alphabet[mask & (buffer >> bits)]\n    }\n  }\n\n  // Partial character:\n  if (bits !== 0) {\n    out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n  }\n\n  // Add padding characters until we hit a byte boundary:\n  if (pad) {\n    while (((out.length * bitsPerChar) & 7) !== 0) {\n      out += '='\n    }\n  }\n\n  return out\n}\n\nfunction createAlphabetIdx (alphabet: string, caseInsensitive: boolean): Record<string, number> {\n  // Build the character lookup table:\n  const alphabetIdx: Record<string, number> = {}\n  for (let i = 0; i < alphabet.length; ++i) {\n    alphabetIdx[alphabet[i]] = i\n    // For case-insensitive codecs, map the opposite case to the same index so\n    // differently cased input decodes without errors (multibase spec).\n    if (caseInsensitive) {\n      const lower = alphabet[i].toLowerCase()\n      const upper = alphabet[i].toUpperCase()\n      if (lower !== alphabet[i]) {\n        alphabetIdx[lower] = i\n      }\n      if (upper !== alphabet[i]) {\n        alphabetIdx[upper] = i\n      }\n    }\n  }\n  return alphabetIdx\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet, caseInsensitive = false }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string, caseInsensitive?: boolean }): Codec<Base, Prefix> {\n  const alphabetIdx = createAlphabetIdx(alphabet, caseInsensitive)\n  return from({\n    prefix,\n    name,\n    encode (input: Uint8Array): string {\n      return encode(input, alphabet, bitsPerChar)\n    },\n    decode (input: string): Uint8Array<ArrayBuffer> {\n      return decode(input, alphabetIdx, bitsPerChar, name)\n    }\n  })\n}\n", "import { rfc4648 } from './base.ts'\n\nexport const base32 = rfc4648({\n  prefix: 'b',\n  name: 'base32',\n  alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32upper = rfc4648({\n  prefix: 'B',\n  name: 'base32upper',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32pad = rfc4648({\n  prefix: 'c',\n  name: 'base32pad',\n  alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32padupper = rfc4648({\n  prefix: 'C',\n  name: 'base32padupper',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32hex = rfc4648({\n  prefix: 'v',\n  name: 'base32hex',\n  alphabet: '0123456789abcdefghijklmnopqrstuv',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32hexupper = rfc4648({\n  prefix: 'V',\n  name: 'base32hexupper',\n  alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32hexpad = rfc4648({\n  prefix: 't',\n  name: 'base32hexpad',\n  alphabet: '0123456789abcdefghijklmnopqrstuv=',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32hexpadupper = rfc4648({\n  prefix: 'T',\n  name: 'base32hexpadupper',\n  alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n  bitsPerChar: 5,\n  caseInsensitive: true\n})\n\nexport const base32z = rfc4648({\n  prefix: 'h',\n  name: 'base32z',\n  alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n  bitsPerChar: 5\n})\n", "import { baseX } from './base.ts'\n\nexport const base58btc = baseX({\n  name: 'base58btc',\n  prefix: 'z',\n  alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n  name: 'base58flickr',\n  prefix: 'Z',\n  alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "import { rfc4648 } from './base.ts'\n\nexport const base64 = rfc4648({\n  prefix: 'm',\n  name: 'base64',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n  bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n  prefix: 'M',\n  name: 'base64pad',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n  bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n  prefix: 'u',\n  name: 'base64url',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n  bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n  prefix: 'U',\n  name: 'base64urlpad',\n  alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n  bitsPerChar: 6\n})\n", "/**\n * Represents an array of a fixed length, preventing modifications to its size.\n *\n * The `FixedLengthArray` utility type transforms a standard array into a variant where\n * methods that could alter the length are omitted. It leverages TypeScript's advanced types,\n * such as conditional types and mapped types, to ensure that the array cannot be resized\n * through methods like `push`, `pop`, `splice`, `shift`, and `unshift`. The utility type\n * maintains all other characteristics of a standard array, including indexing, iteration,\n * and type checking for its elements.\n *\n * Note: The type does not prevent direct assignment to indices, even if it would exceed\n * the original length. However, such actions would lead to TypeScript type errors.\n *\n * @example\n * ```ts\n * // Declare a variable with a type of fixed-length array of three strings.\n * let myFixedLengthArray: FixedLengthArray< [string, string, string]>;\n *\n * // Array declaration tests\n * myFixedLengthArray = [ 'a', 'b', 'c' ];  // OK\n * myFixedLengthArray = [ 'a', 'b', 123 ];  // TYPE ERROR\n * myFixedLengthArray = [ 'a' ];            // LENGTH ERROR\n * myFixedLengthArray = [ 'a', 'b' ];       // LENGTH ERROR\n *\n * // Index assignment tests\n * myFixedLengthArray[1] = 'foo';           // OK\n * myFixedLengthArray[1000] = 'foo';        // INVALID INDEX ERROR\n *\n * // Methods that mutate array length\n * myFixedLengthArray.push('foo');          // MISSING METHOD ERROR\n * myFixedLengthArray.pop();                // MISSING METHOD ERROR\n *\n * // Direct length manipulation\n * myFixedLengthArray.length = 123;         // READ-ONLY ERROR\n *\n * // Destructuring\n * let [ a ] = myFixedLengthArray;          // OK\n * let [ a, b ] = myFixedLengthArray;       // OK\n * let [ a, b, c ] = myFixedLengthArray;    // OK\n * let [ a, b, c, d ] = myFixedLengthArray; // INVALID INDEX ERROR\n * ```\n *\n * @template T extends any[] - The array type to be transformed.\n */\nexport type FixedLengthArray<T extends any[]> =\n  Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>\n  & {\n    /**\n     * Custom iterator for the `FixedLengthArray` type.\n     *\n     * This iterator allows the `FixedLengthArray` to be used in standard iteration\n     * contexts, such as `for...of` loops and spread syntax. It ensures that even though\n     * the array is of a fixed length with disabled mutation methods, it still retains\n     * iterable behavior similar to a regular array.\n     *\n     * @returns An IterableIterator for the array items.\n     */\n    [Symbol.iterator]: () => IterableIterator<ArrayItems<T>>\n  };\n\n/** Helper types for {@link FixedLengthArray} */\ntype ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number;\ntype ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never;\n\n/**\n * isArrayBufferSlice\n *\n * Checks if the ArrayBufferView represents a slice (subarray or a subview)\n * of an ArrayBuffer.\n *\n * An ArrayBufferView (TypedArray or DataView) can represent a portion of an\n * ArrayBuffer - such a view is said to be a \"slice\" of the original buffer.\n * This can occur when the `subarray` or `slice` method is called on a\n * TypedArray or when a DataView is created with a byteOffset and/or\n * byteLength that doesn't cover the full ArrayBuffer.\n *\n * @param arrayBufferView - The ArrayBufferView to be checked\n * @returns true if the ArrayBufferView represents a slice of an ArrayBuffer; false otherwise.\n */\nexport function isArrayBufferSlice(arrayBufferView: ArrayBufferView): boolean {\n  return arrayBufferView.byteOffset !== 0 || arrayBufferView.byteLength !== arrayBufferView.buffer.byteLength;\n}\n\n/**\n * Checks if the given object is an AsyncIterable.\n *\n * An AsyncIterable is an object that implements the AsyncIterable protocol,\n * which means it has a [Symbol.asyncIterator] method. This function checks\n * if the provided object conforms to this protocol by verifying the presence\n * and type of the [Symbol.asyncIterator] method.\n *\n * @param obj - The object to be checked for AsyncIterable conformity.\n * @returns True if the object is an AsyncIterable, false otherwise.\n *\n * @example\n * ```ts\n * // Returns true for a valid AsyncIterable\n * const asyncIterable = {\n *   async *[Symbol.asyncIterator]() {\n *     yield 1;\n *     yield 2;\n *   }\n * };\n * console.log(isAsyncIterable(asyncIterable)); // true\n * ```\n *\n * @example\n * ```ts\n * // Returns false for a regular object\n * console.log(isAsyncIterable({ a: 1, b: 2 })); // false\n * ```\n */\nexport function isAsyncIterable(obj: any): obj is AsyncIterable<any> {\n  if (typeof obj !== 'object' || obj === null) {\n    return false;\n  }\n\n  return typeof obj[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * isDefined\n *\n * Utility function to check if a variable is neither null nor undefined.\n * This function helps in making TypeScript infer the type of the variable\n * as being defined, excluding `null` and `undefined`.\n *\n * The function uses strict equality (`!==`) for the comparison, ensuring\n * that the variable is not just falsy (like an empty string or zero),\n * but is truly either `null` or `undefined`.\n *\n * @param arg - The variable to be checked\n * @returns true if the variable is neither `null` nor `undefined`\n */\nexport function isDefined<T>(arg: T): arg is Exclude<T, null | undefined> {\n  return arg !== null && arg !== undefined;\n}\n\n/**\n * Utility type that transforms a type `T` to have only certain keys `K` as required, while the\n * rest remain optional, except for keys specified in `O`, which are omitted entirely.\n *\n * This type is useful when you need a variation of a type where only specific properties are\n * required, and others are either optional or not included at all. It allows for more flexible type\n * definitions based on existing types without the need to redefine them.\n *\n * @template T - The original type to be transformed.\n * @template K - The keys of `T` that should be required.\n * @template O - The keys of `T` that should be omitted from the resulting type (optional).\n *\n * @example\n * ```ts\n * // Given an interface\n * interface Example {\n *   requiredProp: string;\n *   optionalProp?: number;\n *   anotherOptionalProp?: boolean;\n * }\n *\n * // Making 'optionalProp' required and omitting 'anotherOptionalProp'\n * type ModifiedExample = RequireOnly<Example, 'optionalProp', 'anotherOptionalProp'>;\n * // Result: { requiredProp?: string; optionalProp: number; }\n * ```\n */\nexport type RequireOnly<T, K extends keyof T, O extends keyof T = never> = Required<Pick<T, K>> & Omit<Partial<T>, O>;\n\n/**\n * universalTypeOf\n *\n * Why does this function exist?\n *\n * You can typically check if a value is of a particular type, such as\n * Uint8Array or ArrayBuffer, by using the `instanceof` operator. The\n * `instanceof` operator checks the prototype property of a constructor\n * in the object's prototype chain.\n *\n * However, there is a caveat with the `instanceof` check if the value\n * was created from a different JavaScript context (like an iframe or\n * a web worker). In those cases, the `instanceof` check might fail\n * because each context has a different global object, and therefore,\n * different built-in constructor functions.\n *\n * The `typeof` operator provides information about the type of the\n * operand in a less detailed way. For basic data types like number,\n * string, boolean, and undefined, the `typeof` operator works as\n * expected.  However, for objects, including arrays and null,\n * it always returns \"object\".  For functions, it returns \"function\".\n * So, while `typeof` is good for basic type checking, it doesn't\n * give detailed information about complex data types.\n *\n * Unlike `instanceof` and `typeof`, `Object.prototype.toString.call(value)`\n * can ensure a consistent result across different JavaScript\n * contexts.\n *\n * Credit for inspiration:\n *   Angus Croll\n *   https://github.com/angus-c\n *   https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/\n */\nexport function universalTypeOf(value: unknown): string {\n  // Returns '[Object Type]' string.\n  const typeString = Object.prototype.toString.call(value);\n  // Returns ['Object', 'Type'] array or null.\n  const match = /\\s([a-zA-Z0-9]+)/.exec(typeString);\n  // Deconstructs the array and gets just the type from index 1.\n  const [_, type] = match as RegExpExecArray;\n\n  return type;\n}\n\n/**\n * Utility type to extract the type resolved by a Promise.\n *\n * This type unwraps the type `T` from `Promise<T>` if `T` is a Promise, otherwise returns `T` as\n * is. It's useful in situations where you need to handle the type returned by a promise-based\n * function in a synchronous context, such as defining types for test vectors or handling return\n * types in non-async code blocks.\n *\n * @template T - The type to unwrap from the Promise.\n *\n * @example\n * ```ts\n * // For a Promise type, it extracts the resolved type.\n * type AsyncNumber = Promise<number>;\n * type UnwrappedNumber = UnwrapPromise<AsyncNumber>; // number\n *\n * // For a non-Promise type, it returns the type as is.\n * type StringValue = string;\n * type UnwrappedString = UnwrapPromise<StringValue>; // string\n * ```\n */\nexport type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;", "import type { Multibase } from 'multiformats';\n\nimport { base32z } from 'multiformats/bases/base32';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { base64url } from 'multiformats/bases/base64';\n\nimport { isArrayBufferSlice, isAsyncIterable, universalTypeOf } from './type-utils.js';\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nexport class Convert {\n  data: any;\n  format: string;\n\n  constructor(data: any, format: string) {\n    this.data = data;\n    this.format = format;\n  }\n\n  static arrayBuffer(data: ArrayBuffer): Convert {\n    return new Convert(data, 'ArrayBuffer');\n  }\n\n  static asyncIterable(data: AsyncIterable<any>): Convert {\n    if (!isAsyncIterable(data)) {\n      throw new TypeError('Input must be of type AsyncIterable.');\n    }\n    return new Convert(data, 'AsyncIterable');\n  }\n\n  static base32Z(data: string): Convert {\n    return new Convert(data, 'Base32Z');\n  }\n\n  static base58Btc(data: string): Convert {\n    return new Convert(data, 'Base58Btc');\n  }\n\n  static base64Url(data: string): Convert {\n    return new Convert(data, 'Base64Url');\n  }\n\n  /**\n   * Reference:\n   * The BufferSource type is a TypeScript type that represents an ArrayBuffer\n   * or one of the ArrayBufferView types, such a TypedArray (e.g., Uint8Array)\n   * or a DataView.\n   */\n  static bufferSource(data: BufferSource): Convert {\n    return new Convert(data, 'BufferSource');\n  }\n\n  static hex(data: string): Convert {\n    if (typeof data !== 'string') {\n      throw new TypeError('Hex input must be a string.');\n    }\n    if (data.length % 2 !== 0) {\n      throw new TypeError('Hex input must have an even number of characters.');\n    }\n    return new Convert(data, 'Hex');\n  }\n\n  static multibase(data: string): Convert {\n    return new Convert(data, 'Multibase');\n  }\n\n  static object(data: Record<string, any>): Convert {\n    return new Convert(data, 'Object');\n  }\n\n  static string(data: string): Convert {\n    return new Convert(data, 'String');\n  }\n\n  static uint8Array(data: Uint8Array): Convert {\n    return new Convert(data, 'Uint8Array');\n  }\n\n  toArrayBuffer(): ArrayBuffer {\n    switch (this.format) {\n\n      case 'Base58Btc': {\n        return base58btc.baseDecode(this.data).buffer as ArrayBuffer;\n      }\n\n      case 'Base64Url': {\n        return base64url.baseDecode(this.data).buffer as ArrayBuffer;\n      }\n\n      case 'BufferSource': {\n        const dataType = universalTypeOf(this.data);\n        if (dataType === 'ArrayBuffer') {\n          // Data is already an ArrayBuffer, No conversion is necessary.\n          return this.data;\n        } else if (ArrayBuffer.isView(this.data)) {\n          // Data is a DataView or a different TypedArray (e.g., Uint16Array).\n          if (isArrayBufferSlice(this.data)) {\n            // Data is a slice of an ArrayBuffer. Return a new ArrayBuffer or ArrayBufferView of the same slice.\n            return this.data.buffer.slice(this.data.byteOffset, this.data.byteOffset + this.data.byteLength) as ArrayBuffer;\n          } else {\n            // Data is a whole ArrayBuffer viewed as a different TypedArray or DataView. Return the whole ArrayBuffer.\n            return this.data.buffer as ArrayBuffer;\n          }\n        } else {\n          throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`);\n        }\n      }\n\n      case 'Hex': {\n        return this.toUint8Array().buffer as ArrayBuffer;\n      }\n\n      case 'String': {\n        return this.toUint8Array().buffer as ArrayBuffer;\n      }\n\n      case 'Uint8Array': {\n        return this.data.buffer as ArrayBuffer;\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`);\n    }\n  }\n\n  async toArrayBufferAsync(): Promise<ArrayBuffer> {\n    if (this.format === 'AsyncIterable') {\n      const blob = await this.toBlobAsync();\n      return await blob.arrayBuffer();\n    }\n\n    throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`);\n  }\n\n  toBase32Z(): string {\n    if (this.format === 'Uint8Array') {\n      return base32z.baseEncode(this.data);\n    }\n\n    throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`);\n  }\n\n  toBase58Btc(): string {\n    switch (this.format) {\n\n      case 'ArrayBuffer': {\n        const u8a = new Uint8Array(this.data);\n        return base58btc.baseEncode(u8a);\n      }\n\n      case 'Multibase': {\n        return this.data.substring(1);\n      }\n\n      case 'Uint8Array': {\n        return base58btc.baseEncode(this.data);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`);\n    }\n  }\n\n  toBase64Url(): string {\n    switch (this.format) {\n\n      case 'ArrayBuffer': {\n        const u8a = new Uint8Array(this.data);\n        return base64url.baseEncode(u8a);\n      }\n\n      case 'BufferSource': {\n        const u8a = this.toUint8Array();\n        return base64url.baseEncode(u8a);\n      }\n\n      case 'Object': {\n        const string = JSON.stringify(this.data);\n        const u8a = textEncoder.encode(string);\n        return base64url.baseEncode(u8a);\n      }\n\n      case 'String': {\n        const u8a = textEncoder.encode(this.data);\n        return base64url.baseEncode(u8a);\n      }\n\n      case 'Uint8Array': {\n        return base64url.baseEncode(this.data);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`);\n    }\n  }\n\n  async toBlobAsync(): Promise<Blob> {\n    if (this.format === 'AsyncIterable') {\n      // Initialize an array to hold the chunks from the AsyncIterable.\n      const chunks = [];\n\n      // Asynchronously iterate over each chunk in the AsyncIterable.\n      for await (const chunk of (this.data as AsyncIterable<any>)) {\n        // Append each chunk to the chunks array. These chunks can be of any type, typically binary data or text.\n        chunks.push(chunk);\n      }\n\n      // Create a new Blob from the aggregated chunks.\n      // The Blob constructor combines these chunks into a single Blob object.\n      const blob = new Blob(chunks);\n\n      return blob;\n    }\n\n    throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`);\n  }\n\n  toHex(): string {\n    // pre-calculating Hex values improves runtime by 6-10x.\n    const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\n\n    switch (this.format) {\n\n      case 'ArrayBuffer':\n      case 'Base64Url': {\n        const u8a = this.toUint8Array();\n        return Convert.uint8Array(u8a).toHex();\n      }\n\n      case 'Uint8Array': {\n        let hex = '';\n        for (const byte of this.data) {\n          hex += hexes[byte];\n        }\n        return hex;\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`);\n    }\n  }\n\n  toMultibase(): Multibase<any> {\n    if (this.format === 'Base58Btc') {\n      return `z${this.data}`;\n    }\n\n    throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`);\n  }\n\n  toObject(): object {\n    switch (this.format) {\n\n      case 'Base64Url': {\n        const u8a = base64url.baseDecode(this.data);\n        const text = textDecoder.decode(u8a);\n        return JSON.parse(text);\n      }\n\n      case 'String': {\n        return JSON.parse(this.data);\n      }\n\n      case 'Uint8Array': {\n        const text = textDecoder.decode(this.data);\n        return JSON.parse(text);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Object is not supported.`);\n    }\n  }\n\n  async toObjectAsync<T = unknown>(): Promise<T> {\n    if (this.format === 'AsyncIterable') {\n      // Convert the AsyncIterable to a String.\n      const text = await this.toStringAsync();\n\n      // Parse the string as JSON. This step assumes that the string represents a valid JSON structure.\n      // JSON.parse() will convert the string into a corresponding JavaScript object. The caller\n      // chooses the return type via the `T` type parameter (defaults to `unknown` so callers\n      // must narrow before using the result, instead of `any` silently propagating).\n      const json = JSON.parse(text) as T;\n\n      // Return the parsed JavaScript object. The type of this object will depend on the structure\n      // of the JSON in the stream. It could be an object, array, string, number, etc.\n      return json;\n    }\n\n    throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`);\n  }\n\n  toString(): string {\n    switch (this.format) {\n\n      case 'ArrayBuffer': {\n        return textDecoder.decode(this.data);\n      }\n\n      case 'Base64Url': {\n        const u8a = base64url.baseDecode(this.data);\n        return textDecoder.decode(u8a);\n      }\n\n      case 'Object': {\n        return JSON.stringify(this.data);\n      }\n\n      case 'Uint8Array': {\n        return textDecoder.decode(this.data);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to String is not supported.`);\n    }\n  }\n\n  async toStringAsync(): Promise<string> {\n    if (this.format === 'AsyncIterable') {\n      // Initialize an empty string to accumulate the decoded text.\n      let str = '';\n\n      // Iterate over the chunks from the AsyncIterable.\n      for await (const chunk of (this.data as AsyncIterable<any>)) {\n        // If the chunk is already a string, concatenate it directly.\n        if (typeof chunk === 'string')\n        {str += chunk;}\n        else\n        // If the chunk is a Uint8Array or similar, use the decoder to convert it to a string.\n        // The `stream: true` option lets the decoder handle multi-byte characters spanning\n        // multiple chunks.\n        {str += textDecoder.decode(chunk, { stream: true });}\n      }\n\n      // Finalize the decoding process to handle any remaining bytes and signal the end of the stream.\n      // The `stream: false` option flushes the decoder's internal state.\n      str += textDecoder.decode(undefined, { stream: false });\n\n      // Return the accumulated string.\n      return str;\n    }\n\n    throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`);\n  }\n\n  toUint8Array(): Uint8Array {\n    switch (this.format) {\n\n      case 'ArrayBuffer': {\n        // \u00C7reate Uint8Array as a view on the ArrayBuffer.\n        // Note: The Uint8Array shares the same memory as the ArrayBuffer, so this operation is very efficient.\n        return new Uint8Array(this.data);\n      }\n\n      case 'Base32Z': {\n        return base32z.baseDecode(this.data);\n      }\n\n      case 'Base58Btc': {\n        return base58btc.baseDecode(this.data);\n      }\n\n      case 'Base64Url': {\n        return base64url.baseDecode(this.data);\n      }\n\n      case 'BufferSource': {\n        const dataType = universalTypeOf(this.data);\n        if (dataType === 'Uint8Array') {\n          // Data is already a Uint8Array. No conversion is necessary.\n          // Note: Uint8Array is a type of BufferSource.\n          return this.data;\n        } else if (dataType === 'ArrayBuffer') {\n          // Data is an ArrayBuffer, create Uint8Array as a view on the ArrayBuffer.\n          // Note: The Uint8Array shares the same memory as the ArrayBuffer, so this operation is very efficient.\n          return new Uint8Array(this.data);\n        } else if (ArrayBuffer.isView(this.data)) {\n          // Data is a DataView or a different TypedArray (e.g., Uint16Array).\n          return new Uint8Array(this.data.buffer, this.data.byteOffset, this.data.byteLength);\n        } else {\n          throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`);\n        }\n      }\n\n      case 'Hex': {\n        const u8a = new Uint8Array(this.data.length / 2);\n        for (let i = 0; i < this.data.length; i += 2) {\n          const byteValue = Number.parseInt(this.data.substring(i, i + 2), 16);\n          if (Number.isNaN(byteValue)) {\n            throw new TypeError('Input is not a valid hexadecimal string.');\n          }\n          u8a[i / 2] = byteValue;\n        }\n        return u8a;\n      }\n\n      case 'Object': {\n        const string = JSON.stringify(this.data);\n        return textEncoder.encode(string);\n      }\n\n      case 'String': {\n        return textEncoder.encode(this.data);\n      }\n\n      default:\n        throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`);\n    }\n  }\n\n  async toUint8ArrayAsync(): Promise<Uint8Array> {\n    if (this.format === 'AsyncIterable') {\n      const arrayBuffer = await this.toArrayBufferAsync();\n      return new Uint8Array(arrayBuffer);\n    }\n\n    throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`);\n  }\n}", "const pendingFallbackOperations = new Map<string, Promise<void>>();\n\n/**\n * Run one operation exclusively across every browser context on the origin.\n * Non-browser runtimes use a module-wide queue, which coordinates every\n * caller in the process.\n */\nexport async function runWithCrossContextLock<T>(name: string, operation: () => Promise<T>): Promise<T> {\n  const lockManager = globalThis.navigator?.locks;\n  if (lockManager !== undefined) {\n    return lockManager.request(name, operation);\n  }\n\n  // `isSecureContext` exists on browser Window and Worker globals. Never\n  // degrade to a realm-local queue there: doing so would reintroduce races\n  // between tabs, workers, and service workers that share persistent state.\n  if (globalThis.isSecureContext !== undefined) {\n    throw new Error('Cross-context locking requires the Web Locks API.');\n  }\n\n  return runSerializedByKey(pendingFallbackOperations, name, operation);\n}\n\n/**\n * Serialize operations sharing one key through a pending-completion map: each\n * operation chains behind the key's tail, failures never poison the queue,\n * and the tail entry removes itself once no successor has replaced it.\n */\nexport async function runSerializedByKey<T>(\n  pending: Map<string, Promise<void>>,\n  key: string,\n  operation: () => Promise<T>,\n): Promise<T> {\n  const previous = pending.get(key);\n  const operationPromise = (async (): Promise<T> => {\n    if (previous !== undefined) {\n      await previous;\n    }\n    return operation();\n  })();\n  const completion = operationPromise.then(\n    (): void => undefined,\n    (): void => undefined,\n  );\n  pending.set(key, completion);\n\n  try {\n    return await operationPromise;\n  } finally {\n    if (pending.get(key) === completion) {\n      pending.delete(key);\n    }\n  }\n}\n", "import { baseX } from './base.ts'\n\nexport const base36 = baseX({\n  prefix: 'k',\n  name: 'base36',\n  alphabet: '0123456789abcdefghijklmnopqrstuvwxyz',\n  caseInsensitive: true\n})\n\nexport const base36upper = baseX({\n  prefix: 'K',\n  name: 'base36upper',\n  alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n  caseInsensitive: true\n})\n", "import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n  const code = varint.decode(data, offset)\n  return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n  varint.encode(int, target, offset)\n  return target\n}\n\nexport function encodingLength (int: number): number {\n  return varint.encodingLength(int)\n}\n", "/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n  , REST = 0x7F\n  , MSBALL = ~REST\n  , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n  out = out || [];\n  offset = offset || 0;\n  var oldOffset = offset;\n\n  while(num >= INT) {\n    out[offset++] = (num & 0xFF) | MSB;\n    num /= 128;\n  }\n  while(num & MSBALL) {\n    out[offset++] = (num & 0xFF) | MSB;\n    num >>>= 7;\n  }\n  out[offset] = num | 0;\n  \n  // @ts-ignore\n  encode.bytes = offset - oldOffset + 1;\n  \n  return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n  , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n  var res    = 0\n    , offset = offset || 0\n    , shift  = 0\n    , counter = offset\n    , b\n    , l = buf.length;\n\n  do {\n    if (counter >= l) {\n      // @ts-ignore\n      read.bytes = 0;\n      throw new RangeError('Could not decode varint')\n    }\n    b = buf[counter++];\n    res += shift < 28\n      ? (b & REST$1) << shift\n      : (b & REST$1) * Math.pow(2, shift);\n    shift += 7;\n  } while (b >= MSB$1)\n\n  // @ts-ignore\n  read.bytes = counter - offset;\n\n  return res\n}\n\nvar N1 = Math.pow(2,  7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n  return (\n    value < N1 ? 1\n  : value < N2 ? 2\n  : value < N3 ? 3\n  : value < N4 ? 4\n  : value < N5 ? 5\n  : value < N6 ? 6\n  : value < N7 ? 7\n  : value < N8 ? 8\n  : value < N9 ? 9\n  :              10\n  )\n};\n\nvar varint = {\n    encode: encode_1\n  , decode: decode\n  , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import { coerce, equals as equalBytes, toArrayBufferBackedArray } from '../bytes.ts'\nimport * as varint from '../varint.ts'\nimport type { MultihashDigest } from './interface.ts'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n  const size = digest.byteLength\n  const sizeOffset = varint.encodingLength(code)\n  const digestOffset = sizeOffset + varint.encodingLength(size)\n\n  const bytes = new Uint8Array(digestOffset + size)\n  varint.encodeTo(code, bytes, 0)\n  varint.encodeTo(size, bytes, sizeOffset)\n  bytes.set(digest, digestOffset)\n\n  return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n  const bytes = coerce(multihash)\n  const [code, sizeOffset] = varint.decode(bytes)\n  const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n  const digest = bytes.subarray(sizeOffset + digestOffset)\n\n  if (digest.byteLength !== size) {\n    throw new Error('Incorrect length')\n  }\n\n  return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n  if (a === b) {\n    return true\n  } else {\n    const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n    return (\n      a.code === data.code &&\n      a.size === data.size &&\n      data.bytes instanceof Uint8Array &&\n      equalBytes(a.bytes, data.bytes)\n    )\n  }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest<Code extends number, Size extends number> implements MultihashDigest {\n  readonly code: Code\n  readonly size: Size\n  readonly digest: Uint8Array<ArrayBuffer>\n  readonly bytes: Uint8Array<ArrayBuffer>\n\n  /**\n   * Creates a multihash digest.\n   */\n  constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n    this.code = code\n    this.size = size\n    this.digest = toArrayBufferBackedArray(digest)\n    this.bytes = toArrayBufferBackedArray(bytes)\n  }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode <T extends number> (digest: MultihashDigest, code: T): digest is MultihashDigest<T> {\n  return digest.code === code\n}\n", "import { base32 } from './bases/base32.ts'\nimport { base36 } from './bases/base36.ts'\nimport { base58btc } from './bases/base58.ts'\nimport { coerce, toArrayBufferBackedArray } from './bytes.ts'\nimport * as Digest from './hashes/digest.ts'\nimport * as varint from './varint.ts'\nimport type * as API from './link/interface.ts'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.ts'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n  const { bytes, version } = link\n  switch (version) {\n    case 0:\n      return toStringV0(\n        bytes,\n        baseCache(link),\n        base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n      )\n    default:\n      return toStringV1(\n        bytes,\n        baseCache(link),\n        (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n      )\n  }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n  return {\n    '/': format(link)\n  }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n  return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\n  const baseCache = cache.get(cid)\n  if (baseCache == null) {\n    const baseCache = new Map()\n    cache.set(cid, baseCache)\n    return baseCache\n  }\n  return baseCache\n}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n  readonly code: Format\n  readonly version: Version\n  readonly multihash: API.MultihashDigest<Alg>\n  readonly bytes: Uint8Array<ArrayBuffer>\n  readonly '/': Uint8Array<ArrayBuffer>\n\n  /**\n   * @param version - Version of the CID\n   * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n   * @param multihash - (Multi)hash of the of the content.\n   */\n  constructor (version: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n    this.code = code\n    this.version = version\n    this.multihash = multihash\n    this.bytes = toArrayBufferBackedArray(bytes)\n\n    // flag to serializers that this is a CID and\n    // should be treated specially\n    this['/'] = this.bytes\n  }\n\n  /**\n   * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n   * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n   *\n   * @deprecated\n   */\n  get asCID (): this {\n    return this\n  }\n\n  // ArrayBufferView\n  get byteOffset (): number {\n    return this.bytes.byteOffset\n  }\n\n  // ArrayBufferView\n  get byteLength (): number {\n    return this.bytes.byteLength\n  }\n\n  toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n    switch (this.version) {\n      case 0: {\n        return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n      }\n      case 1: {\n        const { code, multihash } = this\n\n        if (code !== DAG_PB_CODE) {\n          throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n        }\n\n        // sha2-256\n        if (multihash.code !== SHA_256_CODE) {\n          throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n        }\n\n        return (\n          CID.createV0(\n            multihash as API.MultihashDigest<API.SHA_256>\n          )\n        )\n      }\n      default: {\n        throw Error(\n          `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n        )\n      }\n    }\n  }\n\n  toV1 (): CID<Data, Format, Alg, 1> {\n    switch (this.version) {\n      case 0: {\n        const { code, digest } = this.multihash\n        const multihash = Digest.create(code, digest)\n        return (\n          CID.createV1(this.code, multihash)\n        )\n      }\n      case 1: {\n        return this as CID<Data, Format, Alg, 1>\n      }\n      default: {\n        throw Error(\n          `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n        )\n      }\n    }\n  }\n\n  equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n    return CID.equals(this, other)\n  }\n\n  static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n    const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n    return (\n      unknown != null &&\n      self.code === unknown.code &&\n      self.version === unknown.version &&\n      Digest.equals(self.multihash, unknown.multihash)\n    )\n  }\n\n  toString (base?: API.MultibaseEncoder<string>): string {\n    return format(this, base)\n  }\n\n  toJSON (): API.LinkJSON<this> {\n    return { '/': format(this) }\n  }\n\n  link (): this {\n    return this\n  }\n\n  readonly [Symbol.toStringTag] = 'CID';\n\n  // Legacy\n\n  [Symbol.for('nodejs.util.inspect.custom')] (): string {\n    return `CID(${this.toString()})`\n  }\n\n  /**\n   * Takes any input `value` and returns a `CID` instance if it was\n   * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n   * it will return value back. If `value` is not instance of this CID\n   * class, but is compatible CID it will return new instance of this\n   * `CID` class. Otherwise returns null.\n   *\n   * This allows two different incompatible versions of CID library to\n   * co-exist and interop as long as binary interface is compatible.\n   */\n  static asCID <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n    if (input == null) {\n      return null\n    }\n\n    const value = input as any\n    if (value instanceof CID) {\n      // If value is instance of CID then we're all set.\n      return value\n    } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n      // If value isn't instance of this CID class but `this.asCID === this` or\n      // `value['/'] === value.bytes` is true it is CID instance coming from a\n      // different implementation (diff version or duplicate). In that case we\n      // rebase it to this `CID` implementation so caller is guaranteed to get\n      // instance with expected API.\n      const { version, code, multihash, bytes } = value\n      return new CID(\n        version,\n        code,\n        multihash as API.MultihashDigest<Alg>,\n        bytes ?? encodeCID(version, code, multihash.bytes)\n      )\n    } else if (value[cidSymbol] === true) {\n      // If value is a CID from older implementation that used to be tagged via\n      // symbol we still rebase it to the this `CID` implementation by\n      // delegating that to a constructor.\n      const { version, multihash, code } = value\n      const digest = Digest.decode(multihash) as API.MultihashDigest<Alg>\n      return CID.create(version, code, digest)\n    } else {\n      // Otherwise value is not a CID (or an incompatible version of it) in\n      // which case we return `null`.\n      return null\n    }\n  }\n\n  /**\n   * @param version - Version of the CID\n   * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n   * @param digest - (Multi)hash of the of the content.\n   */\n  static create <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n    if (typeof code !== 'number') {\n      throw new Error('String codecs are no longer supported')\n    }\n\n    if (!(digest.bytes instanceof Uint8Array)) {\n      throw new Error('Invalid digest')\n    }\n\n    switch (version) {\n      case 0: {\n        if (code !== DAG_PB_CODE) {\n          throw new Error(\n            `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n          )\n        } else {\n          return new CID(version, code, digest, digest.bytes)\n        }\n      }\n      case 1: {\n        const bytes = encodeCID(version, code, digest.bytes)\n        return new CID(version, code, digest, bytes)\n      }\n      default: {\n        throw new Error('Invalid version')\n      }\n    }\n  }\n\n  /**\n   * Simplified version of `create` for CIDv0.\n   */\n  static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n    return CID.create(0, DAG_PB_CODE, digest)\n  }\n\n  /**\n   * Simplified version of `create` for CIDv1.\n   *\n   * @param code - Content encoding format code.\n   * @param digest - Multihash of the content.\n   */\n  static createV1 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n    return CID.create(1, code, digest)\n  }\n\n  /**\n   * Decoded a CID from its binary representation. The byte array must contain\n   * only the CID with no additional bytes.\n   *\n   * An error will be thrown if the bytes provided do not contain a valid\n   * binary representation of a CID.\n   */\n  static decode <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\n    const [cid, remainder] = CID.decodeFirst(bytes)\n    if (remainder.length !== 0) {\n      throw new Error('Incorrect length')\n    }\n    return cid\n  }\n\n  /**\n   * Decoded a CID from its binary representation at the beginning of a byte\n   * array.\n   *\n   * Returns an array with the first element containing the CID and the second\n   * element containing the remainder of the original byte array. The remainder\n   * will be a zero-length byte array if the provided bytes only contained a\n   * binary CID representation.\n   */\n  static decodeFirst <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n    const specs = CID.inspectBytes(bytes)\n    const prefixSize = specs.size - specs.multihashSize\n    const multihashBytes = coerce(\n      bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n    )\n    if (multihashBytes.byteLength !== specs.multihashSize) {\n      throw new Error('Incorrect length')\n    }\n    const digestBytes = multihashBytes.subarray(\n      specs.multihashSize - specs.digestSize\n    )\n    const digest = new Digest.Digest(\n      specs.multihashCode,\n      specs.digestSize,\n      digestBytes,\n      multihashBytes\n    )\n    const cid =\n      specs.version === 0\n        ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n        : CID.createV1(specs.codec, digest)\n    return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n  }\n\n  /**\n   * Inspect the initial bytes of a CID to determine its properties.\n   *\n   * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n   * bytes but for larger multicodec code values and larger multihash digest\n   * lengths these varints can be quite large. It is recommended that at least\n   * 10 bytes be made available in the `initialBytes` argument for a complete\n   * inspection.\n   */\n  static inspectBytes <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n    let offset = 0\n    const next = (): number => {\n      const [i, length] = varint.decode(initialBytes.subarray(offset))\n      offset += length\n      return i\n    }\n\n    let version = next() as V\n    let codec = DAG_PB_CODE as C\n    if (version as number === 18) {\n      // CIDv0\n      version = 0 as V\n      offset = 0\n    } else {\n      codec = next() as C\n    }\n\n    if (version !== 0 && version !== 1) {\n      throw new RangeError(`Invalid CID version ${version}`)\n    }\n\n    const prefixSize = offset\n    const multihashCode = next() as A // multihash code\n    const digestSize = next() // multihash length\n    const size = offset + digestSize\n    const multihashSize = size - prefixSize\n\n    return { version, codec, multihashCode, digestSize, multihashSize, size }\n  }\n\n  /**\n   * Takes cid in a string representation and creates an instance. If `base`\n   * decoder is not provided will use a default from the configuration. It will\n   * throw an error if encoding of the CID is not compatible with supplied (or\n   * a default decoder).\n   */\n  static parse <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n    const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n    const cid = CID.decode(bytes)\n\n    if (cid.version === 0 && source[0] !== 'Q') {\n      throw Error('Version 0 CID string must not include multibase prefix')\n    }\n\n    // Cache string representation to avoid computing it on `this.toString()`\n    baseCache(cid).set(prefix, source)\n\n    return cid\n  }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n  switch (source[0]) {\n    // CIDv0 is parsed differently\n    case 'Q': {\n      const decoder = base ?? base58btc\n      return [\n        base58btc.prefix as Prefix,\n        decoder.decode(`${base58btc.prefix}${source}`)\n      ]\n    }\n    case base58btc.prefix: {\n      const decoder = base ?? base58btc\n      return [base58btc.prefix as Prefix, decoder.decode(source)]\n    }\n    case base32.prefix: {\n      const decoder = base ?? base32\n      return [base32.prefix as Prefix, decoder.decode(source)]\n    }\n    case base36.prefix: {\n      const decoder = base ?? base36\n      return [base36.prefix as Prefix, decoder.decode(source)]\n    }\n    default: {\n      if (base == null) {\n        throw Error(\n          'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n        )\n      }\n      return [source[0] as Prefix, base.decode(source)]\n    }\n  }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n  const { prefix } = base\n  if (prefix !== base58btc.prefix) {\n    throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n  }\n\n  const cid = cache.get(prefix)\n  if (cid == null) {\n    const cid = base.encode(bytes).slice(1)\n    cache.set(prefix, cid)\n    return cid\n  } else {\n    return cid\n  }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\n  const { prefix } = base\n  const cid = cache.get(prefix)\n  if (cid == null) {\n    const cid = base.encode(bytes)\n    cache.set(prefix, cid)\n    return cid\n  } else {\n    return cid\n  }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n  const codeOffset = varint.encodingLength(version)\n  const hashOffset = codeOffset + varint.encodingLength(code)\n  const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n  varint.encodeTo(version, bytes, 0)\n  varint.encodeTo(code, bytes, codeOffset)\n  bytes.set(multihash, hashOffset)\n  return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "import { varint } from 'multiformats';\n\nexport type MulticodecDefinition = {\n  code: number;\n  // codeBytes: Uint8Array;\n  name: string;\n};\n\n/**\n * The `Multicodec` class provides an interface to prepend binary data\n * with a prefix that identifies the data that follows.\n * https://github.com/multiformats/multicodec/blob/master/table.csv\n *\n * Multicodec is a self-describing multiformat, it wraps other formats with\n * a tiny bit of self-description. A multicodec identifier is a\n * varint (variable integer) that indicates the format of the data.\n *\n * The canonical table of multicodecs can be access at the following URL:\n * https://github.com/multiformats/multicodec/blob/master/table.csv\n *\n * Example usage:\n *\n * ```ts\n * Multicodec.registerCodec({ code: 0xed, name: 'ed25519-pub' });\n * const prefixedData = Multicodec.addPrefix({ code: 0xed, data: new Uint8Array(32) });\n * ```\n */\nexport class Multicodec {\n  /**\n   * A static field containing a map of codec codes to their corresponding names.\n   */\n  static readonly codeToName = new Map<number, string>();\n\n  /**\n   * A static field containing a map of codec names to their corresponding codes.\n   */\n  static readonly nameToCode = new Map<string, number>();\n\n  /**\n   * Adds a multicodec prefix to input data.\n   *\n   * @param options - The options for adding a prefix.\n   * @param options.code - The codec code. Either the code or name must be provided.\n   * @param options.name - The codec name. Either the code or name must be provided.\n   * @param options.data - The data to be prefixed.\n   * @returns The data with the added prefix as a Uint8Array.\n   */\n  public static addPrefix(options: {\n    code?: number,\n    data: Uint8Array,\n    name?: string,\n  }): Uint8Array {\n    let { code, data, name } = options;\n\n    if (!(name ? !code : code)) {\n      throw new Error(`Either 'name' or 'code' must be defined, but not both.`);\n    }\n\n    // If code was given, confirm it exists, or lookup code by name.\n    code = Multicodec.codeToName.has(code!) ? code : Multicodec.nameToCode.get(name!);\n\n    // Throw error if a registered Codec wasn't found.\n    if (code === undefined) {\n      throw new Error(`Unsupported multicodec: ${options.name ?? options.code}`);\n    }\n\n    // Create a new array to store the prefix and input data.\n    const prefixLength = varint.encodingLength(code);\n    const dataWithPrefix = new Uint8Array(prefixLength + data.byteLength);\n    dataWithPrefix.set(data, prefixLength);\n\n    // Prepend the prefix.\n    varint.encodeTo(code, dataWithPrefix);\n\n    return dataWithPrefix;\n  }\n\n  /**\n   * Get the Multicodec code from given prefixed data.\n   *\n   * @param options - The options for getting the codec code.\n   * @param options.prefixedData - The data to extract the codec code from.\n   * @returns - The Multicodec code as a number.\n   */\n  public static getCodeFromData(options: {\n    prefixedData: Uint8Array\n  }): number {\n    const { prefixedData } = options;\n    const [code, _] = varint.decode(prefixedData);\n\n    return code;\n  }\n\n  /**\n   * Get the Multicodec code from given Multicodec name.\n   *\n   * @param options - The options for getting the codec code.\n   * @param options.name - The name to lookup.\n   * @returns - The Multicodec code as a number.\n   */\n  public static getCodeFromName(options: {\n    name: string\n  }): number {\n    const { name } = options;\n\n    // Throw error if a registered Codec wasn't found.\n    const code = Multicodec.nameToCode.get(name);\n    if (code === undefined) {\n      throw new Error(`Unsupported multicodec: ${name}`);\n    }\n\n    return code;\n  }\n\n  /**\n   * Get the Multicodec name from given Multicodec code.\n   *\n   * @param options - The options for getting the codec name.\n   * @param options.name - The code to lookup.\n   * @returns - The Multicodec name as a string.\n   */\n  public static getNameFromCode(options: {\n    code: number\n  }): string {\n    const { code } = options;\n\n    // Throw error if a registered Codec wasn't found.\n    const name = Multicodec.codeToName.get(code);\n    if (name === undefined) {\n      throw new Error(`Unsupported multicodec: ${code}`);\n    }\n\n    return name;\n  }\n\n  /**\n   * Registers a new codec in the Multicodec class.\n   *\n   * @param codec - The codec to be registered.\n   */\n  public static registerCodec(codec: MulticodecDefinition): void {\n    Multicodec.codeToName.set(codec.code, codec.name);\n    Multicodec.nameToCode.set(codec.name, codec.code);\n  }\n\n  /**\n   * Returns the data with the Multicodec prefix removed.\n   *\n   * @param refixedData - The data to extract the codec code from.\n   * @returns {Uint8Array}\n   */\n  public static removePrefix(options: {\n    prefixedData: Uint8Array\n  }): { code: number, name: string, data: Uint8Array } {\n    const { prefixedData } = options;\n    const [code, codeByteLength] = varint.decode(prefixedData);\n\n    // Throw error if a registered Codec wasn't found.\n    const name = Multicodec.codeToName.get(code);\n    if (name === undefined) {\n      throw new Error(`Unsupported multicodec: ${code}`);\n    }\n\n    return { code, data: prefixedData.slice(codeByteLength), name };\n  }\n}\n\n// Pre-defined registered codecs:\nMulticodec.registerCodec({ code: 0xed, name: 'ed25519-pub' });\nMulticodec.registerCodec({ code: 0x1300, name: 'ed25519-priv' });\nMulticodec.registerCodec({ code: 0xec, name: 'x25519-pub' });\nMulticodec.registerCodec({ code: 0x1302, name: 'x25519-priv' });\nMulticodec.registerCodec({ code: 0xe7, name: 'secp256k1-pub' });\nMulticodec.registerCodec({ code: 0x1301, name: 'secp256k1-priv' });", "/**\n * Returns `true` only when a browser's connectivity hint explicitly reports that it is offline.\n *\n * An absent hint or `onLine === true` does not prove that a particular endpoint is reachable.\n */\nexport function isExplicitlyOffline(): boolean {\n  return globalThis.navigator?.onLine === false;\n}\n", "/**\n * Checks whether the given object has any properties.\n */\nexport function isEmptyObject(obj: unknown): boolean {\n  if (typeof obj !== 'object' || obj === null) {\n    return false;\n  }\n\n  if (Object.getOwnPropertySymbols(obj).length > 0) {\n    return false;\n  }\n\n  return Object.keys(obj).length === 0;\n}\n\n/**\n * Recursively removes all properties with an empty object or array as its value from the given object.\n *\n * Null-tolerant: skips `null` values without recursing into them.\n * `typeof null === 'object'` in JavaScript, so without an explicit guard\n * the recursion would call `Object.keys(null)` and throw.\n */\nexport function removeEmptyObjects(obj: Record<string, unknown>): void {\n  Object.keys(obj).forEach(key => {\n    const value = obj[key];\n    if (value !== null && typeof value === 'object') {\n      // recursive remove empty object or array properties in nested objects\n      removeEmptyObjects(value as Record<string, unknown>);\n    }\n\n    if (isEmptyObject(value)) {\n      delete obj[key];\n    }\n  });\n}\n\n/**\n * Recursively removes all properties with `undefined` as its value from the given object.\n *\n * Mutates `obj` in place and descends into nested objects. Null-tolerant:\n * `null` values are left in place but not recursed into (`typeof null ===\n * 'object'` in JavaScript, so without the guard the recursion would call\n * `Object.keys(null)` and throw). Use {@link omitUndefined} when you\n * want an immutable, shallow, type-preserving alternative.\n *\n * @see {@link omitUndefined} for the non-mutating, typed, shallow variant used\n *   by higher-level packages like `@enbox/api` to normalize call-site options.\n */\nexport function removeUndefinedProperties(obj: Record<string, unknown>): void {\n  Object.keys(obj).forEach(key => {\n    const value = obj[key];\n    if (value === undefined) {\n      delete obj[key];\n    } else if (value !== null && typeof value === 'object') {\n      removeUndefinedProperties(value as Record<string, unknown>); // recursive remove `undefined` properties in nested objects\n    }\n  });\n}\n\n/**\n * Returns a new object containing only the entries of `input` whose values are\n * not `undefined`. Pure \u2014 never mutates the input. Shallow \u2014 does not descend\n * into nested objects.\n *\n * Companion to {@link removeUndefinedProperties}, which mutates and recurses.\n * Pick the variant that matches the call site:\n *\n * | Helper                       | Mutates? | Recursive? | Typed?           |\n * |------------------------------|----------|------------|------------------|\n * | `removeUndefinedProperties`  | yes      | yes        | no (`Record`)    |\n * | `omitUndefined`              | no       | no         | yes (preserves T)|\n *\n * Both helpers are the single source of truth for the monorepo \u2014\n * `@enbox/dwn-sdk-js/utils/object.ts` re-exports them rather than holding\n * its own copy. New shape-transform helpers belong here.\n *\n * @example\n * ```ts\n * omitUndefined({ a: 1, b: undefined, c: 'x' });\n * // \u2192 { a: 1, c: 'x' }\n *\n * // Useful when building option payloads where `undefined` keys would break\n * // assertion equality in tests:\n * const opts = omitUndefined({ password: input.password, sync: input.sync });\n * ```\n */\nexport function omitUndefined<T extends object>(input: T): Partial<T> {\n  const result: Partial<T> = {};\n  for (const key of Object.keys(input) as (keyof T)[]) {\n    const value = input[key];\n    if (value !== undefined) {\n      result[key] = value;\n    }\n  }\n  return result;\n}", "import type { KeyValueStore } from './types.js';\n\n/**\n * The `MemoryStore` class is an implementation of\n * `KeyValueStore` that holds data in memory.\n *\n * It provides a basic key-value store that works synchronously and keeps all\n * data in memory. This can be used for testing, or for handling small amounts\n * of data with simple key-value semantics.\n *\n * Example usage:\n *\n * ```ts\n * const memoryStore = new MemoryStore<string, number>();\n * await memoryStore.set(\"key1\", 1);\n * const value = await memoryStore.get(\"key1\");\n * console.log(value); // 1\n * ```\n *\n * @public\n */\nexport class MemoryStore<K, V> implements KeyValueStore<K, V> {\n  /**\n   * A private field that contains the Map used as the key-value store.\n   */\n  private readonly store: Map<K, V> = new Map();\n\n  /**\n   * Clears all entries in the key-value store.\n   *\n   * @returns A Promise that resolves when the operation is complete.\n   */\n  public async clear(): Promise<void> {\n    this.store.clear();\n  }\n\n  /**\n   * This operation is no-op for `MemoryStore`.\n   */\n  public async open(): Promise<void> {\n    /** no-op */\n  }\n\n  /**\n   * This operation is no-op for `MemoryStore`.\n   */\n  public async close(): Promise<void> {\n    /** no-op */\n  }\n\n  /**\n   * Deletes an entry from the key-value store by its key.\n   *\n   * @param id - The key of the entry to delete.\n   * @returns A Promise that resolves to a boolean indicating whether the entry was successfully deleted.\n   */\n  public async delete(id: K): Promise<boolean> {\n    return this.store.delete(id);\n  }\n\n  /**\n   * Retrieves the value of an entry by its key.\n   *\n   * @param id - The key of the entry to retrieve.\n   * @returns A Promise that resolves to the value of the entry, or `undefined` if the entry does not exist.\n   */\n  public async get(id: K): Promise<V | undefined> {\n    return this.store.get(id);\n  }\n\n  /**\n   * Checks for the presence of an entry by key.\n   *\n   * @param id - The key to check for the existence of.\n   * @returns A Promise that resolves to a boolean indicating whether an element with the specified key exists or not.\n   */\n  public async has(id: K): Promise<boolean> {\n    return this.store.has(id);\n  }\n\n  /**\n   * Retrieves all values in the key-value store.\n   *\n   * @returns A Promise that resolves to an array of all values in the store.\n   */\n  public async list(): Promise<V[]> {\n    return Array.from(this.store.values());\n  }\n\n  /**\n   * Sets the value of an entry in the key-value store.\n   *\n   * @param id - The key of the entry to set.\n   * @param key - The new value for the entry.\n   * @returns A Promise that resolves when the operation is complete.\n   */\n  public async set(id: K, key: V): Promise<void> {\n    this.store.set(id, key);\n  }\n}\n", "import { Convert } from './convert.js';\n\nexport class Stream {\n  /**\n   * Creates a `ReadableStream<Uint8Array>` from a `Blob`.\n   *\n   * This is a convenience method that wraps `Blob.stream()` with proper typing. It's useful when\n   * you have a `Blob` and need a `ReadableStream<Uint8Array>` for streaming consumption.\n   *\n   * @example\n   * ```ts\n   * const blob = new Blob(['Hello, World!'], { type: 'text/plain' });\n   * const readableStream = Stream.fromBlob(blob);\n   * ```\n   *\n   * @param blob - The `Blob` to create a `ReadableStream` from.\n   * @returns A `ReadableStream<Uint8Array>` containing the blob's data.\n   */\n  public static fromBlob(blob: Blob): ReadableStream<Uint8Array> {\n    return blob.stream();\n  }\n\n  /**\n   * Creates a `ReadableStream<Uint8Array>` from a `Uint8Array`.\n   *\n   * This method creates a `ReadableStream` that emits the provided bytes in chunks.\n   *\n   * @example\n   * ```ts\n   * const bytes = new Uint8Array([1, 2, 3, 4, 5]);\n   * const readableStream = Stream.fromBytes(bytes);\n   * ```\n   *\n   * @param bytes - The `Uint8Array` to create a `ReadableStream` from.\n   * @param chunkLength - Optional chunk size in bytes. Defaults to 100,000 bytes.\n   * @returns A `ReadableStream<Uint8Array>` that emits the bytes in chunks.\n   */\n  public static fromBytes(bytes: Uint8Array, chunkLength: number = 100_000): ReadableStream<Uint8Array> {\n    let offset = 0;\n    return new ReadableStream<Uint8Array>({\n      pull(controller): void {\n        if (offset >= bytes.length) {\n          controller.close();\n          return;\n        }\n        const end = Math.min(offset + chunkLength, bytes.length);\n        controller.enqueue(bytes.subarray(offset, end));\n        offset = end;\n      }\n    });\n  }\n\n  /**\n   * Transforms a `ReadableStream` into an `AsyncIterable`. This allows for the asynchronous\n   * iteration over the stream's data chunks.\n   *\n   * This method creates an async iterator from a `ReadableStream`, enabling the use of\n   * `for await...of` loops to process stream data. It reads from the stream until it's closed or\n   * errored, yielding each chunk as it becomes available.\n   *\n   * @example\n   * ```ts\n   * const readableStream = new ReadableStream({ ... });\n   * for await (const chunk of Stream.asAsyncIterator(readableStream)) {\n   *   // process each chunk\n   * }\n   * ```\n   *\n   * @remarks\n   * - The method ensures proper cleanup by releasing the reader lock when iteration is completed or\n   *   if an error occurs.\n   *\n   * @param readableStream - The Web `ReadableStream` to be transformed into an `AsyncIterable`.\n   * @returns An `AsyncIterable` that yields data chunks from the `ReadableStream`.\n   */\n  public static async * asAsyncIterator<T>(readableStream: ReadableStream<T>): AsyncIterable<T> {\n    const reader = readableStream.getReader();\n    try {\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) {break;}\n        yield value;\n      }\n    } finally {\n      reader.releaseLock();\n    }\n  }\n\n  /**\n   * Consumes a `ReadableStream` and returns its contents as an `ArrayBuffer`.\n   *\n   * This method reads all data from a `ReadableStream`, collects it, and converts it into an\n   * `ArrayBuffer`.\n   *\n   * @example\n   * ```ts\n   * const readableStream = new ReadableStream({ ... });\n   * const arrayBuffer = await Stream.consumeToArrayBuffer({ readableStream });\n   * ```\n   *\n   * @param readableStream - The Web `ReadableStream` whose data will be consumed.\n   * @returns A Promise that resolves to an `ArrayBuffer` containing all the data from the stream.\n   */\n  public static async consumeToArrayBuffer({ readableStream }: { readableStream: ReadableStream}): Promise<ArrayBuffer> {\n    const iterableStream = Stream.asAsyncIterator(readableStream);\n    const arrayBuffer = await Convert.asyncIterable(iterableStream).toArrayBufferAsync();\n\n    return arrayBuffer;\n  }\n\n  /**\n   * Consumes a `ReadableStream` and returns its contents as a `Blob`.\n   *\n   * This method reads all data from a `ReadableStream`, collects it, and converts it into a `Blob`.\n   *\n   * @example\n   * ```ts\n   * const readableStream = new ReadableStream({ ... });\n   * const blob = await Stream.consumeToBlob({ readableStream });\n   * ```\n   *\n   * @param readableStream - The Web `ReadableStream` whose data will be consumed.\n   * @returns A Promise that resolves to a `Blob` containing all the data from the stream.\n   */\n  public static async consumeToBlob({ readableStream }: { readableStream: ReadableStream}): Promise<Blob> {\n    const iterableStream = Stream.asAsyncIterator(readableStream);\n    const blob = await Convert.asyncIterable(iterableStream).toBlobAsync();\n\n    return blob;\n  }\n\n  /**\n   * Consumes a `ReadableStream` and returns its contents as a `Uint8Array`.\n   *\n   * This method reads all data from a `ReadableStream`, collects it, and converts it into a\n   * `Uint8Array`.\n   *\n   * @example\n   * ```ts\n   * const readableStream = new ReadableStream({ ... });\n   * const bytes = await Stream.consumeToBytes({ readableStream });\n   * ```\n   *\n   * @param readableStream - The Web `ReadableStream` whose data will be consumed.\n   * @returns A Promise that resolves to a `Uint8Array` containing all the data from the stream.\n   */\n  public static async consumeToBytes({ readableStream }: { readableStream: ReadableStream }): Promise<Uint8Array> {\n    const iterableStream = Stream.asAsyncIterator(readableStream);\n    const bytes = await Convert.asyncIterable(iterableStream).toUint8ArrayAsync();\n\n    return bytes;\n  }\n\n  /**\n   * Consumes a `ReadableStream` and parses its contents as JSON.\n   *\n   * This method reads all the data from the stream, converts it to a text string, and then parses\n   * it as JSON, returning the resulting object.\n   *\n   * @example\n   * ```ts\n   * const readableStream = new ReadableStream({ ... });\n   * const jsonData = await Stream.consumeToJson({ readableStream });\n   * ```\n   *\n   * @param readableStream - The Web `ReadableStream` whose JSON content will be consumed.\n   * @returns A Promise that resolves to the parsed JSON object from the stream's data.\n   */\n  public static async consumeToJson<T = unknown>({ readableStream }: { readableStream: ReadableStream}): Promise<T> {\n    const iterableStream = Stream.asAsyncIterator(readableStream);\n    const object = await Convert.asyncIterable(iterableStream).toObjectAsync<T>();\n\n    return object;\n  }\n\n  /**\n   * Consumes a `ReadableStream` and returns its contents as a text string.\n   *\n   * This method reads all the data from the stream, converting it into a single string.\n   *\n   * @example\n   * ```ts\n   * const readableStream = new ReadableStream({ ... });\n   * const text = await Stream.consumeToText({ readableStream });\n   * ```\n   *\n   * @param readableStream - The Web `ReadableStream` whose text content will be consumed.\n   * @returns A Promise that resolves to a string containing all the data from the stream.\n   */\n  public static async consumeToText({ readableStream }: { readableStream: ReadableStream}): Promise<string> {\n    const iterableStream = Stream.asAsyncIterator(readableStream);\n    const text = await Convert.asyncIterable(iterableStream).toStringAsync();\n\n    return text;\n  }\n\n  /**\n   * Generates a `ReadableStream` of `Uint8Array` chunks with customizable length and fill value.\n   *\n   * This method creates a `ReadableStream` that emits `Uint8Array` chunks. You can specify the\n   * total length of the stream, the length of individual chunks, and a fill value for the chunks.\n   *\n   * @example\n   * ```ts\n   * // Create a stream of 1000 bytes with 100-byte chunks filled with 0xAA.\n   * const byteStream = Stream.generateByteStream({\n   *   streamLength: 1000,\n   *   chunkLength: 100,\n   *   fillValue: 0xAA\n   * });\n   * ```\n   *\n   * @param streamLength - The total length of the stream in bytes. If omitted, the stream is infinite.\n   * @param chunkLength - The length of each chunk. If omitted, each chunk is the size of `streamLength`.\n   * @param fillValue - A byte value to fill every position in each chunk. If omitted, chunks are zero-filled.\n   * @returns A `ReadableStream` that emits `Uint8Array` chunks.\n   */\n  public static generateByteStream({ streamLength, chunkLength, fillValue }: {\n    streamLength?: number,\n    chunkLength?: number,\n    fillValue?: number\n  }): ReadableStream<Uint8Array> {\n    let bytesRemaining = streamLength ?? Infinity;\n    let controller: ReadableStreamDefaultController<Uint8Array>;\n\n    function enqueueChunk(): void {\n      const currentChunkLength = Math.min(bytesRemaining, chunkLength ?? Infinity);\n      bytesRemaining -= currentChunkLength;\n\n      let chunk: Uint8Array;\n\n      if (typeof fillValue === 'number') {\n        chunk = new Uint8Array(currentChunkLength).fill(fillValue);\n      } else {\n        chunk = new Uint8Array(currentChunkLength);\n      }\n\n      controller.enqueue(chunk);\n\n      // If there are no more bytes to send, close the stream\n      if (bytesRemaining <= 0) {\n        controller.close();\n      }\n    }\n\n    return new ReadableStream<Uint8Array>({\n      start(c): void {\n        controller = c;\n        enqueueChunk();\n      },\n      pull(): void {\n        enqueueChunk();\n      },\n    });\n  }\n\n  /**\n   * Checks if the provided Web `ReadableStream` is in a readable state.\n   *\n   * After verifying that the stream is a Web {@link https://streams.spec.whatwg.org/#rs-model | ReadableStream},\n   * this method checks the {@link https://streams.spec.whatwg.org/#readablestream-locked | locked}\n   * property of the ReadableStream. The `locked` property is `true` if a reader is currently\n   * active, meaning the stream is either being read or has already been read (and hence is not in a\n   * readable state). If `locked` is `false`, it means the stream is still in a state where it can\n   * be read.\n   *\n   * In the case where a `ReadableStream` has been unlocked but is no longer readable (for example,\n   * if it has been fully read or cancelled), additional checks are needed beyond just examining the\n   * locked property. The ReadableStream API does not provide a direct way to check if the stream\n   * has data left or if it's in a readable state once it's been unlocked.\n   *\n   * Per {@link https://streams.spec.whatwg.org/#other-specs-rs-introspect | WHATWG Streams, Section 9.1.3. Introspection}:\n   *\n   * > ...note that apart from checking whether or not the stream is locked, this direct\n   * > introspection is not possible via the public JavaScript API, and so specifications should\n   * > instead use the algorithms in \u00A79.1.2 Reading. (For example, instead of testing if the stream\n   * > is readable, attempt to get a reader and handle any exception.)\n   *\n   * This implementation employs the technique suggested by the WHATWG Streams standard by\n   * attempting to acquire a reader and checking the state of the reader. If acquiring a reader\n   * succeeds, it immediately releases the lock and returns `true`, indicating the stream is\n   * readable. If an error occurs while trying to get a reader (which can happen if the stream is\n   * already closed or errored), it catches the error and returns `false`, indicating the stream is\n   * not readable.\n   *\n   * @example\n   * ```ts\n   * const readableStream = new ReadableStream({ ... });\n   * const isStreamReadable = Stream.isReadable({ readableStream });\n   * console.log(isStreamReadable); // Output: true or false\n   * ```\n   *\n   * @remarks\n   * - This method does not check whether the stream has data left to read; it only checks if the\n   *   stream is in a state that allows reading. It is possible for a stream to be unlocked but\n   *   still have no data left if it has never been locked to a reader.\n   *\n   * @param readableStream - The Web `ReadableStream` to be checked for readability.\n   *\n   * @returns `true` if the stream is a `ReadableStream` and is in a readable state (not locked and\n   *          no error on getting a reader); otherwise, `false`.\n   */\n  public static isReadable({ readableStream }: { readableStream: ReadableStream }): boolean {\n    // Check if the stream is a WHATWG `ReadableStream`.\n    if (!Stream.isReadableStream(readableStream)) {\n      return false;\n    }\n\n    // Check if the stream is locked.\n    if (readableStream.locked) {\n      return false;\n    }\n\n    try {\n      // Try to get a reader to check if the stream is readable.\n      const reader = readableStream.getReader();\n      // If successful, immediately release the lock.\n      reader.releaseLock();\n      return true;\n    } catch {\n      // If an error occurs (e.g., the stream is not readable), return false.\n      return false;\n    }\n  }\n\n  /**\n   * Checks if an object is a Web `ReadableStream`.\n   *\n   * This method verifies whether the given object is a `ReadableStream` by checking its type and\n   * the presence of the `getReader` function.\n   *\n   * @example\n   * ```ts\n   * const obj = getSomeObject();\n   * if (Stream.isReadableStream(obj)) {\n   *   // obj is a ReadableStream\n   * }\n   * ```\n   *\n   * @param obj - The object to be checked.\n   * @returns `true` if `obj` is a `ReadableStream`; otherwise, `false`.\n   */\n  public static isReadableStream(obj: unknown): obj is ReadableStream {\n    return (\n      typeof obj === 'object' && obj !== null &&\n      'getReader' in obj && typeof obj.getReader === 'function'\n    );\n  }\n\n  /**\n   * Checks if an object is a Web `ReadableStream`, `WritableStream`, or `TransformStream`.\n   *\n   * This method verifies the type of a given object to determine if it is one of the standard\n   * stream types in the Web Streams API: `ReadableStream`, `WritableStream`, or `TransformStream`.\n   * It employs type-checking strategies that are specific to each stream type.\n   *\n   * The method checks for the specific functions and properties associated with each stream type:\n   * - `ReadableStream`: Identified by the presence of a `getReader` method.\n   * - `WritableStream`: Identified by the presence of a `getWriter` and `abort` methods.\n   * - `TransformStream`: Identified by having both `readable` and `writable` properties.\n   *\n   * @example\n   * ```ts\n   * const readableStream = new ReadableStream();\n   * console.log(Stream.isStream(readableStream)); // Output: true\n   *\n   * const writableStream = new WritableStream();\n   * console.log(Stream.isStream(writableStream)); // Output: true\n   *\n   * const transformStream = new TransformStream();\n   * console.log(Stream.isStream(transformStream)); // Output: true\n   *\n   * const nonStreamObject = {};\n   * console.log(Stream.isStream(nonStreamObject)); // Output: false\n   * ```\n   *\n   * @remarks\n   * - This method does not differentiate between `ReadableStream`, `WritableStream`, and\n   *   `TransformStream`. It checks if the object conforms to any of these types.\n   * - This method is specific to the Web Streams API and may not recognize non-standard or custom\n   *   stream-like objects that do not adhere to the Web Streams API specifications.\n   *\n   * @param obj - The object to be checked for being a Web `ReadableStream`, `WritableStream`, or `TransformStream`.\n   * @returns `true` if the object is a `ReadableStream`, `WritableStream`, or `TransformStream`; otherwise, `false`.\n   */\n  public static isStream(obj: unknown): obj is ReadableStream | WritableStream | TransformStream {\n    return Stream.isReadableStream(obj) || Stream.isWritableStream(obj) || Stream.isTransformStream(obj);\n  }\n\n  /**\n   * Checks if an object is a `TransformStream`.\n   *\n   * This method verifies whether the given object is a `TransformStream` by checking its type and\n   * the presence of `readable` and `writable` properties.\n   *\n   * @example\n   * ```ts\n   * const obj = getSomeObject();\n   * if (Stream.isTransformStream(obj)) {\n   *   // obj is a TransformStream\n   * }\n   * ```\n   *\n   * @param obj - The object to be checked.\n   * @returns `true` if `obj` is a `TransformStream`; otherwise, `false`.\n   */\n  public static isTransformStream(obj: unknown): obj is TransformStream {\n    return (\n      typeof obj === 'object' && obj !== null &&\n      'readable' in obj && typeof obj.readable === 'object' &&\n      'writable' in obj && typeof obj.writable === 'object'\n    );\n  }\n\n  /**\n   * Checks if an object is a `WritableStream`.\n   *\n   * This method determines whether the given object is a `WritableStream` by verifying its type and\n   * the presence of the `getWriter` and `abort` functions.\n   *\n   * @example\n   * ```ts\n   * const obj = getSomeObject();\n   * if (Stream.isWritableStream(obj)) {\n   *   // obj is a WritableStream\n   * }\n   * ```\n   *\n   * @param obj - The object to be checked.\n     * @returns `true` if `obj` is a `TransformStream`; otherwise, `false`.\n     */\n  public static isWritableStream(obj: unknown): obj is WritableStream {\n    return (\n      typeof obj === 'object' && obj !== null &&\n      'getWriter' in obj && typeof obj.getWriter === 'function' &&\n      'abort' in obj && typeof obj.abort === 'function'\n    );\n  }\n}", "/**\n * URL helpers shared across packages.\n *\n * @module\n */\n\n/**\n * Returns true when the hostname is a loopback, private, link-local, or\n * otherwise non-routable literal that should not be fetched from untrusted\n * input.\n */\nexport function isPrivateHostname(hostname: string): boolean {\n  let h = hostname.trim().toLowerCase();\n\n  if (h.startsWith('[') && h.endsWith(']')) {\n    h = h.slice(1, -1);\n  }\n\n  const zoneIndex = h.indexOf('%');\n  if (zoneIndex !== -1) {\n    h = h.slice(0, zoneIndex);\n  }\n\n  if (h.endsWith('.')) {\n    h = h.slice(0, -1);\n  }\n\n  if (h === 'localhost' || h.endsWith('.localhost')) {\n    return true;\n  }\n\n  const ipv4 = parseIpv4(h);\n  if (ipv4 !== undefined) {\n    return isPrivateIpv4(ipv4);\n  }\n\n  if (h.includes(':')) {\n    return isPrivateIpv6(h);\n  }\n\n  return false;\n}\n\n/** Default protocols accepted by {@link assertPublicUrl} when no explicit list is given. */\nconst DEFAULT_PUBLIC_URL_PROTOCOLS: readonly string[] = ['http:', 'https:'];\n\n/**\n * Thrown by {@link assertPublicUrl} (and surfaced by {@link fetchPublicUrl}) when a URL \u2014 or a\n * redirect target \u2014 fails public-URL validation. Distinct from generic `Error` so callers can\n * map validation failures to a specific error code (e.g. `invalidGatewayUri`) without\n * accidentally also mapping unrelated network failures.\n */\nexport class PublicUrlValidationError extends Error {\n  public constructor(message: string) {\n    super(message);\n    this.name = 'PublicUrlValidationError';\n  }\n}\n\n/**\n * Parses and validates that a URL targets a routable public host over an allowed network scheme.\n *\n * Rejects:\n * - URLs whose protocol is not in `allowedProtocols` (defaults to `http:` / `https:`), so callers\n *   cannot smuggle `file:`, `javascript:`, `data:`, `ws:`, etc. past a downstream `fetch()`.\n * - URLs without a hostname.\n * - URLs whose hostname is a loopback, private, link-local, or otherwise non-routable literal per\n *   {@link isPrivateHostname}, unless `allowPrivateHosts` explicitly permits trusted local targets.\n *\n * This intentionally does not perform DNS resolution, so callers handling high-risk server-side\n * fetches should still consider DNS rebinding defenses (and use {@link fetchPublicUrl} to also\n * validate every redirect target).\n */\nexport function assertPublicUrl(url: string | URL, description = 'URL', options?: {\n  allowedProtocols?: readonly string[];\n  allowPrivateHosts?: boolean;\n}): URL {\n  const parsedUrl = typeof url === 'string' ? new URL(url) : new URL(url.toString());\n  const allowedProtocols = options?.allowedProtocols ?? DEFAULT_PUBLIC_URL_PROTOCOLS;\n\n  if (!allowedProtocols.includes(parsedUrl.protocol)) {\n    throw new PublicUrlValidationError(`${description} must use one of the allowed schemes (${allowedProtocols.join(', ')}): ${parsedUrl.protocol}`);\n  }\n\n  if (parsedUrl.hostname === '') {\n    throw new PublicUrlValidationError(`${description} must specify a hostname.`);\n  }\n\n  if (!options?.allowPrivateHosts && isPrivateHostname(parsedUrl.hostname)) {\n    throw new PublicUrlValidationError(`${description} must not target a private, loopback, or link-local host: ${parsedUrl.hostname}`);\n  }\n\n  return parsedUrl;\n}\n\n/**\n * Maximum number of HTTP redirects {@link fetchPublicUrl} will follow before giving up. Public\n * relays and DID document servers should rarely chain more than 1\u20132 redirects; this leaves enough\n * headroom for those while still bounding worst-case behavior.\n */\nconst DEFAULT_MAX_REDIRECTS = 5;\n\nconst REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);\n\n/**\n * Performs a `fetch()` whose target \u2014 and every subsequent redirect target \u2014 is validated by\n * {@link assertPublicUrl}. Defends against SSRF via redirect-based bypasses where a public\n * gateway returns `Location: http://127.0.0.1/...` after the initial validation succeeded.\n *\n * Manually drives the redirect loop so each `Location` is re-validated. A 3xx response without a\n * `Location` header (e.g. `304 Not Modified`) is returned to the caller unchanged.\n */\nexport async function fetchPublicUrl(url: string | URL, init?: RequestInit, options?: {\n  description?: string;\n  allowedProtocols?: readonly string[];\n  /** Allow trusted local targets without bypassing scheme validation or redirect limits. */\n  allowPrivateHosts?: boolean;\n  maxRedirects?: number;\n  /** Wrap each validated hop's fetch independently of URL and redirect handling. */\n  fetchFn?: (url: string, init: RequestInit) => Promise<Response>;\n}): Promise<Response> {\n  const description = options?.description ?? 'URL';\n  const maxRedirects = options?.maxRedirects ?? DEFAULT_MAX_REDIRECTS;\n  const fetchFn = options?.fetchFn ?? fetch;\n  let currentUrl = assertPublicUrl(url, description, options).href;\n\n  for (let attempt = 0; attempt <= maxRedirects; attempt++) {\n    const response = await fetchFn(currentUrl, { ...init, redirect: 'manual' });\n\n    if (!REDIRECT_STATUS_CODES.has(response.status)) {\n      return response;\n    }\n\n    const location = response.headers.get('location');\n    if (location === null) {\n      return response;\n    }\n\n    currentUrl = assertPublicUrl(new URL(location, currentUrl), description, options).href;\n  }\n\n  throw new Error(`${description} exceeded the maximum number of redirects (${maxRedirects}).`);\n}\n\n/**\n * Concatenates a base URL and a path ensuring that there is exactly one slash between them.\n *\n * The `path` argument must be a pure URL pathname \u2014 raw `?` (query) and `#` (fragment) delimiters\n * are rejected because they are silently percent-encoded by the WHATWG URL parser when assigned\n * to `pathname`, which would otherwise change the endpoint a caller meant to reach. Callers that\n * need to attach a query string or fragment should construct the URL explicitly. Percent-encoded\n * `%3F` / `%23` are preserved so genuine path segments containing those characters work.\n */\nexport function concatenateUrl(baseUrl: string, path: string): string {\n  if (path.includes('?') || path.includes('#')) {\n    throw new Error('Path must not contain a raw query string or fragment; build the URL explicitly instead.');\n  }\n\n  const sanitizedPath = path.replaceAll(/^\\/+/g, '');\n  const segments = sanitizedPath.split('/');\n\n  if (segments.some(isUnsafePathSegment)) {\n    throw new Error('Path must not contain parent directory segments.');\n  }\n\n  const url = new URL(baseUrl);\n  const basePath = url.pathname.endsWith('/') ? url.pathname : `${url.pathname}/`;\n  url.pathname = `${basePath}${sanitizedPath}`.replaceAll(/\\/{2,}/g, '/');\n\n  if (url.pathname.includes('/../') || url.pathname.endsWith('/..')) {\n    throw new Error('Path must not escape the base URL path.');\n  }\n\n  return url.toString();\n}\n\n/**\n * Returns true when a single path segment is unsafe to append to a base URL.\n *\n * A segment is unsafe when it contains parent-directory traversal (`..`), embedded path\n * separators (`/` or `\\`) \u2014 including any percent-encoded variants \u2014 or malformed percent\n * encoding (which is always rejected so callers cannot smuggle traversal past `decodeURIComponent`\n * by triggering a `URIError`).\n */\nfunction isUnsafePathSegment(segment: string): boolean {\n  if (segment === '..') {\n    return true;\n  }\n\n  let decodedSegment: string;\n  try {\n    decodedSegment = decodeURIComponent(segment);\n  } catch {\n    return true;\n  }\n\n  return decodedSegment === '..' || decodedSegment.includes('/') || decodedSegment.includes('\\\\');\n}\n\nfunction parseIpv4(hostname: string): [number, number, number, number] | undefined {\n  const parts = hostname.split('.');\n  if (parts.length !== 4) {\n    return undefined;\n  }\n\n  const octets = parts.map((part) => {\n    if (!/^\\d+$/.test(part)) {\n      return Number.NaN;\n    }\n    return Number(part);\n  });\n\n  if (!octets.every((octet) => Number.isInteger(octet) && octet >= 0 && octet <= 255)) {\n    return undefined;\n  }\n\n  return octets as [number, number, number, number];\n}\n\nfunction isPrivateIpv4([a, b]: [number, number, number, number]): boolean {\n  if (a === 0) { return true; } // 0.0.0.0/8\n  if (a === 10) { return true; } // 10.0.0.0/8\n  if (a === 100 && b >= 64 && b <= 127) { return true; } // 100.64.0.0/10\n  if (a === 127) { return true; } // 127.0.0.0/8\n  if (a === 169 && b === 254) { return true; } // 169.254.0.0/16\n  if (a === 172 && b >= 16 && b <= 31) { return true; } // 172.16.0.0/12\n  if (a === 192 && b === 168) { return true; } // 192.168.0.0/16\n  if (a >= 224) { return true; } // multicast/reserved\n\n  return false;\n}\n\nfunction isPrivateIpv6(hostname: string): boolean {\n  const hextets = parseIpv6(hostname);\n  if (hextets === undefined) {\n    return false;\n  }\n\n  const [h0, h1, h2, h3, h4, h5, h6, h7] = hextets;\n  const firstSixZero = h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0;\n\n  if (hextets.every((hextet) => hextet === 0)) { return true; } // ::/128\n  if (firstSixZero && h6 === 0 && h7 === 1) { return true; } // ::1/128\n\n  if ((h0 & 0xfe00) === 0xfc00) { return true; } // fc00::/7\n  if ((h0 & 0xffc0) === 0xfe80) { return true; } // fe80::/10\n  if ((h0 & 0xff00) === 0xff00) { return true; } // ff00::/8\n\n  if (h0 === 0x0064 && h1 === 0xff9b && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0) {\n    return isPrivateIpv4(ipv6HextetsToIpv4(h6, h7)); // 64:ff9b::/96\n  }\n\n  if (h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0xffff) {\n    return isPrivateIpv4(ipv6HextetsToIpv4(h6, h7)); // ::ffff:0:0/96\n  }\n\n  if (firstSixZero) {\n    return true; // deprecated IPv4-compatible ::/96\n  }\n\n  return false;\n}\n\nfunction parseIpv6(hostname: string): [number, number, number, number, number, number, number, number] | undefined {\n  const [left, right, extra] = hostname.split('::');\n  if (extra !== undefined) {\n    return undefined;\n  }\n\n  const leftParts = left === '' ? [] : left.split(':');\n  const rightParts = right === undefined || right === '' ? [] : right.split(':');\n  const parts = expandIpv4Suffix([...leftParts, ...rightParts]);\n  if (parts === undefined) {\n    return undefined;\n  }\n\n  if (parts.length > 8 || (right === undefined && parts.length !== 8) || (right !== undefined && parts.length >= 8)) {\n    return undefined;\n  }\n\n  const parsedParts = parts.map((part) => {\n    if (!/^[0-9a-f]{1,4}$/.test(part)) {\n      return Number.NaN;\n    }\n    return Number.parseInt(part, 16);\n  });\n  if (!parsedParts.every((part) => Number.isInteger(part) && part >= 0 && part <= 0xffff)) {\n    return undefined;\n  }\n\n  if (right === undefined) {\n    return parsedParts as [number, number, number, number, number, number, number, number];\n  }\n\n  const fill = new Array(8 - parsedParts.length).fill(0);\n  return [\n    ...parsedParts.slice(0, leftParts.length),\n    ...fill,\n    ...parsedParts.slice(leftParts.length),\n  ] as [number, number, number, number, number, number, number, number];\n}\n\nfunction expandIpv4Suffix(parts: string[]): string[] | undefined {\n  const last = parts.at(-1);\n  if (!last?.includes('.')) {\n    return parts;\n  }\n\n  const ipv4 = parseIpv4(last);\n  if (ipv4 === undefined) {\n    return undefined;\n  }\n\n  const [a, b, c, d] = ipv4;\n  return [\n    ...parts.slice(0, -1),\n    (((a << 8) | b) & 0xffff).toString(16),\n    (((c << 8) | d) & 0xffff).toString(16),\n  ];\n}\n\nfunction ipv6HextetsToIpv4(high: number, low: number): [number, number, number, number] {\n  return [\n    (high >> 8) & 0xff,\n    high & 0xff,\n    (low >> 8) & 0xff,\n    low & 0xff,\n  ];\n}\n"],
  "mappings": "6FAGO,IAAKA,QACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SAFCA,QAAA,IAmCNC,EAAN,KAA6C,CAA7C,cACE,KAAQ,SAAqB,SAE7B,YAAYC,EAA0B,CACpC,KAAK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AAO,SAASA,EAAM,EAAE,EAFtB,OAAO,GAGjB,EACD,GAAI,CAACuB,EAAY,MAAOvB,GAAS,OAAO,UAAUA,CAAI,GAAKA,GAAQ,GAAKA,GAAQ,KAAM,EACpF,OAGF,GAAIkB,IAAU,OACZ,OAAOK,EAGT,IAAMC,EAAO,IAAI,MAAM,EAAID,EAAY,MAAM,EAAE,KAAK,CAAC,EACrD,MAAO,CACL,GAAGA,EAAY,MAAM,EAAGH,EAAU,MAAM,EACxC,GAAGI,EACH,GAAGD,EAAY,MAAMH,EAAU,MAAM,CACvC,CACF,CAEA,SAASE,GAAiBxB,EAAuC,CAC/D,IAAM2B,EAAO3B,EAAM,GAAG,EAAE,EACxB,GAAI,CAAC2B,GAAM,SAAS,GAAG,EACrB,OAAO3B,EAGT,IAAM/B,EAAOC,GAAUyD,CAAI,EAC3B,GAAI1D,IAAS,OACX,OAGF,GAAM,CAACmC,EAAGC,EAAGuB,EAAGC,CAAC,EAAI5D,EACrB,MAAO,CACL,GAAG+B,EAAM,MAAM,EAAG,EAAE,IACjBI,GAAK,EAAKC,GAAK,OAAQ,SAAS,EAAE,IAClCuB,GAAK,EAAKC,GAAK,OAAQ,SAAS,EAAE,CACvC,CACF,CAEA,SAASX,GAAkBY,EAAcC,EAA+C,CACtF,MAAO,CACJD,GAAQ,EAAK,IACdA,EAAO,IACNC,GAAO,EAAK,IACbA,EAAM,GACR,CACF",
  "names": ["LogLevel", "EnboxLogger", "logLevel", "message", "logger", "durationUnitMultipliers", "nowMs", "parseDurationInMilliseconds", "duration", "match", "durationUnit", "multiplier", "durationInMilliseconds", "timed", "label", "fn", "log", "logger", "start", "result", "elapsed", "err", "MAX_TIMER_DELAY_MS", "sleep", "signal", "remaining", "resolve", "reject", "timer", "onAbort", "schedule", "delay", "now", "isPositiveIntegerOrInfinity", "value", "assertPositiveIntegerOrInfinity", "name", "assertTtl", "ttl", "unrefTimer", "timer", "entryCompare", "left", "right", "TtlCache", "options", "dispose", "max", "noDisposeOnSet", "noUpdateTTL", "updateAgeOnGet", "key", "existing", "current", "expiresAt", "sequence", "shouldDispose", "entry", "entries", "hadTimer", "purged", "remainingTtl", "currentTime", "purgeState", "evictCandidate", "currentEntry", "evictKey", "evictEntry", "evictExpiresAt", "evictSequence", "selectedExpiresAt", "selectedSequence", "reason", "delay", "MAX_TIMER_DELAY_MS", "nextExpiration", "compareUtf16", "left", "right", "canonicalizeJson", "value", "object", "canonical", "key", "entry", "canonicalJsonStringify", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "toArrayBufferBackedArray", "isByteArrayWithArrayBuffer", "b", "toArrayBufferBackedArray", "base", "ALPHABET", "name", "caseInsensitive", "BASE_MAP", "j", "i", "x", "xc", "xl", "xu", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "caseInsensitive", "base_x_default", "coerce", "string", "alphabetIdx", "bitsPerChar", "end", "out", "bits", "buffer", "written", "i", "value", "data", "pad", "mask", "createAlphabetIdx", "lower", "upper", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base58btc", "baseX", "base58flickr", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "isArrayBufferSlice", "arrayBufferView", "isAsyncIterable", "obj", "isDefined", "arg", "universalTypeOf", "value", "typeString", "match", "_", "type", "textEncoder", "textDecoder", "Convert", "_Convert", "data", "format", "isAsyncIterable", "base58btc", "base64url", "universalTypeOf", "isArrayBufferSlice", "base32z", "u8a", "string", "chunks", "chunk", "hexes", "v", "i", "hex", "byte", "text", "str", "dataType", "byteValue", "arrayBuffer", "pendingFallbackOperations", "runWithCrossContextLock", "name", "operation", "lockManager", "runSerializedByKey", "pending", "key", "previous", "operationPromise", "completion", "base36", "baseX", "base36upper", "varint_exports", "__export", "decode", "encodeTo", "encodingLength", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "toArrayBufferBackedArray", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "_CID", "version", "code", "multihash", "bytes", "toArrayBufferBackedArray", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "base36", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "_Multicodec", "options", "code", "data", "name", "prefixLength", "varint_exports", "dataWithPrefix", "prefixedData", "_", "codec", "codeByteLength", "Multicodec", "isExplicitlyOffline", "isEmptyObject", "obj", "removeEmptyObjects", "key", "value", "removeUndefinedProperties", "omitUndefined", "input", "result", "MemoryStore", "id", "key", "Stream", "_Stream", "blob", "bytes", "chunkLength", "offset", "controller", "end", "readableStream", "reader", "done", "value", "iterableStream", "Convert", "streamLength", "fillValue", "bytesRemaining", "enqueueChunk", "currentChunkLength", "chunk", "c", "obj", "isPrivateHostname", "hostname", "h", "zoneIndex", "ipv4", "parseIpv4", "isPrivateIpv4", "isPrivateIpv6", "DEFAULT_PUBLIC_URL_PROTOCOLS", "PublicUrlValidationError", "message", "assertPublicUrl", "url", "description", "options", "parsedUrl", "allowedProtocols", "DEFAULT_MAX_REDIRECTS", "REDIRECT_STATUS_CODES", "fetchPublicUrl", "init", "maxRedirects", "fetchFn", "currentUrl", "attempt", "response", "location", "concatenateUrl", "baseUrl", "path", "sanitizedPath", "isUnsafePathSegment", "basePath", "segment", "decodedSegment", "parts", "octets", "part", "octet", "a", "b", "hextets", "parseIpv6", "h0", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "firstSixZero", "hextet", "ipv6HextetsToIpv4", "left", "right", "extra", "leftParts", "rightParts", "expandIpv4Suffix", "parsedParts", "fill", "last", "c", "d", "high", "low"]
}
