@flamingo-stack/openframe-frontend-core 0.0.809 → 0.0.810

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/{chunk-ZAXGW4KT.cjs → chunk-2C63MX75.cjs} +13 -13
  2. package/dist/{chunk-KS5V55HN.cjs → chunk-3FBXQSSC.cjs} +7 -7
  3. package/dist/{chunk-OAJ3AL4V.cjs → chunk-B6DIM5JG.cjs} +4 -4
  4. package/dist/{chunk-KITOT3DS.cjs → chunk-CLMUD56S.cjs} +10 -10
  5. package/dist/{chunk-DDFT6VQ3.cjs → chunk-CZWQCYKV.cjs} +3 -3
  6. package/dist/{chunk-AZJYMTBS.cjs → chunk-EKDLVUEA.cjs} +2 -2
  7. package/dist/{chunk-KCB72H7A.cjs → chunk-ETI7OMPU.cjs} +39 -39
  8. package/dist/{chunk-Q3C6UJJ7.cjs → chunk-F26COFTW.cjs} +57 -57
  9. package/dist/{chunk-RZNRKWG5.cjs → chunk-FCFYZIOY.cjs} +9 -9
  10. package/dist/{chunk-3B76QFXV.cjs → chunk-GG36TCKP.cjs} +4 -4
  11. package/dist/{chunk-BT53NHR7.cjs → chunk-J4QORJMC.cjs} +25 -25
  12. package/dist/{chunk-WDL3GFH2.cjs → chunk-MAQFG62O.cjs} +19 -19
  13. package/dist/{chunk-UVLTUSH3.cjs → chunk-MSAXZRXZ.cjs} +131 -131
  14. package/dist/{chunk-KHKPLOU4.cjs → chunk-QDB2JO55.cjs} +144 -36
  15. package/dist/{chunk-OFGYPMTE.cjs → chunk-R2ABQG2T.cjs} +39 -39
  16. package/dist/{chunk-VKAFZCFV.cjs → chunk-RKNCNL6K.cjs} +13 -13
  17. package/dist/{chunk-5UTJARDM.cjs → chunk-RPBOWCME.cjs} +2 -2
  18. package/dist/{chunk-WV44WJKR.cjs → chunk-TOTR2WMH.cjs} +3 -3
  19. package/dist/{chunk-VUKN6KEE.cjs → chunk-X2JSCOOR.cjs} +52 -52
  20. package/dist/{chunk-LUICXMHC.cjs → chunk-ZXBRPQND.cjs} +6 -6
  21. package/dist/{cloud-tenants-DJAA23GR.cjs → cloud-tenants-QTASS5KP.cjs} +6 -6
  22. package/dist/components/case-studies/index.cjs +18 -18
  23. package/dist/components/chat/hooks/use-jetstream-dialog-subscription.js +1 -1
  24. package/dist/components/chat/hooks/use-nats-dialog-subscription.js +1 -1
  25. package/dist/components/chat/index.cjs +4 -4
  26. package/dist/components/chat/types/api.types.d.ts +8 -4
  27. package/dist/components/chat/types/api.types.d.ts.map +1 -1
  28. package/dist/components/contact/index.cjs +7 -7
  29. package/dist/components/docs/index.cjs +10 -10
  30. package/dist/components/embeds/index.cjs +7 -7
  31. package/dist/components/faq/index.cjs +8 -8
  32. package/dist/components/features/index.cjs +6 -6
  33. package/dist/components/help-center-pages/index.cjs +74 -74
  34. package/dist/components/index.cjs +41 -41
  35. package/dist/components/meeting-scheduler/index.cjs +36 -36
  36. package/dist/components/navigation/index.cjs +9 -9
  37. package/dist/components/onboarding-guides/index.cjs +8 -8
  38. package/dist/components/product-demo/index.cjs +15 -15
  39. package/dist/components/tickets/index.cjs +11 -11
  40. package/dist/components/ui/index.cjs +6 -6
  41. package/dist/{devices-AIDQW4HB.cjs → devices-KPMQI57Y.cjs} +7 -7
  42. package/dist/{embeddable-chat-XT6GMSBX.cjs → embeddable-chat-LB7NDFVQ.cjs} +60 -60
  43. package/dist/hooks/index.cjs +3 -3
  44. package/dist/index.cjs +10 -10
  45. package/dist/{knowledge-JWCFM3GO.cjs → knowledge-JWGBY3ZJ.cjs} +7 -7
  46. package/dist/{logs-ZNIXPJXA.cjs → logs-QENTXKWY.cjs} +14 -14
  47. package/dist/nats/index.cjs +2 -2
  48. package/dist/nats/nats-provider.d.ts +9 -3
  49. package/dist/nats/nats-provider.d.ts.map +1 -1
  50. package/dist/nats/nats-provider.js +7 -3
  51. package/dist/nats/shared-connection.d.ts +44 -1
  52. package/dist/nats/shared-connection.d.ts.map +1 -1
  53. package/dist/nats/shared-connection.js +126 -22
  54. package/dist/{policies-Z4NGPLA2.cjs → policies-2HXFZ2EL.cjs} +10 -10
  55. package/dist/{scripts-G4Y5SPOW.cjs → scripts-TMXULK6L.cjs} +11 -11
  56. package/dist/{software-update-VAOKDA76.cjs → software-update-H2LAEWDN.cjs} +9 -9
  57. package/package.json +1 -1
  58. package/src/components/chat/hooks/use-jetstream-dialog-subscription.ts +1 -1
  59. package/src/components/chat/hooks/use-nats-dialog-subscription.ts +1 -1
  60. package/src/components/chat/types/api.types.ts +8 -4
  61. package/src/nats/nats-provider.tsx +15 -4
  62. package/src/nats/shared-connection.ts +199 -25
@@ -13,7 +13,7 @@ var _chunkFDZOE5TLcjs = require('./chunk-FDZOE5TL.cjs');
13
13
 
14
14
 
15
15
 
16
- var _chunkUVLTUSH3cjs = require('./chunk-UVLTUSH3.cjs');
16
+ var _chunkMSAXZRXZcjs = require('./chunk-MSAXZRXZ.cjs');
17
17
  require('./chunk-FLW2VL5W.cjs');
18
18
  require('./chunk-NG3RKTQU.cjs');
19
19
 
@@ -21,14 +21,14 @@ require('./chunk-NG3RKTQU.cjs');
21
21
  var _chunkFRS2VO22cjs = require('./chunk-FRS2VO22.cjs');
22
22
  require('./chunk-HQQE74RO.cjs');
23
23
  require('./chunk-DEY6XXGO.cjs');
24
- require('./chunk-AZJYMTBS.cjs');
24
+ require('./chunk-EKDLVUEA.cjs');
25
25
  require('./chunk-VXAKQRV7.cjs');
26
26
  require('./chunk-24I6RFVU.cjs');
27
27
  require('./chunk-7Z536SPR.cjs');
28
28
  require('./chunk-MZ4KBSH7.cjs');
29
29
  require('./chunk-YR74H7Z3.cjs');
30
- require('./chunk-BT53NHR7.cjs');
31
- require('./chunk-KS5V55HN.cjs');
30
+ require('./chunk-J4QORJMC.cjs');
31
+ require('./chunk-3FBXQSSC.cjs');
32
32
  require('./chunk-JLKGLPDC.cjs');
33
33
  require('./chunk-ZD6SZLO2.cjs');
34
34
  require('./chunk-KVJKKVB3.cjs');
@@ -1866,7 +1866,7 @@ require('./chunk-4WIJI4AK.cjs');
1866
1866
  require('./chunk-AHBTZ7DN.cjs');
1867
1867
  require('./chunk-7JWFMAQB.cjs');
1868
1868
  require('./chunk-V45KLJQP.cjs');
1869
- require('./chunk-KHKPLOU4.cjs');
1869
+ require('./chunk-QDB2JO55.cjs');
1870
1870
 
1871
1871
  // src/components/product-demo/screens/scripts.tsx
1872
1872
  var _react = require('react');
@@ -1995,8 +1995,8 @@ function buildScriptsFixture(cast) {
1995
1995
  var _jsxruntime = require('react/jsx-runtime');
1996
1996
  var WIDE_HIDDEN_COLUMNS = ["result", "open"];
1997
1997
  var COMPACT_COLUMNS = [
1998
- { ..._chunkUVLTUSH3cjs.EXECUTION_COLUMNS.machineId, width: "flex-1 min-w-0", hideAt: void 0 },
1999
- _chunkUVLTUSH3cjs.EXECUTION_COLUMNS.status
1998
+ { ..._chunkMSAXZRXZcjs.EXECUTION_COLUMNS.machineId, width: "flex-1 min-w-0", hideAt: void 0 },
1999
+ _chunkMSAXZRXZcjs.EXECUTION_COLUMNS.status
2000
2000
  ];
2001
2001
  var COMPACT_ROWS = 4;
2002
2002
  var TOKEN_CLASS = {
@@ -2055,7 +2055,7 @@ function ScriptCodePicture({ script }) {
2055
2055
  /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "div", { className: "flex min-w-0 items-center justify-between gap-[var(--spacing-system-m)]", children: [
2056
2056
  /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkFRS2VO22cjs.TruncateText, { variant: "h6", tone: "secondary", children: `Written by ${provenance.author} \xB7 approved by ${provenance.approver}` }),
2057
2057
  /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
2058
- _chunkUVLTUSH3cjs.ScriptShellBadge,
2058
+ _chunkMSAXZRXZcjs.ScriptShellBadge,
2059
2059
  {
2060
2060
  value: script.shellType,
2061
2061
  className: "shrink-0 text-ods-text-secondary text-h6",
@@ -2079,7 +2079,7 @@ function ScriptsScreen({ compact = false }) {
2079
2079
  return (
2080
2080
  // Four runs of the card's row height fill the frame; the padding is what is left round them.
2081
2081
  /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "h-full overflow-hidden bg-ods-bg p-[var(--spacing-system-xsf)]", children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
2082
- _chunkUVLTUSH3cjs.ScriptExecutionsTable,
2082
+ _chunkMSAXZRXZcjs.ScriptExecutionsTable,
2083
2083
  {
2084
2084
  rows: fixture.executions.slice(0, COMPACT_ROWS),
2085
2085
  columns: COMPACT_COLUMNS,
@@ -2089,13 +2089,13 @@ function ScriptsScreen({ compact = false }) {
2089
2089
  ) })
2090
2090
  );
2091
2091
  }
2092
- const renderOutput = (row) => row.id === fixture.openExecutionId ? /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkUVLTUSH3cjs.ScriptExecutionResult, { result: row.result, empty: "\u2014" }) : null;
2092
+ const renderOutput = (row) => row.id === fixture.openExecutionId ? /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkMSAXZRXZcjs.ScriptExecutionResult, { result: row.result, empty: "\u2014" }) : null;
2093
2093
  return (
2094
2094
  // The frame's tighter padding and no header row: the output opened under a run needs the height.
2095
2095
  /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "div", { className: "flex h-full gap-[var(--spacing-system-m)] overflow-hidden bg-ods-bg p-[var(--spacing-system-m)]", children: [
2096
2096
  /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "w-[39%] shrink-0", children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, ScriptCodePicture, { script: fixture.script }) }),
2097
2097
  /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "min-w-0 flex-1 overflow-hidden", children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
2098
- _chunkUVLTUSH3cjs.ScriptExecutionsTable,
2098
+ _chunkMSAXZRXZcjs.ScriptExecutionsTable,
2099
2099
  {
2100
2100
  rows: fixture.executions,
2101
2101
  hideColumns: WIDE_HIDDEN_COLUMNS,
@@ -15,7 +15,7 @@ var _chunkFDZOE5TLcjs = require('./chunk-FDZOE5TL.cjs');
15
15
 
16
16
 
17
17
 
18
- var _chunkUVLTUSH3cjs = require('./chunk-UVLTUSH3.cjs');
18
+ var _chunkMSAXZRXZcjs = require('./chunk-MSAXZRXZ.cjs');
19
19
  require('./chunk-FLW2VL5W.cjs');
20
20
  require('./chunk-NG3RKTQU.cjs');
21
21
 
@@ -23,14 +23,14 @@ require('./chunk-NG3RKTQU.cjs');
23
23
  var _chunkFRS2VO22cjs = require('./chunk-FRS2VO22.cjs');
24
24
  require('./chunk-HQQE74RO.cjs');
25
25
  require('./chunk-DEY6XXGO.cjs');
26
- require('./chunk-AZJYMTBS.cjs');
26
+ require('./chunk-EKDLVUEA.cjs');
27
27
  require('./chunk-VXAKQRV7.cjs');
28
28
  require('./chunk-24I6RFVU.cjs');
29
29
  require('./chunk-7Z536SPR.cjs');
30
30
  require('./chunk-MZ4KBSH7.cjs');
31
31
  require('./chunk-YR74H7Z3.cjs');
32
- require('./chunk-BT53NHR7.cjs');
33
- require('./chunk-KS5V55HN.cjs');
32
+ require('./chunk-J4QORJMC.cjs');
33
+ require('./chunk-3FBXQSSC.cjs');
34
34
  require('./chunk-JLKGLPDC.cjs');
35
35
  require('./chunk-ZD6SZLO2.cjs');
36
36
  require('./chunk-KVJKKVB3.cjs');
@@ -1866,7 +1866,7 @@ require('./chunk-4WIJI4AK.cjs');
1866
1866
  require('./chunk-AHBTZ7DN.cjs');
1867
1867
  require('./chunk-7JWFMAQB.cjs');
1868
1868
  require('./chunk-V45KLJQP.cjs');
1869
- require('./chunk-KHKPLOU4.cjs');
1869
+ require('./chunk-QDB2JO55.cjs');
1870
1870
 
1871
1871
  // src/components/product-demo/screens/software-update.tsx
1872
1872
  var _react = require('react');
@@ -1922,12 +1922,12 @@ function StaticPackageField({ value }) {
1922
1922
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
1923
1923
  _chunkFRS2VO22cjs.Autocomplete,
1924
1924
  {
1925
- label: _chunkUVLTUSH3cjs.PACKAGE_SEARCH_LABEL,
1925
+ label: _chunkMSAXZRXZcjs.PACKAGE_SEARCH_LABEL,
1926
1926
  labelVariant: "large",
1927
1927
  options: value ? [{ value: value.id, label: value.name, description: _nullishCoalesce(value.description, () => ( void 0)) }] : [],
1928
1928
  value: _nullishCoalesce(_optionalChain([value, 'optionalAccess', _ => _.id]), () => ( null)),
1929
1929
  onChange: noop,
1930
- placeholder: _chunkUVLTUSH3cjs.PACKAGE_SEARCH_PLACEHOLDER
1930
+ placeholder: _chunkMSAXZRXZcjs.PACKAGE_SEARCH_PLACEHOLDER
1931
1931
  }
1932
1932
  );
1933
1933
  }
@@ -1941,7 +1941,7 @@ function SoftwareUpdateScreen({ compact = false }) {
1941
1941
  [fixture.devices, fixture.selectedIds]
1942
1942
  );
1943
1943
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "h-full bg-ods-bg pt-[var(--spacing-system-l)]", children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "h-full", children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
1944
- _chunkUVLTUSH3cjs.SoftwareActionForm,
1944
+ _chunkMSAXZRXZcjs.SoftwareActionForm,
1945
1945
  {
1946
1946
  action: fixture.action,
1947
1947
  showHeader: false,
@@ -1953,7 +1953,7 @@ function SoftwareUpdateScreen({ compact = false }) {
1953
1953
  initialValues: fixture.initialValues,
1954
1954
  renderPackageSearch,
1955
1955
  renderDevicePicker: () => /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
1956
- _chunkUVLTUSH3cjs.DeviceSelector,
1956
+ _chunkMSAXZRXZcjs.DeviceSelector,
1957
1957
  {
1958
1958
  devices: selected,
1959
1959
  loading: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flamingo-stack/openframe-frontend-core",
3
- "version": "0.0.809",
3
+ "version": "0.0.810",
4
4
  "description": "Shared design system and components for all Flamingo platforms",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -228,7 +228,7 @@ export function useJetStreamDialogSubscription({
228
228
  const lifecycle = startConnectionLifecycle({
229
229
  conn: sharedConn,
230
230
  wsUrl,
231
- onBeforeReconnect: () => onBeforeReconnectRef.current?.(),
231
+ onBeforeReconnect: ctx => onBeforeReconnectRef.current?.(ctx),
232
232
  backoff: reconnectionBackoffRef.current,
233
233
  getFreshUrl: () => getNatsWsUrlRef.current(),
234
234
  // JetStream emits 'error' for protocol-level failures (e.g. -ERR Permissions
@@ -144,7 +144,7 @@ export function useNatsDialogSubscription({
144
144
  const lifecycle = startConnectionLifecycle({
145
145
  conn: sharedConn,
146
146
  wsUrl,
147
- onBeforeReconnect: () => onBeforeReconnectRef.current?.(),
147
+ onBeforeReconnect: ctx => onBeforeReconnectRef.current?.(ctx),
148
148
  backoff: reconnectionBackoffRef.current,
149
149
  getFreshUrl: () => getNatsWsUrlRef.current(),
150
150
  shouldRetryOn: isDisconnectStatus,
@@ -3,6 +3,7 @@
3
3
  * Contains types for API interactions and React hooks
4
4
  */
5
5
 
6
+ import type { NatsBeforeReconnect } from '../../../nats';
6
7
  import type { ChatType, ChatApprovalStatus } from './chat.types';
7
8
  import type { MessageSegment, TokenUsageData, ToolExecutionSegment } from './message.types';
8
9
  import type { ChunkData, NatsMessageType, FetchChunksFunction } from './network.types';
@@ -36,8 +37,11 @@ export interface UseNatsDialogSubscriptionOptions {
36
37
  onConnect?: () => void;
37
38
  onDisconnect?: () => void;
38
39
  onSubscribed?: () => void;
39
- /** Called on disconnect, before nats.ws attempts reconnection. Use to refresh auth (cookies/tokens). */
40
- onBeforeReconnect?: () => Promise<void> | void;
40
+ /**
41
+ * Called on disconnect, before nats.ws attempts reconnection. Use to refresh auth (cookies/tokens).
42
+ * May return a verdict (`pause` / `terminal`) to stop the dial loop; see {@link NatsBeforeReconnect}.
43
+ */
44
+ onBeforeReconnect?: NatsBeforeReconnect;
41
45
  /**
42
46
  * Function to get the NATS WebSocket URL
43
47
  */
@@ -112,8 +116,8 @@ export interface UseJetStreamDialogSubscriptionOptions {
112
116
  onConnect?: () => void;
113
117
  onDisconnect?: () => void;
114
118
  onSubscribed?: () => void;
115
- /** Called on disconnect, before reconnect attempt. Use to refresh auth. */
116
- onBeforeReconnect?: () => Promise<void> | void;
119
+ /** Called on disconnect, before reconnect attempt. Use to refresh auth. May return a verdict; see {@link NatsBeforeReconnect}. */
120
+ onBeforeReconnect?: NatsBeforeReconnect;
117
121
  /** Build the NATS WebSocket URL (or null when not yet available). */
118
122
  getNatsWsUrl: () => string | null;
119
123
  clientConfig?: {
@@ -7,6 +7,7 @@ import {
7
7
  releaseClient,
8
8
  startConnectionLifecycle,
9
9
  type AcquireClientOptions,
10
+ type NatsBeforeReconnect,
10
11
  type NatsReconnectionBackoff,
11
12
  } from './shared-connection';
12
13
 
@@ -14,8 +15,8 @@ export interface NatsProviderProps {
14
15
  children: ReactNode;
15
16
  /** Return the current NATS WebSocket URL (or null when not yet available, e.g. unauthenticated). */
16
17
  getWsUrl: () => string | null;
17
- /** Called before each reconnect attempt. */
18
- onBeforeReconnect?: () => Promise<void> | void;
18
+ /** Called before each reconnect attempt. May return a verdict; see `NatsReconnectVerdict`. */
19
+ onBeforeReconnect?: NatsBeforeReconnect;
19
20
  clientConfig?: AcquireClientOptions;
20
21
  reconnectionBackoff?: NatsReconnectionBackoff;
21
22
  /**
@@ -30,6 +31,12 @@ export interface NatsContextValue {
30
31
  status: NatsStatus;
31
32
  isReady: boolean;
32
33
  reconnectionCount: number;
34
+ /**
35
+ * A `terminal` verdict stopped reconnecting; `status` stays `disconnected`. Reset when this
36
+ * provider re-acquires (`urlRevision` changes); the connection itself stays terminal while
37
+ * another consumer still holds it.
38
+ */
39
+ terminal: boolean;
33
40
  }
34
41
 
35
42
  const NatsContext = createContext<NatsContextValue | null>(null);
@@ -45,6 +52,7 @@ export function NatsProvider({
45
52
  const [client, setClient] = useState<NatsClient | null>(null);
46
53
  const [status, setStatus] = useState<NatsStatus>('closed');
47
54
  const [reconnectionCount, setReconnectionCount] = useState(0);
55
+ const [terminal, setTerminal] = useState(false);
48
56
 
49
57
  const getWsUrlRef = useRef(getWsUrl);
50
58
  useEffect(() => {
@@ -95,9 +103,10 @@ export function NatsProvider({
95
103
  const lifecycle = startConnectionLifecycle({
96
104
  conn,
97
105
  wsUrl,
98
- onBeforeReconnect: () => onBeforeReconnectRef.current?.(),
106
+ onBeforeReconnect: ctx => onBeforeReconnectRef.current?.(ctx),
99
107
  backoff: reconnectionBackoffRef.current,
100
108
  getFreshUrl: () => getWsUrlRef.current(),
109
+ onTerminal: () => setTerminal(true),
101
110
  onStatusChange: newStatus => {
102
111
  if (newStatus === 'error') return;
103
112
  setStatus(newStatus);
@@ -118,6 +127,7 @@ export function NatsProvider({
118
127
  }
119
128
  setClient(null);
120
129
  setStatus('closed');
130
+ setTerminal(false);
121
131
  };
122
132
  }, [urlRevision]);
123
133
 
@@ -127,8 +137,9 @@ export function NatsProvider({
127
137
  status,
128
138
  isReady: status === 'connected' && client !== null,
129
139
  reconnectionCount,
140
+ terminal,
130
141
  }),
131
- [client, status, reconnectionCount],
142
+ [client, status, reconnectionCount, terminal],
132
143
  );
133
144
 
134
145
  return <NatsContext.Provider value={value}>{children}</NatsContext.Provider>;
@@ -8,8 +8,32 @@ export const NATS_DEFAULTS = {
8
8
  RETRY_INITIAL_DELAY_MS: 1000,
9
9
  RETRY_MAX_DELAY_MS: 30_000,
10
10
  RETRY_MULTIPLIER: 2,
11
+ /** Failed dials in a row after which the lifecycle stops dialling for a while. */
12
+ PAUSE_AFTER_FAILURES: 5,
13
+ /** Length of a pause, plus up to 20% jitter so clients paused by one outage do not wake together. */
14
+ PAUSE_MS: 300_000,
15
+ /** A pause ignores visibility/online resume triggers for this long, so toggling tabs is not a retry button. */
16
+ PAUSE_MIN_RESUME_MS: 30_000,
11
17
  } as const;
12
18
 
19
+ /**
20
+ * What `onBeforeReconnect` can decide about the connection, not just this attempt.
21
+ * - `continue` (or returning nothing): dial.
22
+ * - `pause`: no dials for `PAUSE_MS` plus jitter; ends early (not within `PAUSE_MIN_RESUME_MS`) on the tab
23
+ * becoming visible or the browser coming back online.
24
+ * - `terminal`: the connection can never come back (e.g. the tenant is gone). No lifecycle dials it again until a fresh acquire.
25
+ */
26
+ export type NatsReconnectVerdict = 'continue' | 'pause' | 'terminal';
27
+
28
+ export interface NatsReconnectContext {
29
+ /** Dials that failed since the connection was last up. */
30
+ consecutiveFailures: number;
31
+ }
32
+
33
+ export type NatsBeforeReconnect = (
34
+ ctx: NatsReconnectContext,
35
+ ) => Promise<NatsReconnectVerdict | void> | NatsReconnectVerdict | void;
36
+
13
37
  export interface NatsReconnectionBackoff {
14
38
  /** Number of fast retries before exponential phase kicks in. Default: 0. */
15
39
  fastRetries?: number;
@@ -44,6 +68,20 @@ export interface SharedConnection {
44
68
  * found in; see {@link handOffRetry}.
45
69
  */
46
70
  retrySchedulers: Set<() => void>;
71
+ /**
72
+ * Failed dials since the connection was last up. Lives here, not in a
73
+ * lifecycle, so a successor that takes over the loop (or a consumer that
74
+ * mounts) continues the same backoff instead of restarting at the fast tier.
75
+ */
76
+ failedDials: number;
77
+ /** The rejection last counted into `failedDials`; see `countFailedDial`. */
78
+ lastDialError: unknown;
79
+ /** Set by a `terminal` verdict. Cleared only by a fresh acquire (see {@link acquireClient}). */
80
+ terminal: boolean;
81
+ /** Set while dialling is suspended; `until` is a `Date.now()` timestamp. */
82
+ pause: { until: number; startedAt: number; dispose: () => void } | null;
83
+ /** One entry per lifecycle with an `onTerminal`; run when the connection turns terminal. */
84
+ terminalListeners: Set<() => void>;
47
85
  }
48
86
 
49
87
  export interface AcquireClientOptions {
@@ -111,8 +149,22 @@ export function acquireClient(url: string, opts?: AcquireClientOptions): SharedC
111
149
  retryTimer: null,
112
150
  retryOwner: null,
113
151
  retrySchedulers: new Set(),
152
+ failedDials: 0,
153
+ lastDialError: undefined,
154
+ terminal: false,
155
+ pause: null,
156
+ terminalListeners: new Set(),
114
157
  };
115
158
  connections.set(url, conn);
159
+ } else if (conn.refCount === 0) {
160
+ // Cached only for the close grace period: nobody was attached, so this is a
161
+ // new owner (e.g. `urlRevision` re-ran), not another consumer of the same
162
+ // outage. A consumer joining a live connection must NOT reset it — a chat
163
+ // surface mounting would otherwise undo a terminal verdict.
164
+ conn.failedDials = 0;
165
+ conn.terminal = false;
166
+ conn.pause?.dispose();
167
+ conn.pause = null;
116
168
  }
117
169
 
118
170
  conn.refCount += 1;
@@ -142,6 +194,8 @@ export function releaseClient(url: string, opts?: ReleaseClientOptions): void {
142
194
  clearTimeout(conn.retryTimer);
143
195
  conn.retryTimer = null;
144
196
  }
197
+ conn.pause?.dispose();
198
+ conn.pause = null;
145
199
  void conn.client.close().catch(() => {});
146
200
  }, delay);
147
201
  }
@@ -165,11 +219,17 @@ export function getSharedConnectionFor(url: string | null | undefined): SharedCo
165
219
  export interface ConnectionLifecycleOptions {
166
220
  conn: SharedConnection;
167
221
  wsUrl: string;
168
- onBeforeReconnect?: () => Promise<void> | void;
222
+ onBeforeReconnect?: NatsBeforeReconnect;
169
223
  backoff?: NatsReconnectionBackoff;
170
224
  getFreshUrl: () => string | null;
171
225
  /** Called on every status change (after closed-guard). */
172
226
  onStatusChange?: (status: NatsStatus, evt: NatsStatusEvent) => void;
227
+ /**
228
+ * Called once when the connection is (or already was, on attach) terminal.
229
+ * The status stays `disconnected`, so this is what tells that apart from an
230
+ * outage that is still being retried.
231
+ */
232
+ onTerminal?: () => void;
173
233
  /**
174
234
  * Decide which statuses should trigger a retry attempt. Defaults to closed +
175
235
  * disconnected. Override to skip 'error' (JetStream protocol errors that
@@ -210,16 +270,90 @@ function handOffRetry(conn: SharedConnection): void {
210
270
  export function startConnectionLifecycle(options: ConnectionLifecycleOptions): ConnectionLifecycleHandle {
211
271
  const { conn, wsUrl } = options;
212
272
  let closed = false;
213
- let retryAttempt = 0;
273
+
274
+ function endPause(): void {
275
+ conn.pause?.dispose();
276
+ conn.pause = null;
277
+ }
278
+
279
+ function startPause(): void {
280
+ if (conn.pause) return;
281
+ const now = Date.now();
282
+ // Spread over up to +20% so clients paused by the same outage do not all wake together.
283
+ const until = now + NATS_DEFAULTS.PAUSE_MS * (1 + Math.random() * 0.2);
284
+
285
+ const resume = () => {
286
+ if (!conn.pause) return;
287
+ if (Date.now() - conn.pause.startedAt < NATS_DEFAULTS.PAUSE_MIN_RESUME_MS) return;
288
+ endPause();
289
+ if (conn.terminal || conn.client.isConnected()) return;
290
+ if (conn.retryTimer) {
291
+ clearTimeout(conn.retryTimer);
292
+ conn.retryTimer = null;
293
+ }
294
+ if (conn.retryOwner) conn.retryOwner();
295
+ else handOffRetry(conn);
296
+ };
297
+ const onVisibility = () => {
298
+ if (document.visibilityState === 'visible') resume();
299
+ };
300
+ const hasDom = typeof document !== 'undefined' && typeof window !== 'undefined';
301
+ if (hasDom) {
302
+ document.addEventListener('visibilitychange', onVisibility);
303
+ window.addEventListener('online', resume);
304
+ }
305
+ // The next dial after an auto-pause is a single probe: one more failure and
306
+ // the threshold is met again, instead of five more dials into a dead endpoint.
307
+ conn.failedDials = Math.min(conn.failedDials, NATS_DEFAULTS.PAUSE_AFTER_FAILURES - 1);
308
+ conn.pause = {
309
+ until,
310
+ startedAt: now,
311
+ dispose: () => {
312
+ if (!hasDom) return;
313
+ document.removeEventListener('visibilitychange', onVisibility);
314
+ window.removeEventListener('online', resume);
315
+ },
316
+ };
317
+ }
318
+
319
+ function markHealthy(): void {
320
+ endPause();
321
+ conn.failedDials = 0;
322
+ }
323
+
324
+ // Lifecycles that attach while a dial is in flight join it (`NatsClient.connect`
325
+ // shares one promise), so one refused dial rejects in every one of them — with
326
+ // the same error object. Counted per lifecycle, consumers mounting together
327
+ // turned one failure into several, skipped the fast tier and reached the pause
328
+ // threshold after a couple of real dials.
329
+ function countFailedDial(err: unknown): void {
330
+ if (err === conn.lastDialError) return;
331
+ conn.lastDialError = err;
332
+ conn.failedDials++;
333
+ }
334
+
335
+ function markTerminal(): void {
336
+ endPause();
337
+ if (conn.retryTimer) clearTimeout(conn.retryTimer);
338
+ conn.terminal = true;
339
+ conn.retryOwner = null;
340
+ conn.retryTimer = null;
341
+ for (const listener of conn.terminalListeners) listener();
342
+ }
214
343
 
215
344
  function emitSynthetic(status: NatsStatus) {
216
345
  if (closed) return;
217
346
  options.onStatusChange?.(status, { status });
218
347
  if (status === 'connected') {
219
- retryAttempt = 0;
348
+ markHealthy();
220
349
  }
221
350
  }
222
351
 
352
+ const notifyTerminal = () => {
353
+ if (!closed) options.onTerminal?.();
354
+ };
355
+ conn.terminalListeners.add(notifyTerminal);
356
+
223
357
  // A lifecycle's identity IS its `scheduleRetry`: that function goes on the
224
358
  // connection's roster and, for whichever lifecycle holds the loop, into
225
359
  // `retryOwner` — one identity, not two.
@@ -228,6 +362,7 @@ export function startConnectionLifecycle(options: ConnectionLifecycleOptions): C
228
362
 
229
363
  function scheduleRetry() {
230
364
  if (closed) return;
365
+ if (conn.terminal) return;
231
366
  if (getSharedConnectionFor(wsUrl) !== conn) return;
232
367
  // This lifecycle now wants a different URL, so it must not drive this
233
368
  // connection — not from its own status events, and not as a handoff
@@ -255,12 +390,12 @@ export function startConnectionLifecycle(options: ConnectionLifecycleOptions): C
255
390
  const maxDelay = cfg.maxDelayMs ?? NATS_DEFAULTS.RETRY_MAX_DELAY_MS;
256
391
  const multiplier = cfg.multiplier ?? NATS_DEFAULTS.RETRY_MULTIPLIER;
257
392
 
393
+ const attempt = conn.failedDials;
258
394
  const delay =
259
- retryAttempt < fastRetries
260
- ? fastDelay
261
- : Math.min(baseDelay * multiplier ** (retryAttempt - fastRetries), maxDelay);
262
- const jitteredDelay = delay * (0.5 + Math.random() * 0.5);
263
- retryAttempt++;
395
+ attempt < fastRetries ? fastDelay : Math.min(baseDelay * multiplier ** (attempt - fastRetries), maxDelay);
396
+ // A pause outranks the backoff: whoever arms the timer — the owner, or a
397
+ // successor taking over mid-pause — waits out what is left of it.
398
+ const wait = Math.max(delay * (0.5 + Math.random() * 0.5), conn.pause ? conn.pause.until - Date.now() : 0);
264
399
 
265
400
  // The retry body is a named async function rather than the timer callback
266
401
  // itself: `setTimeout` discards whatever its callback returns, so an async
@@ -271,6 +406,7 @@ export function startConnectionLifecycle(options: ConnectionLifecycleOptions): C
271
406
  const runRetry = async () => {
272
407
  conn.retryTimer = null;
273
408
  if (closed) return;
409
+ if (conn.terminal) return;
274
410
  if (getSharedConnectionFor(wsUrl) !== conn) return;
275
411
 
276
412
  // Nothing to reconnect. Reached when the dial that was already in flight
@@ -279,17 +415,32 @@ export function startConnectionLifecycle(options: ConnectionLifecycleOptions): C
279
415
  // is a token refresh in the real callers, so it must not run on a
280
416
  // connection that came back on its own.
281
417
  if (conn.client.isConnected()) {
282
- retryAttempt = 0;
418
+ markHealthy();
283
419
  return;
284
420
  }
285
421
 
422
+ // The pause that armed this timer is over. A pause lifted early has
423
+ // already cleared it, so this only fires for one that ran its course.
424
+ if (conn.pause && conn.pause.until <= Date.now()) endPause();
425
+
426
+ let verdict: NatsReconnectVerdict | void = undefined;
286
427
  try {
287
- await options.onBeforeReconnect?.();
428
+ verdict = await options.onBeforeReconnect?.({ consecutiveFailures: conn.failedDials });
288
429
  } catch {
289
430
  // continue regardless of token-refresh outcome
290
431
  }
291
432
  if (closed) return;
292
433
  if (getSharedConnectionFor(wsUrl) !== conn) return;
434
+ // A verdict is a fact about the connection, so it applies even if this
435
+ // lifecycle is the one leaving: the successor inherits it.
436
+ if (conn.terminal) return;
437
+ if (verdict === 'terminal') {
438
+ markTerminal();
439
+ return;
440
+ }
441
+ if (verdict === 'pause' || conn.failedDials >= NATS_DEFAULTS.PAUSE_AFTER_FAILURES) {
442
+ startPause();
443
+ }
293
444
 
294
445
  const freshUrl = options.getFreshUrl();
295
446
  if (freshUrl !== wsUrl) {
@@ -313,13 +464,21 @@ export function startConnectionLifecycle(options: ConnectionLifecycleOptions): C
313
464
  return;
314
465
  }
315
466
 
467
+ // Paused: nothing to dial until the pause ends. Re-arming here (rather
468
+ // than looping on a long timer) keeps one code path for the delay.
469
+ if (conn.pause) {
470
+ scheduleRetry();
471
+ return;
472
+ }
473
+
316
474
  try {
317
475
  await conn.client.connect();
318
476
  if (!closed && getSharedConnectionFor(wsUrl) === conn) {
319
- retryAttempt = 0;
477
+ markHealthy();
320
478
  }
321
- } catch {
479
+ } catch (err) {
322
480
  if (!closed && getSharedConnectionFor(wsUrl) === conn) {
481
+ countFailedDial(err);
323
482
  scheduleRetry();
324
483
  }
325
484
  }
@@ -329,7 +488,7 @@ export function startConnectionLifecycle(options: ConnectionLifecycleOptions): C
329
488
  runRetry().catch((err: unknown) => {
330
489
  console.warn('[nats] retry attempt threw:', err);
331
490
  });
332
- }, jitteredDelay);
491
+ }, wait);
333
492
  }
334
493
 
335
494
  const shouldRetryOn = options.shouldRetryOn ?? defaultShouldRetryOn;
@@ -338,7 +497,7 @@ export function startConnectionLifecycle(options: ConnectionLifecycleOptions): C
338
497
  if (closed) return;
339
498
  options.onStatusChange?.(evt.status, evt);
340
499
  if (evt.status === 'connected') {
341
- retryAttempt = 0;
500
+ markHealthy();
342
501
  }
343
502
  if (shouldRetryOn(evt.status)) {
344
503
  scheduleRetry();
@@ -359,22 +518,37 @@ export function startConnectionLifecycle(options: ConnectionLifecycleOptions): C
359
518
  // dead for as long as anything held a reference to it. `NatsClient.connect()`
360
519
  // already short-circuits on a live connection and joins its own in-flight
361
520
  // dial, so the second copy of that bookkeeping bought nothing.
362
- void (async () => {
363
- try {
364
- await conn.client.connect();
365
- } catch {
366
- if (closed) return;
521
+ //
522
+ // The first dial is immediate only for a connection with no history. A
523
+ // lifecycle attaching to one that has failed, is paused or is armed for a
524
+ // retry (every consumer mount, `urlRevision` re-runs) must not dial past
525
+ // that: it goes through scheduleRetry, which backs off or declines.
526
+ if (conn.terminal) {
527
+ emitSynthetic('disconnected');
528
+ options.onTerminal?.();
529
+ } else if (!conn.client.isConnected() && (conn.failedDials > 0 || conn.pause || conn.retryTimer)) {
530
+ emitSynthetic('disconnected');
531
+ scheduleRetry();
532
+ } else {
533
+ void (async () => {
534
+ try {
535
+ await conn.client.connect();
536
+ } catch (err) {
537
+ if (closed) return;
367
538
 
368
- emitSynthetic('disconnected');
369
- scheduleRetry();
370
- }
371
- })();
539
+ countFailedDial(err);
540
+ emitSynthetic('disconnected');
541
+ scheduleRetry();
542
+ }
543
+ })();
544
+ }
372
545
 
373
546
  return {
374
547
  stop() {
375
548
  closed = true;
376
549
  unsubStatus();
377
550
  conn.retrySchedulers.delete(scheduleRetry);
551
+ conn.terminalListeners.delete(notifyTerminal);
378
552
 
379
553
  if (conn.retryOwner !== scheduleRetry) {
380
554
  // Not ours to cancel. `retryTimer` lives on the CONNECTION, and
@@ -397,8 +571,8 @@ export function startConnectionLifecycle(options: ConnectionLifecycleOptions): C
397
571
  // disconnect lets a survivor claim opportunistically. `wasRetrying` is
398
572
  // read before the clearTimeout above, and the remaining case — the timer
399
573
  // already fired and its callback is mid-dial — is caught by the
400
- // connection not being connected. The successor backs off on its OWN
401
- // attempt counter, which is zero unless it has driven the loop before.
574
+ // connection not being connected. The successor continues the
575
+ // connection's own failure count and pause, not one of its own.
402
576
  if (!wasRetrying && conn.client.isConnected()) return;
403
577
  handOffRetry(conn);
404
578
  },