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

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 (132) hide show
  1. package/dist/{case-study-card-MEWJNF4N.cjs → case-study-card-AMINZROX.cjs} +5 -5
  2. package/dist/{chunk-FRS2VO22.cjs → chunk-243TS7YL.cjs} +38 -38
  3. package/dist/{chunk-GAHXURKJ.cjs → chunk-5QLDHPPU.cjs} +2 -2
  4. package/dist/{chunk-WDL3GFH2.cjs → chunk-66J7ZSI5.cjs} +34 -34
  5. package/dist/{chunk-VKAFZCFV.cjs → chunk-6GT3ZL27.cjs} +28 -28
  6. package/dist/{chunk-PRCGRDHV.cjs → chunk-7Y6M4FW4.cjs} +5 -5
  7. package/dist/{chunk-TOWVMBAP.cjs → chunk-ACCZCRXT.cjs} +14 -14
  8. package/dist/{chunk-VXAKQRV7.cjs → chunk-APOMNC7H.cjs} +5 -5
  9. package/dist/{chunk-KS5V55HN.cjs → chunk-CB77J5L7.cjs} +864 -670
  10. package/dist/{chunk-VHX4A4SA.cjs → chunk-CC3Q3MQG.cjs} +2 -2
  11. package/dist/{chunk-WV44WJKR.cjs → chunk-CJ7W2SY4.cjs} +8 -8
  12. package/dist/{chunk-DDFT6VQ3.cjs → chunk-CLU2KJFB.cjs} +3 -3
  13. package/dist/{chunk-OJZBZH56.cjs → chunk-CNTBGJA7.cjs} +3 -3
  14. package/dist/{chunk-Q3C6UJJ7.cjs → chunk-CPP2APON.cjs} +89 -89
  15. package/dist/{chunk-TT64NRFU.cjs → chunk-ERLMCSGF.cjs} +3 -3
  16. package/dist/{chunk-5UTJARDM.cjs → chunk-FK2WFU7R.cjs} +17 -17
  17. package/dist/{chunk-7PNRXJX2.cjs → chunk-FX35L4Y6.cjs} +3 -3
  18. package/dist/{chunk-5GJM7VRR.cjs → chunk-GI3MMBP3.cjs} +91 -26
  19. package/dist/{chunk-AZJYMTBS.cjs → chunk-GU3GJ5DH.cjs} +50 -50
  20. package/dist/{chunk-VUKN6KEE.cjs → chunk-IQLXO6EI.cjs} +97 -97
  21. package/dist/{chunk-BT53NHR7.cjs → chunk-J6C7F63P.cjs} +120 -120
  22. package/dist/{chunk-PIKHEBG5.cjs → chunk-JNWJB4Z5.cjs} +52 -52
  23. package/dist/{chunk-5MTYKS2Q.cjs → chunk-KVDUWXVZ.cjs} +4 -4
  24. package/dist/{chunk-V4FXUIMH.cjs → chunk-LC65AC6M.cjs} +4 -4
  25. package/dist/{chunk-RZNRKWG5.cjs → chunk-MDBOYMCW.cjs} +22 -22
  26. package/dist/{chunk-AQXKXZWB.cjs → chunk-MG3HJIGG.cjs} +4 -4
  27. package/dist/{chunk-KVJKKVB3.cjs → chunk-NZSWROGM.cjs} +7 -7
  28. package/dist/{chunk-OAJ3AL4V.cjs → chunk-O32RLIN4.cjs} +6 -6
  29. package/dist/{chunk-ZAXGW4KT.cjs → chunk-O4MEG2ZS.cjs} +21 -21
  30. package/dist/{chunk-4W77VLQV.cjs → chunk-OQDPZOGC.cjs} +6 -6
  31. package/dist/{chunk-LUICXMHC.cjs → chunk-PCVY63WQ.cjs} +17 -17
  32. package/dist/{chunk-ML3DG4SS.cjs → chunk-PMOMZSCX.cjs} +5 -5
  33. package/dist/{chunk-TUZV2ZQY.cjs → chunk-Q7QYAINS.cjs} +2 -2
  34. package/dist/{chunk-KHKPLOU4.cjs → chunk-QDB2JO55.cjs} +144 -36
  35. package/dist/{chunk-KCB72H7A.cjs → chunk-R55KNVPR.cjs} +71 -71
  36. package/dist/{chunk-NG3RKTQU.cjs → chunk-SFUNXMY3.cjs} +8 -8
  37. package/dist/{chunk-3B76QFXV.cjs → chunk-TKK66KHU.cjs} +6 -6
  38. package/dist/{chunk-TGOJHOQR.cjs → chunk-U2MHQBL4.cjs} +3 -3
  39. package/dist/{chunk-I3RJLXEL.cjs → chunk-UP3TLY2V.cjs} +131 -131
  40. package/dist/{chunk-KITOT3DS.cjs → chunk-VXMPVDOS.cjs} +26 -26
  41. package/dist/{chunk-UVLTUSH3.cjs → chunk-WX5WDSKV.cjs} +583 -582
  42. package/dist/{chunk-OFGYPMTE.cjs → chunk-XLEWM5X5.cjs} +53 -53
  43. package/dist/{chunk-SZHDXXMK.cjs → chunk-YSDB6HGQ.cjs} +3 -3
  44. package/dist/{chunk-JLKGLPDC.cjs → chunk-ZW25QUJK.cjs} +16 -16
  45. package/dist/{chunk-FLW2VL5W.cjs → chunk-ZZO3FGPM.cjs} +24 -24
  46. package/dist/{cloud-tenants-DJAA23GR.cjs → cloud-tenants-XGGQG7SO.cjs} +25 -25
  47. package/dist/components/case-studies/index.cjs +41 -41
  48. package/dist/components/chat/entity-cards/dispatch.d.ts.map +1 -1
  49. package/dist/components/chat/entity-cards/dispatch.js +4 -1
  50. package/dist/components/chat/hooks/use-jetstream-dialog-subscription.js +1 -1
  51. package/dist/components/chat/hooks/use-nats-dialog-subscription.js +1 -1
  52. package/dist/components/chat/index.cjs +19 -19
  53. package/dist/components/chat/types/api.types.d.ts +8 -4
  54. package/dist/components/chat/types/api.types.d.ts.map +1 -1
  55. package/dist/components/contact/index.cjs +26 -26
  56. package/dist/components/docs/index.cjs +29 -29
  57. package/dist/components/embeds/index.cjs +26 -26
  58. package/dist/components/faq/index.cjs +27 -27
  59. package/dist/components/features/index.cjs +25 -25
  60. package/dist/components/help-center-pages/index.cjs +130 -130
  61. package/dist/components/index.cjs +90 -90
  62. package/dist/components/meeting-scheduler/index.cjs +94 -94
  63. package/dist/components/navigation/index.cjs +28 -28
  64. package/dist/components/onboarding-guides/index.cjs +28 -28
  65. package/dist/components/product-demo/index.cjs +36 -36
  66. package/dist/components/related-content/index.cjs +14 -14
  67. package/dist/components/tickets/index.cjs +32 -32
  68. package/dist/components/ui/index.cjs +25 -25
  69. package/dist/components/ui/markdown/base-components.d.ts.map +1 -1
  70. package/dist/components/ui/markdown/base-components.js +6 -7
  71. package/dist/components/ui/markdown/engine.d.ts +7 -0
  72. package/dist/components/ui/markdown/engine.d.ts.map +1 -1
  73. package/dist/components/ui/markdown/engine.js +12 -3
  74. package/dist/components/ui/markdown/external-media-notice.d.ts +33 -0
  75. package/dist/components/ui/markdown/external-media-notice.d.ts.map +1 -0
  76. package/dist/components/ui/markdown/external-media-notice.js +56 -0
  77. package/dist/components/ui/markdown/mermaid-diagram.d.ts +24 -2
  78. package/dist/components/ui/markdown/mermaid-diagram.d.ts.map +1 -1
  79. package/dist/components/ui/markdown/mermaid-diagram.js +66 -6
  80. package/dist/components/ui/markdown/rich/rich-markdown-renderer.d.ts +4 -4
  81. package/dist/components/ui/markdown/rich/rich-markdown-renderer.d.ts.map +1 -1
  82. package/dist/components/ui/markdown/rich/rich-markdown-renderer.js +2 -1
  83. package/dist/components/ui/markdown/sanitize.d.ts +28 -3
  84. package/dist/components/ui/markdown/sanitize.d.ts.map +1 -1
  85. package/dist/components/ui/markdown/sanitize.js +84 -12
  86. package/dist/components/ui/markdown/simple-markdown-renderer.d.ts +3 -2
  87. package/dist/components/ui/markdown/simple-markdown-renderer.d.ts.map +1 -1
  88. package/dist/{devices-AIDQW4HB.cjs → devices-H5Y4DBVC.cjs} +26 -26
  89. package/dist/{embeddable-chat-XT6GMSBX.cjs → embeddable-chat-77ZOLCCK.cjs} +89 -89
  90. package/dist/hooks/index.cjs +11 -11
  91. package/dist/index.cjs +30 -30
  92. package/dist/{knowledge-JWCFM3GO.cjs → knowledge-MGH65HXM.cjs} +26 -26
  93. package/dist/{logs-ZNIXPJXA.cjs → logs-OL7ETVK6.cjs} +33 -33
  94. package/dist/nats/index.cjs +2 -2
  95. package/dist/nats/nats-provider.d.ts +9 -3
  96. package/dist/nats/nats-provider.d.ts.map +1 -1
  97. package/dist/nats/nats-provider.js +7 -3
  98. package/dist/nats/shared-connection.d.ts +44 -1
  99. package/dist/nats/shared-connection.d.ts.map +1 -1
  100. package/dist/nats/shared-connection.js +126 -22
  101. package/dist/{policies-Z4NGPLA2.cjs → policies-BCECWQ3F.cjs} +29 -29
  102. package/dist/{remote-session-LMUFV2RZ.cjs → remote-session-HML4UF7W.cjs} +11 -11
  103. package/dist/{scripts-G4Y5SPOW.cjs → scripts-XCD6V2JB.cjs} +32 -32
  104. package/dist/{software-update-VAOKDA76.cjs → software-update-U5ESXRG5.cjs} +29 -29
  105. package/dist/{tickets-board-QF5JNSH2.cjs → tickets-board-EICQ5VLE.cjs} +14 -14
  106. package/dist/utils/app-origins.d.ts +41 -0
  107. package/dist/utils/app-origins.d.ts.map +1 -0
  108. package/dist/utils/app-origins.js +51 -0
  109. package/dist/utils/embed-auth-adapter-registry.d.ts +7 -0
  110. package/dist/utils/embed-auth-adapter-registry.d.ts.map +1 -0
  111. package/dist/utils/embed-auth-adapter-registry.js +34 -0
  112. package/dist/utils/embed-authed-fetch.d.ts.map +1 -1
  113. package/dist/utils/embed-authed-fetch.js +6 -19
  114. package/dist/utils/index.cjs +28 -12
  115. package/dist/{video-file-player-2FMFCGXE.cjs → video-file-player-4QMVTOBE.cjs} +3 -3
  116. package/package.json +1 -1
  117. package/src/components/chat/entity-cards/dispatch.tsx +12 -1
  118. package/src/components/chat/hooks/use-jetstream-dialog-subscription.ts +1 -1
  119. package/src/components/chat/hooks/use-nats-dialog-subscription.ts +1 -1
  120. package/src/components/chat/types/api.types.ts +8 -4
  121. package/src/components/ui/markdown/base-components.tsx +6 -7
  122. package/src/components/ui/markdown/engine.tsx +29 -5
  123. package/src/components/ui/markdown/external-media-notice.tsx +84 -0
  124. package/src/components/ui/markdown/mermaid-diagram.tsx +107 -5
  125. package/src/components/ui/markdown/rich/rich-markdown-renderer.tsx +11 -5
  126. package/src/components/ui/markdown/sanitize.ts +162 -15
  127. package/src/components/ui/markdown/simple-markdown-renderer.tsx +6 -2
  128. package/src/nats/nats-provider.tsx +15 -4
  129. package/src/nats/shared-connection.ts +199 -25
  130. package/src/utils/app-origins.ts +95 -0
  131. package/src/utils/embed-auth-adapter-registry.ts +49 -0
  132. package/src/utils/embed-authed-fetch.ts +7 -35
@@ -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
  },
@@ -0,0 +1,95 @@
1
+ import { readRegisteredAdapter, subscribeRegisteredAdapter } from './embed-auth-adapter-registry';
2
+
3
+ /**
4
+ * Where the app loads from: the page, and the origins the host sanctions in
5
+ * `EmbedAuthAdapter.allowedOrigins` (the gateway of a native shell, whose page
6
+ * origin is `capacitor://` / `tauri://`). Untrusted markdown may load media
7
+ * only from here; `embedAuthedFetch` sends the bearer only here.
8
+ */
9
+ export interface AppOrigins {
10
+ /** The page's root URL (`https://host/`, `capacitor://localhost/`); `null` on the server, where there is no page. */
11
+ readonly pageUrl: string | null;
12
+ readonly allowedOrigins: readonly string[];
13
+ }
14
+
15
+ /** The server's answer, and the first one a hydrating client gives: only relative URLs belong to the app. */
16
+ export const SERVER_APP_ORIGINS: AppOrigins = Object.freeze({ pageUrl: null, allowedOrigins: Object.freeze([]) });
17
+
18
+ /** Base relative URLs resolve against without a page: only a relative URL lands on it. */
19
+ const SERVER_PAGE_URL = 'http://app.invalid/';
20
+
21
+ let snapshot: AppOrigins = SERVER_APP_ORIGINS;
22
+
23
+ /**
24
+ * The app's origins now. Same object until they change, so it can be a
25
+ * `useSyncExternalStore` snapshot (`subscribeAppOrigins` reports the change).
26
+ */
27
+ export function readAppOrigins(): AppOrigins {
28
+ if (typeof window === 'undefined') return SERVER_APP_ORIGINS;
29
+ // The page's root, not its full URL: only the origin decides, and a snapshot
30
+ // that changed with every `?tab=` would re-parse every markdown body on the
31
+ // page. Parsed from `href` rather than read from `window.location.origin`:
32
+ // tests mock `window.location` as a plain object without an `origin` field.
33
+ let pageUrl: string;
34
+ try {
35
+ pageUrl = new URL('/', window.location.href).href;
36
+ } catch {
37
+ return SERVER_APP_ORIGINS;
38
+ }
39
+ const allowedOrigins = readRegisteredAdapter<{ allowedOrigins?: readonly string[] }>()?.allowedOrigins ?? [];
40
+ if (
41
+ snapshot.pageUrl !== pageUrl ||
42
+ snapshot.allowedOrigins.length !== allowedOrigins.length ||
43
+ snapshot.allowedOrigins.some((origin, i) => origin !== allowedOrigins[i])
44
+ ) {
45
+ snapshot = { pageUrl, allowedOrigins: [...allowedOrigins] };
46
+ }
47
+ return snapshot;
48
+ }
49
+
50
+ /** Called when a host registers, replaces or clears its auth adapter, which can change `allowedOrigins`. */
51
+ export const subscribeAppOrigins: (listener: () => void) => () => void = subscribeRegisteredAdapter;
52
+
53
+ /**
54
+ * `url` resolved against the page when it belongs to the app, otherwise `null`.
55
+ *
56
+ * The page match compares scheme and host instead of `URL.origin`, which is
57
+ * `"null"` for a `capacitor://` page.
58
+ */
59
+ export function resolveAppOriginUrl(url: string, origins: AppOrigins = readAppOrigins()): URL | null {
60
+ let page: URL;
61
+ let target: URL;
62
+ try {
63
+ page = new URL(origins.pageUrl ?? SERVER_PAGE_URL);
64
+ target = new URL(url, page);
65
+ } catch {
66
+ return null;
67
+ }
68
+ if (target.protocol === page.protocol && target.host === page.host) return target;
69
+ if (target.protocol !== 'http:' && target.protocol !== 'https:') return null;
70
+ return origins.allowedOrigins.includes(target.origin) ? target : null;
71
+ }
72
+
73
+ /**
74
+ * Whether `url` loads from the app itself rather than from a third party.
75
+ * Untrusted markdown may only load media from here: a third-party `<img src>`
76
+ * is a request the content's author receives, with whatever the URL carries.
77
+ * Pass `origins` to decide against a snapshot (a render that must give the
78
+ * server's answer while it hydrates); it defaults to the app's origins now.
79
+ */
80
+ export function isAppOriginUrl(url: string, origins?: AppOrigins): boolean {
81
+ return resolveAppOriginUrl(url, origins) !== null;
82
+ }
83
+
84
+ /**
85
+ * `url` as an absolute http(s) URL against `origins`' page, for a notice to
86
+ * name its host; `null` when it is not http(s).
87
+ */
88
+ export function absoluteHttpUrl(url: string, origins: AppOrigins = readAppOrigins()): string | null {
89
+ try {
90
+ const resolved = new URL(url.trim(), origins.pageUrl ?? SERVER_PAGE_URL);
91
+ return resolved.protocol === 'http:' || resolved.protocol === 'https:' ? resolved.href : null;
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The slot the host's auth adapter (`setEmbedAuthAdapter`) is registered in, and the listeners told when it changes.
3
+ *
4
+ * Both are parked on `globalThis`, NOT in module-private `let`s. Reason: this lib ships multiple entry points
5
+ * (`/utils`, `/components/chat`, …) and a consumer's bundler can inline a file into more than one chunk, giving each
6
+ * chunk its OWN module scope. If the host calls `setEmbedAuthAdapter` from the `/utils` copy while the chat's
7
+ * `embedAuthedFetch` runs from the `/components/chat` copy, a module-local `let` would be set on one copy and read as
8
+ * `null` on the other (the exact "credentials: same-origin, no Bearer, no refresh" symptom). The listeners follow the
9
+ * slot for the same reason: one registered in another copy must still hear about the change.
10
+ *
11
+ * No imports, so the readers (`embed-authed-fetch`, `app-origins`) do not depend on each other through it.
12
+ */
13
+ const ADAPTER_GLOBAL_KEY = '__embedAuthedFetchAdapter__';
14
+ const LISTENERS_GLOBAL_KEY = '__embedAuthedFetchAdapterListeners__';
15
+
16
+ type Slots = Record<string, unknown>;
17
+
18
+ function listeners(): Set<() => void> {
19
+ const slots = globalThis as Slots;
20
+ let set = slots[LISTENERS_GLOBAL_KEY] as Set<() => void> | undefined;
21
+ if (!set) {
22
+ set = new Set();
23
+ slots[LISTENERS_GLOBAL_KEY] = set;
24
+ }
25
+ return set;
26
+ }
27
+
28
+ /** The registered adapter, typed by the caller (the slot itself does not know the adapter's shape). */
29
+ export function readRegisteredAdapter<T>(): T | null {
30
+ if (typeof globalThis === 'undefined') return null;
31
+ return ((globalThis as Slots)[ADAPTER_GLOBAL_KEY] as T | null | undefined) ?? null;
32
+ }
33
+
34
+ /** Store the adapter (or `null`) and tell every listener, in every copy of this module. */
35
+ export function writeRegisteredAdapter(adapter: unknown): void {
36
+ if (typeof globalThis === 'undefined') return;
37
+ (globalThis as Slots)[ADAPTER_GLOBAL_KEY] = adapter;
38
+ for (const listener of [...listeners()]) listener();
39
+ }
40
+
41
+ /** Called after every registration, replacement or clear. */
42
+ export function subscribeRegisteredAdapter(listener: () => void): () => void {
43
+ if (typeof globalThis === 'undefined') return () => {};
44
+ const set = listeners();
45
+ set.add(listener);
46
+ return () => {
47
+ set.delete(listener);
48
+ };
49
+ }
@@ -20,6 +20,8 @@
20
20
  * (e.g. `/api/profile/me`) keep using vanilla `fetch`.
21
21
  */
22
22
 
23
+ import { resolveAppOriginUrl } from './app-origins';
24
+ import { readRegisteredAdapter, writeRegisteredAdapter } from './embed-auth-adapter-registry';
23
25
  import { applyProxyAuth } from './embed-proxy-auth-storage';
24
26
 
25
27
  // =============================================================================
@@ -139,28 +141,9 @@ export interface EmbedAuthAdapter {
139
141
  subscribe?: (listener: () => void) => () => void;
140
142
  }
141
143
 
142
- /**
143
- * The registered adapter is parked on `globalThis`, NOT in a module-private
144
- * `let`. Reason: this lib ships multiple entry points (`/utils`,
145
- * `/components/chat`, …) and a consumer's bundler can inline this file into
146
- * more than one chunk — giving each chunk its OWN module scope. If the host
147
- * calls `setEmbedAuthAdapter` from the `/utils` copy while the chat's
148
- * `embedAuthedFetch` runs from the `/components/chat` copy, a module-local
149
- * `let` would be set on one copy and read as `null` on the other (the exact
150
- * "credentials: same-origin, no Bearer, no refresh" symptom). A single
151
- * `globalThis` slot is shared across every copy, so registration always
152
- * reaches the fetch path.
153
- */
154
- const ADAPTER_GLOBAL_KEY = '__embedAuthedFetchAdapter__';
155
-
144
+ /** The registered adapter: a `globalThis` slot shared by every copy of this module (see the registry). */
156
145
  function getRegisteredAuthAdapter(): EmbedAuthAdapter | null {
157
- if (typeof globalThis === 'undefined') return null;
158
- return ((globalThis as Record<string, unknown>)[ADAPTER_GLOBAL_KEY] as EmbedAuthAdapter | null) ?? null;
159
- }
160
-
161
- function storeRegisteredAuthAdapter(adapter: EmbedAuthAdapter | null): void {
162
- if (typeof globalThis === 'undefined') return;
163
- (globalThis as Record<string, unknown>)[ADAPTER_GLOBAL_KEY] = adapter;
146
+ return readRegisteredAdapter<EmbedAuthAdapter>();
164
147
  }
165
148
 
166
149
  /**
@@ -181,7 +164,7 @@ export function setEmbedAuthAdapter(adapter: EmbedAuthAdapter | null): void {
181
164
  'mount order and pass `null` from the unmounting provider.',
182
165
  );
183
166
  }
184
- storeRegisteredAuthAdapter(adapter);
167
+ writeRegisteredAdapter(adapter);
185
168
  }
186
169
 
187
170
  /**
@@ -237,19 +220,8 @@ export function needsBearerAssetFetch(url: string): boolean {
237
220
  if (typeof window === 'undefined') return false;
238
221
  const adapter = getRegisteredAuthAdapter();
239
222
  if (!adapter || adapter.getHeaders?.().Authorization === undefined) return false;
240
- let target: URL;
241
- let pageOrigin: string;
242
- try {
243
- target = new URL(url, window.location.href);
244
- // Same reason `assertSameOrigin` derives it this way: test environments
245
- // mock `window.location` as a plain object with no `origin` field.
246
- pageOrigin = new URL(window.location.href).origin;
247
- } catch {
248
- return false;
249
- }
250
- if (target.protocol !== 'http:' && target.protocol !== 'https:') return false;
251
- if (target.origin === pageOrigin) return true;
252
- return adapter.allowedOrigins?.includes(target.origin) ?? false;
223
+ const target = resolveAppOriginUrl(url);
224
+ return target !== null && (target.protocol === 'http:' || target.protocol === 'https:');
253
225
  }
254
226
 
255
227
  /**