{"version":3,"sources":["/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-I5JVSFNV.cjs","../src/nats/nats.ts","../src/nats/shared-connection.ts","../src/nats/nats-provider.tsx","../src/nats/use-nats-subscription.ts"],"names":["useRef","useEffect","useState"],"mappings":"AAAA,+8BAAY;AACZ;AACA;ACqMA,SAAS,gBAAA,CAAA,EAAyB;AAGhC,EAAA,GAAA,CAAI,OAAO,OAAA,IAAW,WAAA,EAAa;AACjC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,IACF,CAAA;AAAA,EACF;AACF;AAEA,MAAA,SAAe,UAAA,CAAA,EAAa;AAE1B,EAAA,OAAO,4DAAA,CAAO,SAAS,GAAA;AACzB;AASA,SAAS,aAAA,CAAc,IAAA,EAAkB,IAAA,EAAgD;AACvF,EAAA,GAAA,CAAI,CAAC,IAAA,EAAM,OAAO,KAAA,CAAA;AAClB,EAAA,GAAA,CAAI,OAAQ,IAAA,CAAqB,IAAA,IAAQ,UAAA,EAAY,OAAO,IAAA;AAE5D,EAAA,MAAM,EAAA,EAAI,IAAA,CAAK,OAAA,CAAQ,CAAA;AACvB,EAAA,IAAA,CAAA,MAAW,CAAC,CAAA,EAAG,CAAC,EAAA,GAAK,MAAA,CAAO,OAAA,CAAQ,IAA8B,CAAA,EAAG;AACnE,IAAA,GAAA,CAAI,EAAA,IAAM,KAAA,EAAA,GAAa,EAAA,IAAM,IAAA,EAAM,CAAA,CAAE,GAAA,CAAI,CAAA,EAAG,MAAA,CAAO,CAAC,CAAC,CAAA;AAAA,EACvD;AACA,EAAA,OAAO,CAAA;AACT;AAGA,SAAS,YAAA,CAAA,EAAuB;AAC9B,EAAA,MAAM,IAAA,EAAM,IAAI,WAAA,CAAY,CAAC,CAAA;AAC7B,EAAA,MAAA,CAAO,eAAA,CAAgB,GAAG,CAAA;AAC1B,EAAA,OAAO,GAAA,CAAI,CAAC,EAAA,EAAA,CAAK,WAAA,EAAa,CAAA,CAAA;A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AAA,EAAIC,6BAAAA,CAA6B,EAAA,GAAO,OAAO,YAAA,IAAgB,YAAA,EAAc,IAAI,WAAA,CAAY,EAAA,EAAI,IAAK,CAAA;AAEpH,EAAA,MAAM,QAAA,EAAU,gCAAA;AAAA,IACd,MAAA,CAAO,GAAA,EAAA,GAAa;AAClB,MAAA,GAAA,CAAI,CAAC,OAAA,EAAS,MAAA;AACd,MAAA,IAAI;AACF,QAAA,MAAM,OAAA,EAAS,IAAA,CAAK,KAAA,CAAM,OAAA,CAAQ,MAAA,CAAO,GAAA,CAAI,IAAI,CAAC,CAAA;AAClD,QAAA,MAAM,UAAA,CAAW,OAAA,CAAQ,MAAA,EAAQ,GAAG,CAAA;AAAA,MACtC,EAAA,YAAQ;AAAA,MAER;AAAA,IACF,CAAA;AAAA,IACA,CAAC,OAAO;AAAA,EACV,CAAA;AAEA,EAAA,OAAO,mBAAA,CAAoB,OAAA,EAAS,OAAA,EAAS,OAAO,CAAA;AACtD;AJsnBA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,miBAAC","file":"/home/runner/work/openframe-oss-lib/openframe-oss-lib/openframe-frontend-core/dist/chunk-I5JVSFNV.cjs","sourcesContent":[null,"import type {\n  ConnectionOptions,\n  Consumer,\n  ConsumerEvents,\n  ConsumerMessages,\n  DebugEvents,\n  Events,\n  JsMsg,\n  MsgHdrs as NatsHeaders,\n  Msg,\n  NatsConnection,\n  Subscription,\n} from 'nats.ws';\n\nexport type { JsMsg, Msg, Subscription } from 'nats.ws';\n\nexport type JetStreamDeliverPolicy = 'new' | 'byStartSequence';\n\nexport interface JetStreamOrderedSubscribeOptions {\n  streamName: string;\n  filterSubject: string;\n  deliverPolicy: JetStreamDeliverPolicy;\n  /** Required when deliverPolicy === 'byStartSequence'. */\n  optStartSeq?: number;\n  /**\n   * Auto-cleanup the ephemeral consumer after this idle time. Defaults to\n   * nats.ws's own. Applies to the consumer created first: nats.ws only reads it\n   * when the start sequence is the one it was built with, so every consumer it\n   * recreates afterwards reverts to the library default.\n   */\n  inactiveThresholdMs?: number;\n  /** AbortSignal to tear down the consumer. */\n  signal?: AbortSignal;\n  /**\n   * The ordered consumer had to be rebuilt: the server dropped the ephemeral\n   * consumer (its inactivity threshold elapsed while the page was suspended or\n   * offline), heartbeats were missed, or a sequence gap was detected. nats.ws\n   * recreates it from the last delivered sequence, so this is NOT an error —\n   * but everything that aged out of the stream while it was gone is\n   * unrecoverable from the tail, and no connection event announces it (the\n   * WebSocket never dropped). Callers that keep persisted history alongside\n   * the live tail must refetch it here, or they keep showing a snapshot from\n   * before the gap.\n   */\n  onRecovered?: () => void;\n}\n\nexport interface JetStreamSubscriptionHandle {\n  unsubscribe(): void;\n}\n\nexport interface NatsClientOptions {\n  /**\n   * NATS server URL(s), for example:\n   * - \"wss://nats.example.com:443\"\n   * - [\"wss://nats-1.example.com:443\", \"wss://nats-2.example.com:443\"]\n   */\n  servers: string | string[];\n\n  /**\n   * Connection name (shows up in NATS monitoring).\n   */\n  name?: string;\n\n  /**\n   * Auth options (pick one: token or user/pass).\n   */\n  token?: string;\n  user?: string;\n  pass?: string;\n\n  /**\n   * Reconnect behavior.\n   */\n  reconnect?: boolean;\n  maxReconnectAttempts?: number;\n  reconnectTimeWaitMs?: number;\n\n  /**\n   * Exponential backoff for reconnect delays.\n   * When set, uses `reconnectDelayHandler` from nats.ws under the hood,\n   * overriding `reconnectTimeWaitMs`.\n   */\n  exponentialBackoff?: {\n    /** Initial delay in ms (default: 1000) */\n    initialDelayMs?: number;\n    /** Maximum delay cap in ms (default: 30000) */\n    maxDelayMs?: number;\n    /** Multiplier per attempt (default: 2) */\n    multiplier?: number;\n    /** Add random jitter 0-50% of delay to prevent thundering herd (default: true) */\n    jitter?: boolean;\n  };\n\n  /**\n   * Ping behavior (keep-alive).\n   */\n  pingIntervalMs?: number;\n  maxPingOut?: number;\n\n  /**\n   * Optional inbox prefix (useful if you want to isolate request/reply inboxes).\n   */\n  inboxPrefix?: string;\n\n  /**\n   * Connection timeout in milliseconds (maps to `nats.ws` connect option `timeout`).\n   * If you see `NatsError: TIMEOUT` during connect, increase this.\n   */\n  connectTimeoutMs?: number;\n}\n\nexport interface NatsSubscribeOptions {\n  /**\n   * Queue group for load-balancing messages across subscribers.\n   */\n  queue?: string;\n\n  /**\n   * Auto-unsubscribe after receiving this many messages.\n   */\n  max?: number;\n\n  /**\n   * Abort signal to stop message iteration and unsubscribe.\n   */\n  signal?: AbortSignal;\n}\n\nexport type NatsHeadersInit = Record<string, string> | NatsHeaders | undefined;\n\nexport interface NatsPublishOptions {\n  headers?: NatsHeadersInit;\n}\n\nexport interface NatsRequestOptions {\n  timeoutMs?: number;\n  headers?: NatsHeadersInit;\n}\n\nexport interface NatsSubscriptionHandle {\n  readonly subscription: Subscription;\n  unsubscribe(): void;\n}\n\nexport type NatsStatus = 'connecting' | 'connected' | 'disconnected' | 'reconnecting' | 'closed' | 'error';\n\nexport interface NatsStatusEvent {\n  status: NatsStatus;\n  data?: unknown;\n}\n\nexport interface NatsClient {\n  connect(): Promise<void>;\n  close(): Promise<void>;\n\n  isConnected(): boolean;\n\n  publishBytes(subject: string, payload: Uint8Array, options?: NatsPublishOptions): void;\n  publishString(subject: string, payload: string, options?: NatsPublishOptions): void;\n  publishJson<T>(subject: string, payload: T, options?: NatsPublishOptions): void;\n\n  requestBytes(subject: string, payload: Uint8Array, options?: NatsRequestOptions): Promise<Msg>;\n  requestString(subject: string, payload: string, options?: NatsRequestOptions): Promise<string>;\n  requestJson<TResponse, TRequest = unknown>(\n    subject: string,\n    payload: TRequest,\n    options?: NatsRequestOptions,\n  ): Promise<TResponse>;\n\n  subscribeBytes(\n    subject: string,\n    onMessage: (msg: Msg) => void | Promise<void>,\n    options?: NatsSubscribeOptions,\n  ): NatsSubscriptionHandle;\n  subscribeString(\n    subject: string,\n    onMessage: (payload: string, msg: Msg) => void | Promise<void>,\n    options?: NatsSubscribeOptions,\n  ): NatsSubscriptionHandle;\n  subscribeJson<T>(\n    subject: string,\n    onMessage: (payload: T, msg: Msg) => void | Promise<void>,\n    options?: NatsSubscribeOptions,\n  ): NatsSubscriptionHandle;\n\n  /**\n   * Subscribe to a JetStream subject via an ephemeral OrderedConsumer (no acks).\n   * Use `optStartSeq` with `deliverPolicy: 'byStartSequence'` to resume from a known offset,\n   * or `deliverPolicy: 'new'` to live-tail.\n   */\n  subscribeJetStreamOrdered(\n    onMessage: (msg: JsMsg) => void | Promise<void>,\n    options: JetStreamOrderedSubscribeOptions,\n  ): Promise<JetStreamSubscriptionHandle>;\n\n  onStatus(listener: (event: NatsStatusEvent) => void): () => void;\n}\n\nfunction assertClientSide(): void {\n  // This wrapper is meant for browser/Tauri usage via WebSockets.\n  // Keep it safe to import from Next.js server bundles by throwing only when used.\n  if (typeof window === 'undefined') {\n    throw new Error(\n      'NATS client can only connect from the browser/runtime with WebSocket support (window is undefined).',\n    );\n  }\n}\n\nasync function importNats() {\n  // Browser/Tauri only: always use the websocket client (no Node-only deps).\n  return import('nats.ws');\n}\n\n/**\n * The module's own shape, derived from the one dynamic `import()` above rather\n * than restated as `typeof import('nats.ws')` at every use site. Keeps a single\n * source of truth and stays a pure type — nothing here reaches the bundle.\n */\ntype NatsModule = Awaited<ReturnType<typeof importNats>>;\n\nfunction toNatsHeaders(nats: NatsModule, init: NatsHeadersInit): NatsHeaders | undefined {\n  if (!init) return undefined;\n  if (typeof (init as NatsHeaders).get === 'function') return init as NatsHeaders;\n\n  const h = nats.headers();\n  for (const [k, v] of Object.entries(init as Record<string, string>)) {\n    if (v !== undefined && v !== null) h.set(k, String(v));\n  }\n  return h;\n}\n\n/** Returns a cryptographically random float in [0, 1). */\nfunction cryptoRandom(): number {\n  const buf = new Uint32Array(1);\n  crypto.getRandomValues(buf);\n  return buf[0] / (0xffffffff + 1);\n}\n\ninterface ExponentialBackoffHandle {\n  handler: () => number;\n  reset: () => void;\n}\n\nfunction createExponentialBackoffHandler(\n  opts: NonNullable<NatsClientOptions['exponentialBackoff']>,\n): ExponentialBackoffHandle {\n  const initialDelay = opts.initialDelayMs ?? 1000;\n  const maxDelay = opts.maxDelayMs ?? 30_000;\n  const multiplier = opts.multiplier ?? 2;\n  const jitter = opts.jitter ?? true;\n\n  let attempt = 0;\n\n  return {\n    handler: (): number => {\n      const delay = Math.min(initialDelay * multiplier ** attempt, maxDelay);\n      attempt++;\n      return jitter ? delay * (0.5 + cryptoRandom() * 0.5) : delay;\n    },\n    reset: () => {\n      attempt = 0;\n    },\n  };\n}\n\nfunction mapOptionsToConnectionOptions(opts: NatsClientOptions, backoff?: ExponentialBackoffHandle): ConnectionOptions {\n  return {\n    servers: opts.servers,\n    name: opts.name,\n    token: opts.token,\n    user: opts.user,\n    pass: opts.pass,\n    timeout: opts.connectTimeoutMs ?? 15000,\n    reconnect: opts.reconnect ?? true,\n    maxReconnectAttempts: opts.maxReconnectAttempts,\n    reconnectTimeWait: opts.reconnectTimeWaitMs,\n    reconnectDelayHandler: backoff?.handler,\n    pingInterval: opts.pingIntervalMs,\n    maxPingOut: opts.maxPingOut,\n    inboxPrefix: opts.inboxPrefix,\n  };\n}\n\n/**\n * Map a nats.ws status event onto our own status vocabulary.\n *\n * Exact enum matches, never substring tests. Substring matching reported\n * `staleConnection` and `client initiated reconnect` as CONNECTED — both\n * contain \"connect\" and neither contains \"disconnect\" — so the wrapper\n * announced a live connection at the exact moment the client had given up on\n * one. Downstream that is worse than silence: `NatsProvider` reads a\n * `connected` that follows an earlier connection as a RECONNECT and bumps\n * `reconnectionCount`, which every subscriber takes as \"the tail came back\" —\n * resubscribing against a dying client and refetching persisted history.\n * `staleConnection` is the one an idle mobile app hits routinely: no pong\n * within `pingInterval * maxPingOut`, i.e. after a spell in the background.\n *\n * `StaleConnection` maps to `disconnected` rather than being ignored on the\n * grounds that `Disconnect` follows it anyway — it does not always. nats.ws\n * tears the transport down by draining `bufferedAmount` first, and a\n * black-holed socket (no FIN, which is how a mobile link usually dies) never\n * drains, so `Disconnect` can fail to arrive at all. Reporting it is then the\n * only honest answer available: consumers stop trusting a tail the client has\n * already given up on. It does NOT by itself recover that connection — the\n * retry it arms short-circuits, because a protocol that never closed still\n * reports `isConnected()`. Getting the socket back from that state needs a\n * force-close path the client does not currently expose.\n *\n * The enums arrive as arguments rather than through a module-scope import\n * because `nats.ws` is loaded lazily (see {@link importNats}) to keep this\n * module safe to import from a Next server bundle. A hand-copied literal is\n * what this is undoing, so it is not reintroduced here.\n */\nfunction mapNatsTypeToStatus(\n  type: Events | DebugEvents,\n  events: NatsModule['Events'],\n  debugEvents: NatsModule['DebugEvents'],\n): NatsStatus | null {\n  switch (type) {\n    case events.Disconnect:\n      return 'disconnected';\n    case events.Reconnect:\n      return 'connected';\n    case events.Error:\n      return 'error';\n    case debugEvents.Reconnecting:\n    case debugEvents.ClientInitiatedReconnect:\n      return 'reconnecting';\n    case debugEvents.StaleConnection:\n      return 'disconnected';\n    // Events.Update (cluster gossip), Events.LDM and DebugEvents.PingTimer say\n    // nothing about reachability.\n    default:\n      return null;\n  }\n}\n\n/**\n * Report an ordered consumer rebuilding itself.\n *\n * nats.ws announces this on the message iterator's status channel and nowhere\n * else — the iterator keeps yielding, the WebSocket never drops, and nothing\n * consumes that channel unless someone asks for it. That silence is what lets a\n * tail resume after a suspended page having permanently missed whatever expired\n * from the stream meanwhile: the recreation resumes from the last delivered\n * sequence, so the gap is invisible from the tail alone.\n *\n * `recreatedEvent` is nats.ws's own enum value rather than a literal of ours: a\n * copy that drifted from the library would kill this signal silently, which is\n * the failure mode the signal exists to prevent.\n *\n * The status channel is closed along with the iterator, which ends this loop.\n */\nfunction watchForRecovery(\n  iter: ConsumerMessages,\n  recreatedEvent: ConsumerEvents.OrderedConsumerRecreated,\n  onRecovered?: () => void,\n): void {\n  if (!onRecovered) return;\n  void (async () => {\n    try {\n      const status = await iter.status();\n      for await (const event of status) {\n        if (event.type !== recreatedEvent) continue;\n        try {\n          onRecovered();\n        } catch (e) {\n          // A caller that throws must not take the watch down with it — this\n          // loop is the only thing reporting recoveries for this subscription.\n          console.warn('[nats] onRecovered threw:', e);\n        }\n      }\n    } catch {\n      // Status ends with the subscription — nothing left to report.\n    }\n  })();\n}\n\nexport function createNatsClient(options: NatsClientOptions): NatsClient {\n  let nc: NatsConnection | null = null;\n  let statusLoopAbort: AbortController | null = null;\n  let connectInFlight: Promise<void> | null = null;\n\n  const backoff = options.exponentialBackoff ? createExponentialBackoffHandler(options.exponentialBackoff) : undefined;\n\n  const statusListeners = new Set<(event: NatsStatusEvent) => void>();\n\n  function emitStatus(event: NatsStatusEvent) {\n    for (const listener of statusListeners) {\n      try {\n        listener(event);\n      } catch {\n        // ignore listener failures\n      }\n    }\n  }\n\n  async function connect(): Promise<void> {\n    if (nc && !nc.isClosed()) return;\n    if (connectInFlight) {\n      await connectInFlight;\n      return;\n    }\n    assertClientSide();\n\n    connectInFlight = (async () => {\n      try {\n        emitStatus({ status: 'connecting' });\n\n        const nats = await importNats();\n        const conn = await nats.connect(mapOptionsToConnectionOptions(options, backoff));\n        nc = conn;\n\n        emitStatus({ status: 'connected' });\n\n        statusLoopAbort = new AbortController();\n        const signal = statusLoopAbort.signal;\n\n        (async () => {\n          try {\n            for await (const s of conn.status()) {\n              if (signal.aborted) return;\n              const mapped = mapNatsTypeToStatus(s.type, nats.Events, nats.DebugEvents);\n              if (mapped) {\n                if (mapped === 'connected' && backoff) {\n                  backoff.reset();\n                }\n                emitStatus({ status: mapped, data: s.data });\n              }\n            }\n          } catch (e) {\n            if (!signal.aborted) {\n              emitStatus({ status: 'error', data: e });\n\n              if (nc === conn && conn.isClosed()) {\n                nc = null;\n                emitStatus({ status: 'closed' });\n              }\n            }\n          }\n        })().catch(() => {\n          // ignore\n        });\n      } finally {\n        connectInFlight = null;\n      }\n    })();\n\n    await connectInFlight;\n  }\n\n  async function close(): Promise<void> {\n    const conn = nc;\n    nc = null;\n\n    if (statusLoopAbort) {\n      try {\n        statusLoopAbort.abort();\n      } catch {\n        // ignore\n      }\n      statusLoopAbort = null;\n    }\n\n    if (!conn) return;\n    try {\n      await conn.drain();\n    } finally {\n      try {\n        await conn.close();\n      } finally {\n        emitStatus({ status: 'closed' });\n      }\n    }\n  }\n\n  function requireConnection(): NatsConnection {\n    if (!nc) throw new Error('NATS is not connected. Call client.connect() first.');\n    return nc;\n  }\n\n  function isConnected(): boolean {\n    return nc !== null && !nc.isClosed();\n  }\n\n  function publishBytes(subject: string, payload: Uint8Array, opts?: NatsPublishOptions): void {\n    const conn = requireConnection();\n    (async () => {\n      const nats = await importNats();\n      conn.publish(subject, payload, { headers: toNatsHeaders(nats, opts?.headers) });\n    })().catch((e: unknown) => emitStatus({ status: 'error', data: e }));\n  }\n\n  function publishString(subject: string, payload: string, opts?: NatsPublishOptions): void {\n    (async () => {\n      const nats = await importNats();\n      const sc = nats.StringCodec();\n      publishBytes(subject, sc.encode(payload), opts);\n    })().catch((e: unknown) => emitStatus({ status: 'error', data: e }));\n  }\n\n  function publishJson<T>(subject: string, payload: T, opts?: NatsPublishOptions): void {\n    (async () => {\n      const nats = await importNats();\n      const jc = nats.JSONCodec<T>();\n      publishBytes(subject, jc.encode(payload), opts);\n    })().catch((e: unknown) => emitStatus({ status: 'error', data: e }));\n  }\n\n  async function requestBytes(subject: string, payload: Uint8Array, opts?: NatsRequestOptions): Promise<Msg> {\n    const conn = requireConnection();\n    const nats = await importNats();\n    const msg = await conn.request(subject, payload, {\n      timeout: opts?.timeoutMs ?? 2000,\n      headers: toNatsHeaders(nats, opts?.headers),\n    });\n    return msg;\n  }\n\n  async function requestString(subject: string, payload: string, opts?: NatsRequestOptions): Promise<string> {\n    const nats = await importNats();\n    const sc = nats.StringCodec();\n    const msg = await requestBytes(subject, sc.encode(payload), opts);\n    return sc.decode(msg.data);\n  }\n\n  async function requestJson<TResponse, TRequest = unknown>(\n    subject: string,\n    payload: TRequest,\n    opts?: NatsRequestOptions,\n  ): Promise<TResponse> {\n    const nats = await importNats();\n    const reqCodec = nats.JSONCodec<TRequest>();\n    const resCodec = nats.JSONCodec<TResponse>();\n    const msg = await requestBytes(subject, reqCodec.encode(payload), opts);\n    return resCodec.decode(msg.data);\n  }\n\n  function subscribeBytes(\n    subject: string,\n    onMessage: (msg: Msg) => void | Promise<void>,\n    opts?: NatsSubscribeOptions,\n  ): NatsSubscriptionHandle {\n    const conn = requireConnection();\n    const sub = conn.subscribe(subject, { queue: opts?.queue });\n    if (typeof opts?.max === 'number') sub.unsubscribe(opts.max);\n\n    const abortController = new AbortController();\n    const signal = opts?.signal ?? abortController.signal;\n\n    (async () => {\n      try {\n        for await (const msg of sub) {\n          if (signal.aborted) break;\n          await onMessage(msg);\n        }\n      } catch (e) {\n        emitStatus({ status: 'error', data: e });\n      } finally {\n        try {\n          sub.unsubscribe();\n        } catch {\n          // ignore\n        }\n      }\n    })().catch((e: unknown) => emitStatus({ status: 'error', data: e }));\n\n    return {\n      subscription: sub,\n      unsubscribe() {\n        try {\n          abortController.abort();\n        } catch {\n          // ignore\n        }\n        try {\n          sub.unsubscribe();\n        } catch {\n          // ignore\n        }\n      },\n    };\n  }\n\n  function subscribeString(\n    subject: string,\n    onMessage: (payload: string, msg: Msg) => void | Promise<void>,\n    opts?: NatsSubscribeOptions,\n  ): NatsSubscriptionHandle {\n    return subscribeBytes(\n      subject,\n      async msg => {\n        const nats = await importNats();\n        const sc = nats.StringCodec();\n        await onMessage(sc.decode(msg.data), msg);\n      },\n      opts,\n    );\n  }\n\n  function subscribeJson<T>(\n    subject: string,\n    onMessage: (payload: T, msg: Msg) => void | Promise<void>,\n    opts?: NatsSubscribeOptions,\n  ): NatsSubscriptionHandle {\n    return subscribeBytes(\n      subject,\n      async msg => {\n        const nats = await importNats();\n        const jc = nats.JSONCodec<T>();\n        await onMessage(jc.decode(msg.data), msg);\n      },\n      opts,\n    );\n  }\n\n  async function subscribeJetStreamOrdered(\n    onMessage: (msg: JsMsg) => void | Promise<void>,\n    opts: JetStreamOrderedSubscribeOptions,\n  ): Promise<JetStreamSubscriptionHandle> {\n    const conn = requireConnection();\n    if (opts.signal?.aborted) {\n      return { unsubscribe() {} };\n    }\n\n    const nats = await importNats();\n    if (opts.signal?.aborted) {\n      return { unsubscribe() {} };\n    }\n\n    const js = conn.jetstream();\n    const consumer: Consumer = await js.consumers.get(opts.streamName, {\n      filterSubjects: opts.filterSubject,\n      deliver_policy: nats.DeliverPolicy.StartSequence,\n      opt_start_seq: opts.optStartSeq ?? 0,\n      // Milliseconds, NOT nanoseconds: nats.ws runs this through its own\n      // `nanos()` before it reaches the server. Pre-converting here multiplied\n      // it by 1e6 twice, putting the threshold ~9.5 years out — so the ephemeral\n      // consumer never expired. Two consequences, both silent: every reconnect\n      // and dialog switch orphaned a consumer server-side, and a client that\n      // stopped pulling never got the `consumer deleted` that drives the ordered\n      // consumer's self-repair. Undefined stays undefined so nats.ws applies its\n      // own default rather than a copy of it.\n      inactive_threshold: opts.inactiveThresholdMs,\n    });\n\n    const iterRef: { current: ConsumerMessages | null } = { current: null };\n    let closed = false;\n\n    const onAbort = () => {\n      void teardown();\n    };\n    opts.signal?.addEventListener('abort', onAbort, { once: true });\n\n    async function teardown(): Promise<void> {\n      if (closed) return;\n      closed = true;\n      opts.signal?.removeEventListener('abort', onAbort);\n      const iter = iterRef.current;\n      iterRef.current = null;\n      if (iter) {\n        try {\n          await iter.close();\n        } catch {\n          // ignore\n        }\n      }\n    }\n\n    if (opts.signal?.aborted) {\n      void teardown();\n      return { unsubscribe() {} };\n    }\n\n    (async () => {\n      try {\n        const iter = await consumer.consume();\n        if (closed) {\n          try {\n            await iter.close();\n          } catch {\n            // ignore\n          }\n          return;\n        }\n        iterRef.current = iter;\n        watchForRecovery(iter, nats.ConsumerEvents.OrderedConsumerRecreated, opts.onRecovered);\n        for await (const msg of iter) {\n          if (closed) break;\n          try {\n            await onMessage(msg);\n          } catch (e) {\n            emitStatus({ status: 'error', data: e });\n          }\n        }\n      } catch (e) {\n        if (!closed) emitStatus({ status: 'error', data: e });\n      }\n    })().catch((e: unknown) => emitStatus({ status: 'error', data: e }));\n\n    return {\n      unsubscribe() {\n        void teardown();\n      },\n    };\n  }\n\n  function onStatus(listener: (event: NatsStatusEvent) => void): () => void {\n    statusListeners.add(listener);\n    return () => statusListeners.delete(listener);\n  }\n\n  return {\n    connect,\n    close,\n    isConnected,\n    publishBytes,\n    publishString,\n    publishJson,\n    requestBytes,\n    requestString,\n    requestJson,\n    subscribeBytes,\n    subscribeString,\n    subscribeJson,\n    subscribeJetStreamOrdered,\n    onStatus,\n  };\n}\n","import { createNatsClient, type NatsClient, type NatsStatus, type NatsStatusEvent } from './nats';\n\nexport const NATS_DEFAULTS = {\n  SHARED_CLOSE_DELAY_MS: 3000,\n  CONNECT_TIMEOUT_MS: 10_000,\n  PING_INTERVAL_MS: 30_000,\n  MAX_PING_OUT: 3,\n  RETRY_INITIAL_DELAY_MS: 1000,\n  RETRY_MAX_DELAY_MS: 30_000,\n  RETRY_MULTIPLIER: 2,\n} as const;\n\nexport interface NatsReconnectionBackoff {\n  /** Number of fast retries before exponential phase kicks in. Default: 0. */\n  fastRetries?: number;\n  /** Delay used during the fast-retry phase. Default: RETRY_INITIAL_DELAY_MS. */\n  fastRetryDelayMs?: number;\n  /** Base delay for the exponential phase. Default: RETRY_INITIAL_DELAY_MS. */\n  initialDelayMs?: number;\n  /** Upper cap on any single retry delay. Default: RETRY_MAX_DELAY_MS. */\n  maxDelayMs?: number;\n  /** Per-attempt multiplier during exponential phase. Default: RETRY_MULTIPLIER. */\n  multiplier?: number;\n}\n\nexport interface SharedConnection {\n  wsUrl: string;\n  client: NatsClient;\n  refCount: number;\n  closeTimer: ReturnType<typeof setTimeout> | null;\n  retryTimer: ReturnType<typeof setTimeout> | null;\n  /**\n   * The lifecycle driving reconnect, held as its own `scheduleRetry`. When set,\n   * other consumers observe status only and skip their own scheduleRetry —\n   * otherwise every disconnect starts one backoff schedule per attached\n   * consumer, all dialling the same connection on their own clocks.\n   */\n  retryOwner: (() => void) | null;\n  /**\n   * The `scheduleRetry` of every lifecycle currently observing this connection,\n   * in attach order — the same value that goes into `retryOwner`, so a\n   * lifecycle has one identity rather than two. Only the owner drives\n   * reconnect, so when it gives the loop up the roster is what a successor is\n   * found in; see {@link handOffRetry}.\n   */\n  retrySchedulers: Set<() => void>;\n}\n\nexport interface AcquireClientOptions {\n  name?: string;\n  user?: string;\n  pass?: string;\n  connectTimeoutMs?: number;\n  pingIntervalMs?: number;\n  maxPingOut?: number;\n}\n\nexport interface ReleaseClientOptions {\n  delayMs?: number;\n}\n\n// One shared connection PER URL. The previous single-slot implementation\n// force-closed whatever was connected the moment any consumer acquired a\n// DIFFERENT URL — even with live refs on it. With two chat surfaces on\n// distinct endpoints (`/ws/nats` client chat vs `/ws/nats-api` dashboard)\n// mounted at once, each acquire killed the other's socket, and the loser's\n// retry loop self-cancelled (connection identity mismatch) leaving a dead\n// subscription that silently received nothing.\nconst connections = new Map<string, SharedConnection>();\n\n/** Legacy accessor from the single-slot era: returns the first live shared\n *  connection, or null. With MULTIPLE URLs connected (e.g. `/ws/nats` client\n *  chat + `/ws/nats-api` dashboard mounted together) \"first\" is whichever\n *  surface acquired first — an arbitrary, mount-order-dependent answer.\n *  Prefer `getSharedConnectionFor(url)`; this stays only for external\n *  registry-pinned consumers of the old single-connection API. */\nexport function getSharedConnection(): SharedConnection | null {\n  const first = connections.values().next();\n  return first.done ? null : first.value;\n}\n\nexport function acquireClient(url: string, opts?: AcquireClientOptions): SharedConnection {\n  let conn = connections.get(url);\n\n  if (!conn) {\n    const {\n      name = 'openframe-frontend',\n      user = 'machine',\n      pass = '',\n      connectTimeoutMs = NATS_DEFAULTS.CONNECT_TIMEOUT_MS,\n      pingIntervalMs = NATS_DEFAULTS.PING_INTERVAL_MS,\n      maxPingOut = NATS_DEFAULTS.MAX_PING_OUT,\n    } = opts ?? {};\n\n    const client = createNatsClient({\n      servers: url,\n      name,\n      user,\n      pass,\n      connectTimeoutMs,\n      reconnect: false,\n      pingIntervalMs,\n      maxPingOut,\n    });\n\n    conn = {\n      wsUrl: url,\n      client,\n      refCount: 0,\n      closeTimer: null,\n      retryTimer: null,\n      retryOwner: null,\n      retrySchedulers: new Set(),\n    };\n    connections.set(url, conn);\n  }\n\n  conn.refCount += 1;\n  if (conn.closeTimer) {\n    clearTimeout(conn.closeTimer);\n    conn.closeTimer = null;\n  }\n  return conn;\n}\n\nexport function releaseClient(url: string, opts?: ReleaseClientOptions): void {\n  const conn = connections.get(url);\n  if (!conn) return;\n\n  conn.refCount = Math.max(0, conn.refCount - 1);\n  if (conn.refCount > 0) return;\n\n  const delay = opts?.delayMs ?? NATS_DEFAULTS.SHARED_CLOSE_DELAY_MS;\n  conn.closeTimer = setTimeout(() => {\n    conn.closeTimer = null;\n    // A new acquire may have raced in during the grace period.\n    if (conn.refCount > 0) return;\n    if (connections.get(url) === conn) {\n      connections.delete(url);\n    }\n    if (conn.retryTimer) {\n      clearTimeout(conn.retryTimer);\n      conn.retryTimer = null;\n    }\n    void conn.client.close().catch(() => {});\n  }, delay);\n}\n\nexport function getSharedConnectionFor(url: string | null | undefined): SharedConnection | null {\n  if (!url) return null;\n  return connections.get(url) ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Connection lifecycle: retry + status loop, shared by NatsProvider and the\n// chat hooks. Every consumer that wants to observe or drive reconnect calls\n// startConnectionLifecycle(). The first to claim retryOwner runs the actual\n// retry loop; later attachers observe status only. When the owner gives the\n// loop up it is handed to a survivor if the connection still needs one; while\n// the connection is healthy no handoff is needed, because the next status\n// event lets a survivor claim ownership opportunistically inside\n// scheduleRetry.\n// ---------------------------------------------------------------------------\n\nexport interface ConnectionLifecycleOptions {\n  conn: SharedConnection;\n  wsUrl: string;\n  onBeforeReconnect?: () => Promise<void> | void;\n  backoff?: NatsReconnectionBackoff;\n  getFreshUrl: () => string | null;\n  /** Called on every status change (after closed-guard). */\n  onStatusChange?: (status: NatsStatus, evt: NatsStatusEvent) => void;\n  /**\n   * Decide which statuses should trigger a retry attempt. Defaults to closed +\n   * disconnected. Override to skip 'error' (JetStream protocol errors that\n   * don't close the WS) or include it.\n   */\n  shouldRetryOn?: (status: NatsStatus) => boolean;\n}\n\nexport interface ConnectionLifecycleHandle {\n  /** Stop observing status, clear any pending retry, release ownership if held. */\n  stop(): void;\n}\n\nconst defaultShouldRetryOn = (status: NatsStatus) => status === 'closed' || status === 'disconnected';\n\n/**\n * Offer the retry loop to another lifecycle on this connection.\n *\n * A retry is only ever armed from a status event or a failed dial, and a\n * connection that is already down produces neither on its own — so whenever\n * the owner gives the loop up while the connection still needs dialling, a\n * successor has to be pushed rather than left waiting for an event that is not\n * coming.\n *\n * Candidates that cannot service this URL decline inside `scheduleRetry`, so\n * this walks the roster until one actually takes it. Callers must clear any\n * timer of their own first: a successor that claims while a timer is still\n * armed will not arm one, and the departing owner's timer no longer speaks for\n * the connection.\n */\nfunction handOffRetry(conn: SharedConnection): void {\n  for (const takeOver of conn.retrySchedulers) {\n    takeOver();\n    if (conn.retryOwner) return;\n  }\n}\n\nexport function startConnectionLifecycle(options: ConnectionLifecycleOptions): ConnectionLifecycleHandle {\n  const { conn, wsUrl } = options;\n  let closed = false;\n  let retryAttempt = 0;\n\n  function emitSynthetic(status: NatsStatus) {\n    if (closed) return;\n    options.onStatusChange?.(status, { status });\n    if (status === 'connected') {\n      retryAttempt = 0;\n    }\n  }\n\n  // A lifecycle's identity IS its `scheduleRetry`: that function goes on the\n  // connection's roster and, for whichever lifecycle holds the loop, into\n  // `retryOwner` — one identity, not two.\n  conn.retrySchedulers.add(scheduleRetry);\n  if (!conn.retryOwner) conn.retryOwner = scheduleRetry;\n\n  function scheduleRetry() {\n    if (closed) return;\n    if (getSharedConnectionFor(wsUrl) !== conn) return;\n    // This lifecycle now wants a different URL, so it must not drive this\n    // connection — not from its own status events, and not as a handoff\n    // successor. Without the guard, two consumers that had both moved on\n    // passed ownership back and forth indefinitely, running onBeforeReconnect\n    // — a token refresh in the real callers — on every pass and dialling\n    // nothing. The armed callback re-checks, because the URL can move between\n    // arming and firing.\n    if (options.getFreshUrl() !== wsUrl) return;\n    if (!conn.retryOwner) conn.retryOwner = scheduleRetry;\n    if (conn.retryOwner !== scheduleRetry) return;\n\n    // One outage can raise more than one status: nats.ws reports\n    // `staleConnection` and then, once the transport is down, `disconnect`.\n    // Re-arming on the second would spend a backoff tier on the same outage —\n    // on the defaults, waiting 2000ms where the caller asked for 1000. The\n    // armed timer re-validates everything when it fires, so the first one\n    // scheduled for an outage is always the right one to keep.\n    if (conn.retryTimer) return;\n\n    const cfg = options.backoff ?? {};\n    const fastRetries = cfg.fastRetries ?? 0;\n    const fastDelay = cfg.fastRetryDelayMs ?? NATS_DEFAULTS.RETRY_INITIAL_DELAY_MS;\n    const baseDelay = cfg.initialDelayMs ?? NATS_DEFAULTS.RETRY_INITIAL_DELAY_MS;\n    const maxDelay = cfg.maxDelayMs ?? NATS_DEFAULTS.RETRY_MAX_DELAY_MS;\n    const multiplier = cfg.multiplier ?? NATS_DEFAULTS.RETRY_MULTIPLIER;\n\n    const delay =\n      retryAttempt < fastRetries\n        ? fastDelay\n        : Math.min(baseDelay * multiplier ** (retryAttempt - fastRetries), maxDelay);\n    const jitteredDelay = delay * (0.5 + Math.random() * 0.5);\n    retryAttempt++;\n\n    // The retry body is a named async function rather than the timer callback\n    // itself: `setTimeout` discards whatever its callback returns, so an async\n    // callback's rejection has nowhere to go. Everything that can realistically\n    // throw in here is already caught below, so this is the last-resort net —\n    // but the retry loop is what brings the connection back, and a silent\n    // unhandled rejection in it strands every consumer offline.\n    const runRetry = async () => {\n      conn.retryTimer = null;\n      if (closed) return;\n      if (getSharedConnectionFor(wsUrl) !== conn) return;\n\n      // Nothing to reconnect. Reached when the dial that was already in flight\n      // succeeded while this retry sat in its backoff — a handoff during a\n      // healthy first connect is enough to get here — and `onBeforeReconnect`\n      // is a token refresh in the real callers, so it must not run on a\n      // connection that came back on its own.\n      if (conn.client.isConnected()) {\n        retryAttempt = 0;\n        return;\n      }\n\n      try {\n        await options.onBeforeReconnect?.();\n      } catch {\n        // continue regardless of token-refresh outcome\n      }\n      if (closed) return;\n      if (getSharedConnectionFor(wsUrl) !== conn) return;\n\n      const freshUrl = options.getFreshUrl();\n      if (freshUrl !== wsUrl) {\n        // This lifecycle has moved to a different URL, so it must not dial this\n        // connection again while holding the loop — that is the dead end the\n        // rest of this module exists to avoid. Give the loop up and push it to\n        // someone still on this URL.\n        if (conn.retryOwner === scheduleRetry) {\n          conn.retryOwner = null;\n          // A status that landed while the refresh above was awaited can have\n          // armed a new timer under this ownership. It belongs to a lifecycle\n          // that is leaving, and a successor claiming while it is armed would\n          // return early believing the loop is covered — then this timer fires,\n          // finds someone else owns the loop, and bails without handing on.\n          if (conn.retryTimer) {\n            clearTimeout(conn.retryTimer);\n            conn.retryTimer = null;\n          }\n          handOffRetry(conn);\n        }\n        return;\n      }\n\n      try {\n        await conn.client.connect();\n        if (!closed && getSharedConnectionFor(wsUrl) === conn) {\n          retryAttempt = 0;\n        }\n      } catch {\n        if (!closed && getSharedConnectionFor(wsUrl) === conn) {\n          scheduleRetry();\n        }\n      }\n    };\n\n    conn.retryTimer = setTimeout(() => {\n      runRetry().catch((err: unknown) => {\n        console.warn('[nats] retry attempt threw:', err);\n      });\n    }, jitteredDelay);\n  }\n\n  const shouldRetryOn = options.shouldRetryOn ?? defaultShouldRetryOn;\n\n  const unsubStatus = conn.client.onStatus(evt => {\n    if (closed) return;\n    options.onStatusChange?.(evt.status, evt);\n    if (evt.status === 'connected') {\n      retryAttempt = 0;\n    }\n    if (shouldRetryOn(evt.status)) {\n      scheduleRetry();\n    }\n  });\n\n  if (conn.client.isConnected()) {\n    emitSynthetic('connected');\n  }\n\n  // Dial through the client rather than caching a promise on the connection.\n  // A `conn.connectPromise` used to be assigned here with `||=` and then left\n  // in place after a SUCCESSFUL connect, so it doubled as \"this connection has\n  // been dialled at some point\": a consumer that acquired a still-cached\n  // connection whose socket had since died joined that long-settled promise\n  // instead of dialling. No connect, no failure, so nothing scheduled a retry,\n  // and no status event was coming to arm one either — the connection stayed\n  // dead for as long as anything held a reference to it. `NatsClient.connect()`\n  // already short-circuits on a live connection and joins its own in-flight\n  // dial, so the second copy of that bookkeeping bought nothing.\n  void (async () => {\n    try {\n      await conn.client.connect();\n    } catch {\n      if (closed) return;\n\n      emitSynthetic('disconnected');\n      scheduleRetry();\n    }\n  })();\n\n  return {\n    stop() {\n      closed = true;\n      unsubStatus();\n      conn.retrySchedulers.delete(scheduleRetry);\n\n      if (conn.retryOwner !== scheduleRetry) {\n        // Not ours to cancel. `retryTimer` lives on the CONNECTION, and\n        // clearing it unconditionally cancelled the owner's armed retry — so\n        // any consumer merely re-running its effect (an `enabled` toggle, a\n        // dialog closing, a route change) during a backoff killed reconnect\n        // for everyone. Nothing rescheduled it either, for the reason\n        // handOffRetry exists. The connection stayed down for good.\n        return;\n      }\n\n      conn.retryOwner = null;\n      const wasRetrying = conn.retryTimer !== null;\n      if (conn.retryTimer) {\n        clearTimeout(conn.retryTimer);\n        conn.retryTimer = null;\n      }\n\n      // A healthy connection with nothing armed needs no successor: the next\n      // disconnect lets a survivor claim opportunistically. `wasRetrying` is\n      // read before the clearTimeout above, and the remaining case — the timer\n      // already fired and its callback is mid-dial — is caught by the\n      // connection not being connected. The successor backs off on its OWN\n      // attempt counter, which is zero unless it has driven the loop before.\n      if (!wasRetrying && conn.client.isConnected()) return;\n      handOffRetry(conn);\n    },\n  };\n}\n","'use client';\n\nimport { type ReactNode, createContext, useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport type { NatsClient, NatsStatus } from './nats';\nimport {\n  acquireClient,\n  releaseClient,\n  startConnectionLifecycle,\n  type AcquireClientOptions,\n  type NatsReconnectionBackoff,\n} from './shared-connection';\n\nexport type { NatsReconnectionBackoff } from './shared-connection';\n\nexport interface NatsProviderProps {\n  children: ReactNode;\n  /** Return the current NATS WebSocket URL (or null when not yet available, e.g. unauthenticated). */\n  getWsUrl: () => string | null;\n  /** Called before each reconnect attempt. */\n  onBeforeReconnect?: () => Promise<void> | void;\n  clientConfig?: AcquireClientOptions;\n  reconnectionBackoff?: NatsReconnectionBackoff;\n  /**\n   * Bump this to force re-evaluating `getWsUrl()` (e.g. when auth state flips).\n   * Provider does not subscribe to external auth state by itself.\n   */\n  urlRevision?: unknown;\n}\n\nexport interface NatsContextValue {\n  client: NatsClient | null;\n  status: NatsStatus;\n  isReady: boolean;\n  reconnectionCount: number;\n}\n\nconst NatsContext = createContext<NatsContextValue | null>(null);\n\nexport function NatsProvider({\n  children,\n  getWsUrl,\n  onBeforeReconnect,\n  clientConfig,\n  reconnectionBackoff,\n  urlRevision,\n}: NatsProviderProps) {\n  const [client, setClient] = useState<NatsClient | null>(null);\n  const [status, setStatus] = useState<NatsStatus>('closed');\n  const [reconnectionCount, setReconnectionCount] = useState(0);\n\n  const getWsUrlRef = useRef(getWsUrl);\n  useEffect(() => {\n    getWsUrlRef.current = getWsUrl;\n  }, [getWsUrl]);\n\n  const onBeforeReconnectRef = useRef(onBeforeReconnect);\n  useEffect(() => {\n    onBeforeReconnectRef.current = onBeforeReconnect;\n  }, [onBeforeReconnect]);\n\n  const reconnectionBackoffRef = useRef(reconnectionBackoff);\n  useEffect(() => {\n    reconnectionBackoffRef.current = reconnectionBackoff;\n  }, [reconnectionBackoff]);\n\n  const clientConfigRef = useRef(clientConfig);\n  useEffect(() => {\n    clientConfigRef.current = clientConfig;\n  }, [clientConfig]);\n\n  const heldUrlRef = useRef<string | null>(null);\n  const hadConnectionBeforeRef = useRef(false);\n\n  useEffect(() => {\n    const wsUrl = getWsUrlRef.current();\n\n    if (!wsUrl) {\n      if (heldUrlRef.current) {\n        releaseClient(heldUrlRef.current);\n        heldUrlRef.current = null;\n        setClient(null);\n        setStatus('closed');\n      }\n      return undefined;\n    }\n\n    if (heldUrlRef.current && heldUrlRef.current !== wsUrl) {\n      releaseClient(heldUrlRef.current);\n      heldUrlRef.current = null;\n    }\n\n    const conn = acquireClient(wsUrl, clientConfigRef.current);\n    heldUrlRef.current = wsUrl;\n    setClient(conn.client);\n    setStatus(conn.client.isConnected() ? 'connected' : 'connecting');\n\n    const lifecycle = startConnectionLifecycle({\n      conn,\n      wsUrl,\n      onBeforeReconnect: () => onBeforeReconnectRef.current?.(),\n      backoff: reconnectionBackoffRef.current,\n      getFreshUrl: () => getWsUrlRef.current(),\n      onStatusChange: newStatus => {\n        if (newStatus === 'error') return;\n        setStatus(newStatus);\n        if (newStatus === 'connected') {\n          if (hadConnectionBeforeRef.current) {\n            setReconnectionCount(c => c + 1);\n          }\n          hadConnectionBeforeRef.current = true;\n        }\n      },\n    });\n\n    return () => {\n      lifecycle.stop();\n      if (heldUrlRef.current) {\n        releaseClient(heldUrlRef.current);\n        heldUrlRef.current = null;\n      }\n      setClient(null);\n      setStatus('closed');\n    };\n  }, [urlRevision]);\n\n  const value = useMemo<NatsContextValue>(\n    () => ({\n      client,\n      status,\n      isReady: status === 'connected' && client !== null,\n      reconnectionCount,\n    }),\n    [client, status, reconnectionCount],\n  );\n\n  return <NatsContext.Provider value={value}>{children}</NatsContext.Provider>;\n}\n\nexport function useNats(): NatsContextValue {\n  const ctx = useContext(NatsContext);\n  if (!ctx) throw new Error('useNats must be used inside <NatsProvider>');\n  return ctx;\n}\n\nexport function useOptionalNats(): NatsContextValue | null {\n  return useContext(NatsContext);\n}\n","'use client';\n\nimport { useRef, useEffect, useState, useCallback } from 'react';\nimport type { JsMsg, Msg, NatsSubscribeOptions } from './nats';\nimport { useOptionalNats } from './nats-provider';\n\nexport interface UseNatsSubscriptionOptions extends NatsSubscribeOptions {\n  enabled?: boolean;\n}\n\nexport interface UseNatsSubscriptionReturn {\n  isSubscribed: boolean;\n  isReady: boolean;\n}\n\n/**\n * Subscribe to a NATS subject using the shared connection from <NatsProvider>.\n * Automatically (re)subscribes when the connection becomes ready, when the\n * subject changes, and after reconnections.\n */\nexport function useNatsSubscription(\n  subject: string | null,\n  onMessage: (msg: Msg) => void | Promise<void>,\n  options?: UseNatsSubscriptionOptions,\n): UseNatsSubscriptionReturn {\n  const nats = useOptionalNats();\n  const handlerRef = useRef(onMessage);\n  useEffect(() => {\n    handlerRef.current = onMessage;\n  }, [onMessage]);\n\n  const enabled = options?.enabled !== false;\n  const queue = options?.queue;\n  const max = options?.max;\n  const reconnectionCount = nats?.reconnectionCount ?? 0;\n  const isReady = !!nats?.isReady;\n  const client = nats?.client ?? null;\n\n  // Not independent state. The effect below subscribes synchronously and\n  // unconditionally whenever all four preconditions hold, and unsubscribes in\n  // its cleanup — so \"is there a live subscription\" IS this predicate, and\n  // storing it meant every subscribe and every teardown paid a second render\n  // pass to report something the first render already knew.\n  //\n  // It also removes a spurious flap: a reconnect-driven re-subscribe used to\n  // run `setIsSubscribed(false)` (cleanup) then `setIsSubscribed(true)` in the\n  // same commit, so the value briefly described a gap that consumers could\n  // never observe anyway.\n  const isSubscribed = Boolean(client) && isReady && Boolean(subject) && enabled;\n\n  useEffect(() => {\n    if (!client || !isReady || !subject || !enabled) return undefined;\n\n    const sub = client.subscribeBytes(subject, msg => handlerRef.current(msg), { queue, max });\n\n    return () => {\n      try {\n        sub.unsubscribe();\n      } catch {\n        // ignore\n      }\n    };\n    // reconnectionCount intentionally in deps: re-subscribe after reconnect\n  }, [client, isReady, subject, enabled, queue, max, reconnectionCount]);\n\n  return { isSubscribed, isReady };\n}\n\nexport type UseNatsJsonSubscriptionOptions = UseNatsSubscriptionOptions;\n\nexport function useNatsJsonSubscription<T = unknown>(\n  subject: string | null,\n  onPayload: (payload: T, msg: Msg) => void | Promise<void>,\n  options?: UseNatsJsonSubscriptionOptions,\n): UseNatsSubscriptionReturn {\n  const handlerRef = useRef(onPayload);\n  useEffect(() => {\n    handlerRef.current = onPayload;\n  }, [onPayload]);\n\n  // One decoder for the hook's lifetime. `useState`'s lazy initialiser instead\n  // of a ref filled on first render: the guard is exactly the lazy-init shape\n  // `useState` exists for, and it keeps the construction out of render. Null\n  // on a server render, where `TextDecoder` may be absent — `wrapped` only\n  // ever runs client-side, but the guard below keeps that explicit.\n  const [decoder] = useState<TextDecoder | null>(() => (typeof TextDecoder !== 'undefined' ? new TextDecoder() : null));\n\n  const wrapped = useCallback(\n    async (msg: Msg) => {\n      if (!decoder) return;\n      try {\n        const parsed = JSON.parse(decoder.decode(msg.data)) as T;\n        await handlerRef.current(parsed, msg);\n      } catch {\n        // ignore malformed payloads\n      }\n    },\n    [decoder],\n  );\n\n  return useNatsSubscription(subject, wrapped, options);\n}\n\nexport type NatsJsMsg = JsMsg;\n"]}