@djangocfg/layouts 2.1.659 → 2.1.661

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.
package/README.md CHANGED
@@ -189,6 +189,18 @@ Wraps `Boundary` from `@djangocfg/ui-core` — same `variant`/`fallback`/`resetK
189
189
 
190
190
  For local UI widgets that should not report to backend, use `Boundary` from `@djangocfg/ui-core` directly.
191
191
 
192
+ ## Realtime
193
+
194
+ `BaseApp` mounts `RealtimeProvider` from `@djangocfg/realtime` inside `AuthProvider`. It opens no socket until a
195
+ component calls `useTopic`, so a page that never subscribes costs nothing. The socket URL is the API origin plus
196
+ `/ws` (`ws:`/`wss:` by scheme). An SWR middleware makes every `useSWR` whose key is tagged with a topic
197
+ (`['orders:42', …]`) revalidate on each publication and on a gap, at most once per ~250 ms; untagged keys open no
198
+ socket. Realtime issues (a 4401/4403/4500 close, five failed handshakes in a row, a refused topic, a protocol
199
+ error, a dev schema failure) go to `@djangocfg/devtools` like any other frontend error; normal drops are not
200
+ reported. `realtime={{ url, path, onGap, onIssue }}` tunes it, `realtime={false}` removes it. `@djangocfg/realtime`
201
+ is a required peer. Usage:
202
+ [`@djangocfg/realtime`](../realtime/README.md).
203
+
192
204
  ## Analytics and auth funnels
193
205
 
194
206
  `BaseApp` mounts the first-party `AnalyticsProvider` once and bridges events
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djangocfg/layouts",
3
- "version": "2.1.659",
3
+ "version": "2.1.661",
4
4
  "description": "Simple, straightforward layout components for Next.js - import and use with props",
5
5
  "keywords": [
6
6
  "layouts",
@@ -91,11 +91,12 @@
91
91
  "test": "vitest run"
92
92
  },
93
93
  "peerDependencies": {
94
- "@djangocfg/analytics": "^2.1.659",
95
- "@djangocfg/api": "^2.1.659",
96
- "@djangocfg/devtools": "^2.1.659",
97
- "@djangocfg/i18n": "^2.1.659",
98
- "@djangocfg/ui-core": "^2.1.659",
94
+ "@djangocfg/analytics": "^2.1.661",
95
+ "@djangocfg/api": "^2.1.661",
96
+ "@djangocfg/devtools": "^2.1.661",
97
+ "@djangocfg/i18n": "^2.1.661",
98
+ "@djangocfg/realtime": "^2.1.661",
99
+ "@djangocfg/ui-core": "^2.1.661",
99
100
  "@hookform/resolvers": "^5.2.2 || ^7.0.2",
100
101
  "consola": "^3.4.2",
101
102
  "lucide-react": "^1.68.0",
@@ -123,12 +124,13 @@
123
124
  "qrcode.react": "^4.2.0"
124
125
  },
125
126
  "devDependencies": {
126
- "@djangocfg/analytics": "^2.1.659",
127
- "@djangocfg/api": "^2.1.659",
128
- "@djangocfg/devtools": "^2.1.659",
129
- "@djangocfg/i18n": "^2.1.659",
130
- "@djangocfg/typescript-config": "^2.1.659",
131
- "@djangocfg/ui-core": "^2.1.659",
127
+ "@djangocfg/analytics": "^2.1.661",
128
+ "@djangocfg/api": "^2.1.661",
129
+ "@djangocfg/devtools": "^2.1.661",
130
+ "@djangocfg/i18n": "^2.1.661",
131
+ "@djangocfg/realtime": "^2.1.661",
132
+ "@djangocfg/typescript-config": "^2.1.661",
133
+ "@djangocfg/ui-core": "^2.1.661",
132
134
  "@storybook/react-vite": "^10.6.5",
133
135
  "@types/node": "^25.9.5",
134
136
  "@types/react": "19.3.0",
@@ -137,6 +139,7 @@
137
139
  "next-intl": "^4.14.9",
138
140
  "sonner": "2.0.8",
139
141
  "storybook": "^10.6.5",
142
+ "swr": "^2.5.1",
140
143
  "typescript": "^5.9.3",
141
144
  "vitest": "^5.1.0",
142
145
  "zustand": "^5.0.16"
@@ -7,6 +7,8 @@ import type {
7
7
  } from '@djangocfg/ui-core/components';
8
8
  import { EventLevel, EventType, devtools } from '@djangocfg/devtools';
9
9
  import { useCallback } from 'react';
10
+
11
+ import { reportRenderError } from './reportRenderError';
10
12
  import type { ErrorInfo, ReactNode } from 'react';
11
13
 
12
14
  export interface MonitorBoundaryProps extends Omit<BoundaryProps, 'onError' | 'onReset'> {
@@ -26,21 +28,7 @@ function currentUrl(): string | undefined {
26
28
  }
27
29
 
28
30
  function reportError(name: string | undefined, error: Error, info: ErrorInfo): void {
29
- try {
30
- devtools.capture({
31
- event_type: EventType.ERROR,
32
- level: EventLevel.ERROR,
33
- message: error.message || 'Unhandled React render error',
34
- stack_trace: error.stack,
35
- url: currentUrl(),
36
- extra: {
37
- source: name ?? 'boundary',
38
- componentStack: info.componentStack,
39
- },
40
- });
41
- } catch {
42
- // Never let monitor failures crash the boundary itself.
43
- }
31
+ reportRenderError(name ?? 'boundary', error, info);
44
32
  }
45
33
 
46
34
  function reportReset(name: string | undefined, details: BoundaryResetDetails): void {
@@ -0,0 +1,36 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ const capture = vi.fn();
4
+ const flush = vi.fn();
5
+ vi.mock('@djangocfg/devtools', () => ({
6
+ EventLevel: { ERROR: 'error' },
7
+ EventType: { ERROR: 'ERROR' },
8
+ devtools: { capture: (...a: unknown[]) => capture(...a), flush: () => flush() },
9
+ }));
10
+
11
+ import { reportRenderError } from './reportRenderError';
12
+
13
+ describe('reportRenderError', () => {
14
+ beforeEach(() => {
15
+ capture.mockReset();
16
+ flush.mockReset();
17
+ });
18
+
19
+ it('captures a render TypeError with its stack and component stack, then flushes', () => {
20
+ const err = new TypeError("Cannot read properties of undefined (reading 'x')");
21
+ reportRenderError('app', err, { componentStack: '\n in Page' } as never);
22
+ expect(capture).toHaveBeenCalledTimes(1);
23
+ const event = capture.mock.calls[0][0];
24
+ expect(event.message).toContain('Cannot read properties');
25
+ expect(event.stack_trace).toBe(err.stack);
26
+ expect(event.extra).toMatchObject({ source: 'app', errorName: 'TypeError', componentStack: '\n in Page' });
27
+ expect(flush).toHaveBeenCalledTimes(1);
28
+ });
29
+
30
+ it('never throws when devtools does', () => {
31
+ capture.mockImplementation(() => {
32
+ throw new Error('devtools down');
33
+ });
34
+ expect(() => reportRenderError('app', new Error('x'))).not.toThrow();
35
+ });
36
+ });
@@ -0,0 +1,34 @@
1
+ import type { ErrorInfo } from 'react';
2
+
3
+ import { EventLevel, EventType, devtools } from '@djangocfg/devtools';
4
+
5
+ /**
6
+ * Send a render error caught by an error boundary to the backend monitor.
7
+ *
8
+ * A boundary swallows the error: React renders the fallback and the exception
9
+ * never reaches `window.onerror`, so devtools' global capture cannot see it. This
10
+ * is the one place that reports it. It queues the event and flushes at once (the
11
+ * fallback's "Reload" can unload the page before the 5 s timer fires); the flush
12
+ * on `visibilitychange: hidden` still goes out with keepalive.
13
+ *
14
+ * Never throws: monitoring must not crash the boundary.
15
+ */
16
+ export function reportRenderError(source: string, error: Error, info?: ErrorInfo): void {
17
+ try {
18
+ devtools.capture({
19
+ event_type: EventType.ERROR,
20
+ level: EventLevel.ERROR,
21
+ message: error.message || 'Unhandled React render error',
22
+ stack_trace: error.stack,
23
+ url: typeof window !== 'undefined' ? window.location.href : undefined,
24
+ extra: {
25
+ source,
26
+ componentStack: info?.componentStack,
27
+ errorName: error.name,
28
+ },
29
+ });
30
+ devtools.flush();
31
+ } catch {
32
+ // ignore
33
+ }
34
+ }
@@ -13,6 +13,7 @@
13
13
  * - TooltipProvider (tooltip positioning)
14
14
  * - SWRConfig (data fetching)
15
15
  * - AuthProvider (authentication context)
16
+ * - RealtimeProvider (`@djangocfg/realtime`, lazy: no socket until a `useTopic` mounts)
16
17
  * - AuthDialog (global auth prompt dialog)
17
18
  * - AnalyticsProvider (Google Analytics, optional)
18
19
  * - LocaleSuggestion (offers the visitor's language when `i18n` has several locales)
@@ -56,6 +57,7 @@ import { RouteProgressProvider } from '@djangocfg/ui-core/route-progress';
56
57
  import { NextIntlLinkBridge } from './NextIntlLinkBridge';
57
58
  import { ThemeProvider } from '@djangocfg/ui-core/theme';
58
59
  import { AppErrorFallback } from '../../components/errors/AppErrorFallback';
60
+ import { reportRenderError } from '../../components/errors/reportRenderError';
59
61
  import { ErrorTrackingProvider } from '../../components/errors/ErrorsTracker';
60
62
  import { AnalyticsProvider } from '../../snippets/Analytics';
61
63
  import { AuthDialog } from '../../snippets/AuthDialog';
@@ -66,6 +68,9 @@ import { LocaleSuggestion } from '../../components/LocaleSuggestion';
66
68
  import { ProjectNameProvider } from '../../shared/ProjectContext';
67
69
  import { PwaManifestCheck, PwaMetaGuard } from './pwaMeta';
68
70
  import { resolveDevtoolsBaseUrl } from './devtoolsBaseUrl';
71
+ import { RealtimeMount } from './realtime/RealtimeMount';
72
+ import { realtimeRefresh } from './realtime/realtimeRefresh';
73
+ import { resolveRealtimeApiUrl } from './realtime/realtimeApiUrl';
69
74
 
70
75
  import React from 'react';
71
76
 
@@ -91,6 +96,26 @@ function ScrollToTop() {
91
96
  return null;
92
97
  }
93
98
 
99
+ const REALTIME_SWR_MIDDLEWARE = [realtimeRefresh];
100
+
101
+ /** Inside `AuthProvider` so a login or logout reconnects the socket with the new identity. */
102
+ function OptionalRealtime({
103
+ config,
104
+ apiUrl,
105
+ children,
106
+ }: {
107
+ config: BaseAppProps['realtime'];
108
+ apiUrl: string | undefined;
109
+ children: React.ReactNode;
110
+ }) {
111
+ if (config === false || config === undefined) return <>{children}</>;
112
+ return (
113
+ <RealtimeMount config={config} apiUrl={apiUrl}>
114
+ {children}
115
+ </RealtimeMount>
116
+ );
117
+ }
118
+
94
119
  /**
95
120
  * BaseApp - Core providers wrapper for any React/Next.js app
96
121
  *
@@ -112,6 +137,7 @@ export function BaseApp({
112
137
  i18n,
113
138
  pwaMeta = true,
114
139
  progressBar = true,
140
+ realtime = {},
115
141
  debug,
116
142
  }: BaseAppProps) {
117
143
  // auth=false disables AuthProvider entirely (public apps with no login)
@@ -130,6 +156,8 @@ export function BaseApp({
130
156
  baseUrl: resolveDevtoolsBaseUrl({ auth, apiUrl, devtools: devtoolsConfig }),
131
157
  };
132
158
 
159
+ const realtimeApiUrl = resolveRealtimeApiUrl({ auth, apiUrl, realtime });
160
+
133
161
  const content = (
134
162
  <>
135
163
  {pwaMeta && <PwaMetaGuard />}
@@ -158,7 +186,12 @@ export function BaseApp({
158
186
  <UiProviders
159
187
  debug={debug}
160
188
  errorBoundary={enableErrorBoundary ? undefined : false}
161
- onError={errorBoundary?.onError}
189
+ onError={(error, info) => {
190
+ // The boundary swallows the error, so devtools' window.onerror never sees it:
191
+ // report it here, then let the host's own handler run.
192
+ reportRenderError('app-boundary', error, info);
193
+ errorBoundary?.onError?.(error, info);
194
+ }}
162
195
  errorFallback={
163
196
  enableErrorBoundary
164
197
  ? () => <AppErrorFallback supportEmail={errorBoundary?.supportEmail} />
@@ -170,9 +203,11 @@ export function BaseApp({
170
203
  revalidateOnFocus: swr?.revalidateOnFocus ?? true,
171
204
  revalidateOnReconnect: swr?.revalidateOnReconnect ?? true,
172
205
  dedupingInterval: swr?.dedupingInterval ?? 2000,
206
+ use: realtime === false ? undefined : REALTIME_SWR_MIDDLEWARE,
173
207
  }}
174
208
  >
175
209
  <AuthProvider config={authEnabled ? authConfig : undefined} enabled={authEnabled}>
210
+ <OptionalRealtime config={realtime} apiUrl={realtimeApiUrl}>
176
211
  <AnalyticsProvider trackingId={analytics?.googleTrackingId}>
177
212
  <ErrorTrackingProvider
178
213
  validation={errorTracking?.validation}
@@ -197,6 +232,7 @@ export function BaseApp({
197
232
  {authEnabled && <AuthDialog authPath={authConfig?.routes?.auth} />}
198
233
  </ErrorTrackingProvider>
199
234
  </AnalyticsProvider>
235
+ </OptionalRealtime>
200
236
  </AuthProvider>
201
237
  </SWRConfig>
202
238
  </UiProviders>
@@ -86,6 +86,7 @@ interface BaseAppProps {
86
86
  monitor?: MonitorConfig;
87
87
  debug?: DebugConfig; // debug panel (auto in dev / ?debug=1 in prod)
88
88
  i18n?: I18nLayoutConfig; // locale + routing for the link bridge
89
+ realtime?: RealtimeConfig | false; // lazy WebSocket for useTopic; issues go to devtools; false removes it
89
90
  }
90
91
  ```
91
92
 
@@ -10,6 +10,7 @@
10
10
 
11
11
  export { BaseApp } from './BaseApp';
12
12
  export { resolveDevtoolsBaseUrl } from './devtoolsBaseUrl';
13
+ export { resolveRealtimeApiUrl } from './realtime/realtimeApiUrl';
13
14
  export type { BaseAppProps } from './BaseApp';
14
15
 
15
16
  export type { I18nLayoutConfig } from '../types';
@@ -0,0 +1,73 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useEffect } from 'react';
4
+ import { useSWRConfig } from 'swr';
5
+
6
+ import { setRealtimeCidProvider } from '@djangocfg/api';
7
+ import { devtools } from '@djangocfg/devtools';
8
+ import { RealtimeProvider, isKeyForTopic, useRealtimeClient } from '@djangocfg/realtime/react';
9
+
10
+ import type { ReactNode } from 'react';
11
+ import type { ReportedIssue } from '@djangocfg/realtime';
12
+ import type { RealtimeConfig } from '@djangocfg/realtime/react';
13
+
14
+ import { realtimeIssueEvent } from './realtimeIssueEvent';
15
+
16
+ interface RealtimeMountProps {
17
+ config: RealtimeConfig;
18
+ apiUrl: string | undefined;
19
+ children: ReactNode;
20
+ }
21
+
22
+ /**
23
+ * Points `@djangocfg/api`'s `X-Realtime-Cid` header at this tab's socket, so a
24
+ * write's own publication is not echoed back to it. Cleared on unmount.
25
+ */
26
+ function RealtimeCidBridge() {
27
+ const client = useRealtimeClient();
28
+ useEffect(() => {
29
+ if (client === null) return;
30
+ setRealtimeCidProvider(() => client.getCid());
31
+ return () => setRealtimeCidProvider(null);
32
+ }, [client]);
33
+ return null;
34
+ }
35
+
36
+ /** Realtime problems go to the same monitor as every other frontend error. Never throws. */
37
+ function captureIssue(issue: ReportedIssue): void {
38
+ try {
39
+ devtools.capture(realtimeIssueEvent(issue, typeof window !== 'undefined' ? window.location.href : undefined));
40
+ } catch {
41
+ // Monitoring must not break the socket.
42
+ }
43
+ }
44
+
45
+ /**
46
+ * `RealtimeProvider` with the app's defaults: unless the app passes `onGap`, a
47
+ * gap revalidates every SWR key tagged with the topic, so the REST API stays
48
+ * the source of truth; issues are captured by `@djangocfg/devtools` (an app's
49
+ * own `onIssue` runs as well). Sits inside `SWRConfig` and `AuthProvider`.
50
+ */
51
+ export function RealtimeMount({ config, apiUrl, children }: RealtimeMountProps) {
52
+ const { mutate } = useSWRConfig();
53
+ const revalidateTopic = useCallback(
54
+ (topic: string) => {
55
+ void mutate((key) => isKeyForTopic(key, topic));
56
+ },
57
+ [mutate],
58
+ );
59
+ const appOnIssue = config.onIssue;
60
+ const onIssue = useCallback(
61
+ (issue: ReportedIssue) => {
62
+ captureIssue(issue);
63
+ appOnIssue?.(issue);
64
+ },
65
+ [appOnIssue],
66
+ );
67
+ return (
68
+ <RealtimeProvider {...config} apiUrl={apiUrl} onGap={config.onGap ?? revalidateTopic} onIssue={onIssue}>
69
+ <RealtimeCidBridge />
70
+ {children}
71
+ </RealtimeProvider>
72
+ );
73
+ }
@@ -0,0 +1,25 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ import { resolveRealtimeApiUrl } from './realtimeApiUrl';
4
+
5
+ afterEach(() => {
6
+ vi.unstubAllEnvs();
7
+ });
8
+
9
+ describe('resolveRealtimeApiUrl', () => {
10
+ it('prefers realtime.apiUrl, then apiUrl, then auth.apiUrl', () => {
11
+ const auth = { apiUrl: 'https://auth.example.com' };
12
+ expect(resolveRealtimeApiUrl({ realtime: { apiUrl: 'https://rt.example.com' }, apiUrl: 'https://a.example.com', auth })).toBe(
13
+ 'https://rt.example.com',
14
+ );
15
+ expect(resolveRealtimeApiUrl({ apiUrl: 'https://a.example.com', auth })).toBe('https://a.example.com');
16
+ expect(resolveRealtimeApiUrl({ auth })).toBe('https://auth.example.com');
17
+ });
18
+
19
+ it('falls back to NEXT_PUBLIC_API_URL, then to nothing', () => {
20
+ vi.stubEnv('NEXT_PUBLIC_API_URL', 'https://env.example.com');
21
+ expect(resolveRealtimeApiUrl({ auth: false, apiUrl: ' ' })).toBe('https://env.example.com');
22
+ vi.stubEnv('NEXT_PUBLIC_API_URL', '');
23
+ expect(resolveRealtimeApiUrl({ auth: false })).toBeUndefined();
24
+ });
25
+ });
@@ -0,0 +1,18 @@
1
+ import type { BaseLayoutProps } from '../../types/layout.types';
2
+
3
+ /**
4
+ * The API origin the realtime socket URL is derived from: `realtime.apiUrl`,
5
+ * else `apiUrl`, else `auth.apiUrl`, else `NEXT_PUBLIC_API_URL`. Undefined when
6
+ * none is set; the client then uses the page's own origin.
7
+ */
8
+ export function resolveRealtimeApiUrl(
9
+ props: Pick<BaseLayoutProps, 'auth' | 'apiUrl' | 'realtime'>,
10
+ ): string | undefined {
11
+ const pick = (v?: string) => (v && v.trim() ? v : undefined);
12
+ return (
13
+ pick(props.realtime === false ? undefined : props.realtime?.apiUrl) ??
14
+ pick(props.apiUrl) ??
15
+ pick(props.auth === false ? undefined : props.auth?.apiUrl) ??
16
+ pick(process.env.NEXT_PUBLIC_API_URL)
17
+ );
18
+ }
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { realtimeIssueEvent } from './realtimeIssueEvent';
4
+
5
+ describe('realtimeIssueEvent', () => {
6
+ it('maps a server fault to an error and a visitor-side close to a warning', () => {
7
+ const fault = realtimeIssueEvent({ kind: 'closed', code: 4500, reason: 'boom', cid: 'c1' }, 'https://x/');
8
+ expect(fault).toEqual({
9
+ event_type: 'ERROR',
10
+ level: 'error',
11
+ message: 'Realtime closed 4500: boom',
12
+ url: 'https://x/',
13
+ extra: { source: 'realtime', kind: 'closed', cid: 'c1', code: 4500, reason: 'boom' },
14
+ });
15
+ expect(realtimeIssueEvent({ kind: 'closed', code: 4401, reason: '', cid: null }).level).toBe('warning');
16
+ expect(realtimeIssueEvent({ kind: 'closed', code: 4403, reason: '', cid: null }).level).toBe('error');
17
+ });
18
+
19
+ it('keeps the message stable per kind and code so devtools can dedupe', () => {
20
+ const a = realtimeIssueEvent({ kind: 'unreachable', attempts: 5, lastCode: 1006, lastReason: 'x', cid: null });
21
+ const b = realtimeIssueEvent({ kind: 'unreachable', attempts: 5, lastCode: 1006, lastReason: 'y', cid: null });
22
+ expect(a.message).toBe(b.message);
23
+ expect(a.level).toBe('warning');
24
+ });
25
+
26
+ it('warns on forbidden, errors on an app bug, and carries the topic', () => {
27
+ const forbidden = realtimeIssueEvent({ kind: 'refused', topic: 'orders:42', code: 'forbidden', cid: 'c1' });
28
+ const unknown = realtimeIssueEvent({ kind: 'refused', topic: 'ordrs:42', code: 'unknown_topic', cid: 'c1' });
29
+ expect(forbidden.level).toBe('warning');
30
+ expect(unknown.level).toBe('error');
31
+ expect(unknown.extra).toMatchObject({ topic: 'ordrs:42', code: 'unknown_topic', cid: 'c1' });
32
+ });
33
+
34
+ it('reports protocol errors and schema failures as errors', () => {
35
+ expect(realtimeIssueEvent({ kind: 'protocol', code: 'rate', detail: null, cid: 'c1' }).level).toBe('error');
36
+ const invalid = realtimeIssueEvent({ kind: 'invalid_event', topic: 'orders:42', message: 'bad', cid: 'c1' });
37
+ expect(invalid.message).toBe('Realtime event on orders:42 does not match its schema');
38
+ expect(invalid.extra).toMatchObject({ topic: 'orders:42', detail: 'bad' });
39
+ });
40
+ });
@@ -0,0 +1,59 @@
1
+ import { EventLevel, EventType } from '@djangocfg/devtools';
2
+
3
+ import type { DevtoolsEvent } from '@djangocfg/devtools';
4
+ import type { ReportedIssue } from '@djangocfg/realtime';
5
+
6
+ /** Close codes that mean the deployment or the server is wrong, not the visitor. */
7
+ const SERVER_FAULT_CODES: ReadonlySet<number> = new Set([4403, 4500, 0]);
8
+
9
+ function describe(issue: ReportedIssue): { message: string; level: DevtoolsEvent['level']; fields: Record<string, unknown> } {
10
+ switch (issue.kind) {
11
+ case 'closed':
12
+ return {
13
+ message: `Realtime closed ${issue.code}${issue.reason ? `: ${issue.reason}` : ''}`,
14
+ level: SERVER_FAULT_CODES.has(issue.code) ? EventLevel.ERROR : EventLevel.WARNING,
15
+ fields: { code: issue.code, reason: issue.reason },
16
+ };
17
+ case 'unreachable':
18
+ return {
19
+ message: `Realtime unreachable: ${issue.attempts} attempts without hello`,
20
+ level: EventLevel.WARNING,
21
+ fields: { attempts: issue.attempts, code: issue.lastCode, reason: issue.lastReason },
22
+ };
23
+ case 'refused':
24
+ return {
25
+ message: `Realtime refused ${issue.topic}: ${issue.code}`,
26
+ // `forbidden` can be a visitor's own rights; an unknown or invalid name is a bug in the app.
27
+ level: issue.code === 'forbidden' ? EventLevel.WARNING : EventLevel.ERROR,
28
+ fields: { topic: issue.topic, code: issue.code },
29
+ };
30
+ case 'protocol':
31
+ return {
32
+ message: `Realtime protocol error: ${issue.code}`,
33
+ level: EventLevel.ERROR,
34
+ fields: { code: issue.code, detail: issue.detail },
35
+ };
36
+ case 'invalid_event':
37
+ return {
38
+ message: `Realtime event on ${issue.topic} does not match its schema`,
39
+ level: EventLevel.ERROR,
40
+ fields: { topic: issue.topic, detail: issue.message },
41
+ };
42
+ }
43
+ }
44
+
45
+ /**
46
+ * A realtime issue as a devtools event: one stable message per kind and code
47
+ * (devtools dedupes on it), the facts in `extra`. The issue never holds a
48
+ * token, so nothing here can leak one.
49
+ */
50
+ export function realtimeIssueEvent(issue: ReportedIssue, url?: string): DevtoolsEvent {
51
+ const { message, level, fields } = describe(issue);
52
+ return {
53
+ event_type: EventType.ERROR,
54
+ level,
55
+ message,
56
+ url,
57
+ extra: { source: 'realtime', kind: issue.kind, cid: issue.cid, ...fields },
58
+ };
59
+ }
@@ -0,0 +1,20 @@
1
+ 'use client';
2
+
3
+ import { useTopicRefresh } from '@djangocfg/realtime/react';
4
+
5
+ import type { Middleware, SWRHook } from 'swr';
6
+
7
+ /**
8
+ * Zero-code refresh: every `useSWR` whose key is tagged with a topic
9
+ * (`['orders:42', …]`, see `isKeyForTopic`) watches that topic while mounted
10
+ * and revalidates on each publication and on a gap, coalesced to one
11
+ * revalidation per ~250 ms. Untagged keys cost nothing.
12
+ */
13
+ export const realtimeRefresh: Middleware = (useSWRNext: SWRHook) =>
14
+ function useRealtimeRefresh(key, fetcher, config) {
15
+ const swr = useSWRNext(key, fetcher, config);
16
+ useTopicRefresh(key, () => {
17
+ void swr.mutate();
18
+ });
19
+ return swr;
20
+ };
@@ -23,6 +23,7 @@ export type NextIntlRouting = object & { __nextIntlRouting?: never };
23
23
  // Import local provider configs
24
24
  import type { ThemeConfig, SWRConfigOptions } from './providers.types';
25
25
  import type { DevtoolsProps } from '@djangocfg/devtools';
26
+ import type { RealtimeConfig } from '@djangocfg/realtime/react';
26
27
 
27
28
  // ============================================================================
28
29
  // Base Layout Props
@@ -80,6 +81,14 @@ export interface BaseLayoutProps {
80
81
  */
81
82
  devtools?: DevtoolsConfig;
82
83
 
84
+ /**
85
+ * Realtime (`@djangocfg/realtime`): one lazy WebSocket per tab for `useTopic`. On by default and free until a
86
+ * component subscribes. The URL defaults to the API origin (`realtime.apiUrl`, `apiUrl`, `auth.apiUrl`, then
87
+ * `NEXT_PUBLIC_API_URL`) plus `/ws`, `wss:` for `https:`. A gap refetches the SWR keys tagged with the topic unless
88
+ * `onGap` is given. `false` turns it off.
89
+ */
90
+ realtime?: RealtimeConfig | false;
91
+
83
92
  /**
84
93
  * Locale-switching plumbing. Mounted into a `LayoutI18nProvider` inside
85
94
  * `BaseApp` — every locale-aware component (footer, navbar, sidebar,