@djangocfg/layouts 2.1.660 → 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.660",
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.660",
95
- "@djangocfg/api": "^2.1.660",
96
- "@djangocfg/devtools": "^2.1.660",
97
- "@djangocfg/i18n": "^2.1.660",
98
- "@djangocfg/ui-core": "^2.1.660",
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.660",
127
- "@djangocfg/api": "^2.1.660",
128
- "@djangocfg/devtools": "^2.1.660",
129
- "@djangocfg/i18n": "^2.1.660",
130
- "@djangocfg/typescript-config": "^2.1.660",
131
- "@djangocfg/ui-core": "^2.1.660",
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"
@@ -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)
@@ -67,6 +68,9 @@ import { LocaleSuggestion } from '../../components/LocaleSuggestion';
67
68
  import { ProjectNameProvider } from '../../shared/ProjectContext';
68
69
  import { PwaManifestCheck, PwaMetaGuard } from './pwaMeta';
69
70
  import { resolveDevtoolsBaseUrl } from './devtoolsBaseUrl';
71
+ import { RealtimeMount } from './realtime/RealtimeMount';
72
+ import { realtimeRefresh } from './realtime/realtimeRefresh';
73
+ import { resolveRealtimeApiUrl } from './realtime/realtimeApiUrl';
70
74
 
71
75
  import React from 'react';
72
76
 
@@ -92,6 +96,26 @@ function ScrollToTop() {
92
96
  return null;
93
97
  }
94
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
+
95
119
  /**
96
120
  * BaseApp - Core providers wrapper for any React/Next.js app
97
121
  *
@@ -113,6 +137,7 @@ export function BaseApp({
113
137
  i18n,
114
138
  pwaMeta = true,
115
139
  progressBar = true,
140
+ realtime = {},
116
141
  debug,
117
142
  }: BaseAppProps) {
118
143
  // auth=false disables AuthProvider entirely (public apps with no login)
@@ -131,6 +156,8 @@ export function BaseApp({
131
156
  baseUrl: resolveDevtoolsBaseUrl({ auth, apiUrl, devtools: devtoolsConfig }),
132
157
  };
133
158
 
159
+ const realtimeApiUrl = resolveRealtimeApiUrl({ auth, apiUrl, realtime });
160
+
134
161
  const content = (
135
162
  <>
136
163
  {pwaMeta && <PwaMetaGuard />}
@@ -176,9 +203,11 @@ export function BaseApp({
176
203
  revalidateOnFocus: swr?.revalidateOnFocus ?? true,
177
204
  revalidateOnReconnect: swr?.revalidateOnReconnect ?? true,
178
205
  dedupingInterval: swr?.dedupingInterval ?? 2000,
206
+ use: realtime === false ? undefined : REALTIME_SWR_MIDDLEWARE,
179
207
  }}
180
208
  >
181
209
  <AuthProvider config={authEnabled ? authConfig : undefined} enabled={authEnabled}>
210
+ <OptionalRealtime config={realtime} apiUrl={realtimeApiUrl}>
182
211
  <AnalyticsProvider trackingId={analytics?.googleTrackingId}>
183
212
  <ErrorTrackingProvider
184
213
  validation={errorTracking?.validation}
@@ -203,6 +232,7 @@ export function BaseApp({
203
232
  {authEnabled && <AuthDialog authPath={authConfig?.routes?.auth} />}
204
233
  </ErrorTrackingProvider>
205
234
  </AnalyticsProvider>
235
+ </OptionalRealtime>
206
236
  </AuthProvider>
207
237
  </SWRConfig>
208
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,