@micha.bigler/ui-core-micha 4.13.0 → 4.15.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.15.0 - UCM-PERF-4
4
+
5
+ Opt-in `AuthProvider` prop `bootstrap` (`true` for `/api/bootstrap/`, or a same-origin path; requires
6
+ `django-core-micha` >= 3.17.0): the app shell starts from one bootstrap request instead of CSRF, `users/current`,
7
+ `auth-methods`, feed and unread count; `NotificationsProvider` takes its initial feed and count from it once for the same
8
+ person and still opens the WebSocket only after that. Any bootstrap failure falls back to the separate start requests
9
+ exactly once. New hook `useBootstrapExtension(name)` for dcm bootstrap provider payloads. Without the prop nothing
10
+ changes.
11
+
12
+ ## 4.14.0 - UCM-PERF-5
13
+
14
+ New `installChunkLoadRecovery({ guardWindowMs?, reload? })` and `isChunkLoadError(error)`. Installed once at app
15
+ startup, a failed chunk load after a deploy (Vite `vite:preloadError` or an unhandled dynamic-import rejection whose
16
+ error is a fetch failure) reloads the page once; a repeat within the guard window (default 60 s, held in
17
+ `sessionStorage` across the reload) does not, and without usable storage nothing reloads. Module evaluation errors and
18
+ all other errors are left alone. Additive; nothing changes for apps that do not install it.
19
+
3
20
  ## 4.13.0 - UCM-AUTH-14
4
21
 
5
22
  Composable account and profile steps for a page-based setup wizard; all additive. New exports: `SetupWizardShell`
package/README.md CHANGED
@@ -86,6 +86,32 @@ const setupBillingApi = createBillingApi({
86
86
  <PlanPicker api={setupBillingApi} plans={plans} />;
87
87
  ```
88
88
 
89
+ ## Start from one bootstrap request (opt-in)
90
+
91
+ With `django-core-micha` >= 3.17.0, `<AuthProvider bootstrap>` starts from `GET /api/bootstrap/` (or pass a same-origin
92
+ path instead of `true`): one request instead of CSRF, `users/current` + `auth-methods`, then the notification feed and
93
+ unread count. User, auth methods and the initial notifications end up as from the separate requests, `loading` ends at
94
+ the same point, and the notification WebSocket still connects only after that state is in place. If the bootstrap fails
95
+ in any way (a part failure, 501, 404, network), the provider runs today's separate start requests once. App start data
96
+ registered as dcm bootstrap providers is read with `useBootstrapExtension('application_access')` (`undefined` when
97
+ absent, `null`, the opt-in is off or the bootstrap failed). Without the prop nothing changes.
98
+
99
+ ## Stale chunks after a deploy
100
+
101
+ An app that lazy-loads code calls `installChunkLoadRecovery()` once at startup (before rendering). When a deploy has
102
+ removed a chunk that an open page still asks for ("Failed to fetch dynamically imported module", Vite's
103
+ `vite:preloadError`, "Unable to preload CSS"), the page reloads once onto the new build. A second chunk failure within
104
+ 60 seconds of that reload is left alone and surfaces as today, so a genuinely broken deploy cannot loop; a later failure
105
+ reloads again. Without usable `sessionStorage` it never reloads. Other errors are untouched; `isChunkLoadError(error)`
106
+ lets an error boundary tell the cases apart. Option `guardWindowMs` changes the window; the function returns an
107
+ uninstall. A reload loses unsaved input, so do not lazy-load routes where people type before the chunk is needed.
108
+
109
+ ```js
110
+ import { installChunkLoadRecovery } from '@micha.bigler/ui-core-micha';
111
+
112
+ installChunkLoadRecovery();
113
+ ```
114
+
89
115
  ## Consumer integration check
90
116
 
91
117
  ```js
@@ -1,8 +1,8 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  // src/auth/AuthContext.jsx
3
- import React, { createContext, useState, useEffect, } from 'react';
3
+ import React, { createContext, useState, useEffect, useCallback, } from 'react';
4
4
  import { ensureCsrfToken } from './apiClient'; // <--- IMPORT ADDED
5
- import { fetchAuthMethods, fetchCurrentUser, logoutSession, } from './authApi';
5
+ import { fetchAuthMethods, fetchCurrentUser, fetchBootstrap, logoutSession, } from './authApi';
6
6
  import { ReauthModal } from './ReauthModal';
7
7
  export const AuthContext = createContext(null);
8
8
  const DEFAULT_AUTH_METHODS = {
@@ -23,10 +23,15 @@ const DEFAULT_AUTH_METHODS = {
23
23
  two_factor_required: false,
24
24
  qr_signup_enabled: false,
25
25
  };
26
- export const AuthProvider = ({ children }) => {
26
+ export const AuthProvider = ({ children, bootstrap = false }) => {
27
27
  const [user, setUser] = useState(null);
28
28
  const [authMethods, setAuthMethods] = useState(DEFAULT_AUTH_METHODS);
29
29
  const [loading, setLoading] = useState(true);
30
+ const [notificationSeed, setNotificationSeed] = useState(null);
31
+ const [bootstrapExtensions, setBootstrapExtensions] = useState({});
32
+ const consumeBootstrapNotificationSeed = useCallback(() => {
33
+ setNotificationSeed(null);
34
+ }, []);
30
35
  const mapUserFromApi = (data) => {
31
36
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
32
37
  const profile = (data === null || data === void 0 ? void 0 : data.profile) || {};
@@ -34,7 +39,7 @@ export const AuthProvider = ({ children }) => {
34
39
  };
35
40
  useEffect(() => {
36
41
  let isMounted = true;
37
- const initAuth = async () => {
42
+ const initSeparateAuth = async () => {
38
43
  try {
39
44
  // 1) Ensure CSRF cookie exists using the specific client
40
45
  await ensureCsrfToken();
@@ -70,11 +75,49 @@ export const AuthProvider = ({ children }) => {
70
75
  setLoading(false);
71
76
  }
72
77
  };
78
+ const initAuth = async () => {
79
+ if (!bootstrap) {
80
+ await initSeparateAuth();
81
+ return;
82
+ }
83
+ try {
84
+ const data = await fetchBootstrap(bootstrap === true ? '/api/bootstrap/' : bootstrap);
85
+ if (!isMounted)
86
+ return;
87
+ const mappedUser = (data === null || data === void 0 ? void 0 : data.user) ? mapUserFromApi(data.user) : null;
88
+ const methods = data === null || data === void 0 ? void 0 : data.auth_methods;
89
+ if (methods && typeof methods === 'object') {
90
+ setAuthMethods((prev) => (Object.assign(Object.assign({}, prev), methods)));
91
+ }
92
+ setUser(mappedUser);
93
+ setBootstrapExtensions((data === null || data === void 0 ? void 0 : data.extensions) && typeof data.extensions === 'object'
94
+ ? data.extensions : {});
95
+ setNotificationSeed(mappedUser && (data === null || data === void 0 ? void 0 : data.notifications)
96
+ ? { userId: mappedUser.id, notifications: data.notifications }
97
+ : null);
98
+ setLoading(false);
99
+ }
100
+ catch (error) {
101
+ if (isMounted) {
102
+ setBootstrapExtensions({});
103
+ setNotificationSeed(null);
104
+ await initSeparateAuth();
105
+ }
106
+ }
107
+ };
73
108
  initAuth();
74
109
  return () => { isMounted = false; };
75
- }, []);
110
+ }, [bootstrap]);
111
+ // Bootstrap data belongs to the person it was loaded for; drop it when the session changes hands.
112
+ const clearBootstrapData = () => {
113
+ setBootstrapExtensions({});
114
+ setNotificationSeed(null);
115
+ };
76
116
  const login = (userData) => {
77
- setUser((prev) => (Object.assign(Object.assign({}, prev), mapUserFromApi(userData))));
117
+ const mapped = mapUserFromApi(userData);
118
+ if (user && mapped.id !== user.id)
119
+ clearBootstrapData();
120
+ setUser((prev) => (Object.assign(Object.assign({}, prev), mapped)));
78
121
  };
79
122
  const refreshUser = async () => {
80
123
  const data = await fetchCurrentUser();
@@ -90,6 +133,7 @@ export const AuthProvider = ({ children }) => {
90
133
  console.error('Error during logout:', error);
91
134
  }
92
135
  finally {
136
+ clearBootstrapData();
93
137
  setUser(null);
94
138
  }
95
139
  };
@@ -100,5 +144,14 @@ export const AuthProvider = ({ children }) => {
100
144
  login,
101
145
  logout,
102
146
  refreshUser,
147
+ bootstrapNotificationSeed: notificationSeed,
148
+ consumeBootstrapNotificationSeed,
149
+ bootstrapExtensions,
103
150
  }, children: [children, _jsx(ReauthModal, {})] }));
104
151
  };
152
+ export function useBootstrapExtension(name) {
153
+ var _a;
154
+ const context = React.useContext(AuthContext);
155
+ const payload = (_a = context === null || context === void 0 ? void 0 : context.bootstrapExtensions) === null || _a === void 0 ? void 0 : _a[name];
156
+ return payload == null ? undefined : payload;
157
+ }
@@ -20,6 +20,10 @@ export async function fetchCurrentUser() {
20
20
  });
21
21
  return res.data;
22
22
  }
23
+ export async function fetchBootstrap(url) {
24
+ const res = await apiClient.get(url, { skipAuthRedirect: true });
25
+ return res.data;
26
+ }
23
27
  export async function fetchAuthMethods() {
24
28
  const res = await apiClient.get('/api/auth-methods/');
25
29
  return res.data || {};
package/dist/index.js CHANGED
@@ -8,8 +8,9 @@ import './theme/fonts';
8
8
  export { createAppTheme, assertThemeComplete, assertKitSxDisjoint, calculateContrastRatio, KIT_COMPONENT_SX_REGISTRY, reportOffPaletteColours, reportKitSxBypasses, reportRedundantThemeValues, reportThemeAdoption, THEME_COMPLETENESS_SURFACES, } from './theme';
9
9
  // --- 0.1 Consumer integration ---
10
10
  export { checkKitIntegration } from './testing/checkKitIntegration';
11
+ export { installChunkLoadRecovery, isChunkLoadError } from './utils/chunkLoadRecovery';
11
12
  // --- 1. Auth Context (Essentiell für den Wrapper) ---
12
- export { AuthContext, AuthProvider } from './auth/AuthContext';
13
+ export { AuthContext, AuthProvider, useBootstrapExtension } from './auth/AuthContext';
13
14
  export { UserMenu } from './auth/UserMenu';
14
15
  export { default as apiClient, ensureCsrfToken, addPublicPath, removePublicPath, } from "./auth/apiClient";
15
16
  // --- 2. API & Services (Neue Struktur) ---
@@ -39,6 +39,8 @@ function patchStatus(notification, status) {
39
39
  export function NotificationsProvider({ children, wsUrlBase }) {
40
40
  const auth = useContext(AuthContext);
41
41
  const authenticated = Boolean(auth === null || auth === void 0 ? void 0 : auth.user);
42
+ const bootstrapSeed = auth === null || auth === void 0 ? void 0 : auth.bootstrapNotificationSeed;
43
+ const consumeBootstrapSeed = auth === null || auth === void 0 ? void 0 : auth.consumeBootstrapNotificationSeed;
42
44
  const [notifications, setNotifications] = useState([]);
43
45
  const [unreadCount, setUnreadCount] = useState(0);
44
46
  const notificationsRef = useRef([]);
@@ -113,12 +115,24 @@ export function NotificationsProvider({ children, wsUrlBase }) {
113
115
  return subscribe(DEFAULT_ENVELOPE, handleRealtimeMessage);
114
116
  }, [authenticated, subscribe, handleRealtimeMessage]);
115
117
  useEffect(() => {
118
+ var _a, _b, _c;
116
119
  if (!authenticated) {
117
120
  replaceNotifications([]);
118
121
  setUnreadCount(0);
119
122
  setSeeded(false);
120
123
  return undefined;
121
124
  }
125
+ if (bootstrapSeed && bootstrapSeed.userId === ((_a = auth === null || auth === void 0 ? void 0 : auth.user) === null || _a === void 0 ? void 0 : _a.id)) {
126
+ const feed = (_b = bootstrapSeed.notifications) === null || _b === void 0 ? void 0 : _b.feed;
127
+ const unread = (_c = bootstrapSeed.notifications) === null || _c === void 0 ? void 0 : _c.unread_count;
128
+ const nextNotifications = ((feed === null || feed === void 0 ? void 0 : feed.results) || []).map(normalizeNotification);
129
+ notificationsRef.current = nextNotifications;
130
+ setNotifications(nextNotifications);
131
+ setUnreadCount((unread === null || unread === void 0 ? void 0 : unread.count) || 0);
132
+ setSeeded(true);
133
+ consumeBootstrapSeed === null || consumeBootstrapSeed === void 0 ? void 0 : consumeBootstrapSeed();
134
+ return undefined;
135
+ }
122
136
  let cancelled = false;
123
137
  refresh()
124
138
  .catch(() => {
@@ -131,7 +145,9 @@ export function NotificationsProvider({ children, wsUrlBase }) {
131
145
  return () => {
132
146
  cancelled = true;
133
147
  };
134
- }, [authenticated, refresh, replaceNotifications]);
148
+ // The seed and the user id are read when the provider becomes authenticated; adding the user id as
149
+ // a dependency would refetch on a user switch without logout, which is not today's behaviour.
150
+ }, [authenticated, refresh, replaceNotifications, consumeBootstrapSeed]);
135
151
  const mark = useCallback((action, ids) => {
136
152
  const selectedIds = Array.isArray(ids) ? ids : [];
137
153
  const selected = new Set(selectedIds);
@@ -0,0 +1,65 @@
1
+ const LAST_RELOAD_KEY = 'ucm:chunk-load-recovery:last-reload';
2
+ const DEFAULT_GUARD_WINDOW_MS = 60000;
3
+ let activeInstallation = null;
4
+ /**
5
+ * Returns whether an error indicates that a JavaScript or CSS module chunk could not be fetched.
6
+ * Errors thrown while evaluating a successfully fetched module do not count.
7
+ */
8
+ export function isChunkLoadError(error) {
9
+ if (!error || (typeof error !== 'object' && typeof error !== 'function'))
10
+ return false;
11
+ if (error.name === 'ChunkLoadError')
12
+ return true;
13
+ if (typeof error.message !== 'string')
14
+ return false;
15
+ return /failed to fetch dynamically imported module|error loading dynamically imported module|importing a module script failed|unable to preload css/i.test(error.message);
16
+ }
17
+ /**
18
+ * Installs one-shot recovery for failed Vite or unhandled dynamic module loads.
19
+ * The session storage guard defaults to 60 seconds and survives a page reload; storage failures
20
+ * leave the error untouched. Options accept `guardWindowMs` and an injected `reload` function.
21
+ * Returns an uninstall function, or a no-op when called without `window`.
22
+ */
23
+ export function installChunkLoadRecovery({ guardWindowMs = DEFAULT_GUARD_WINDOW_MS, reload = () => window.location.reload() } = {}) {
24
+ if (typeof window === 'undefined')
25
+ return () => { };
26
+ if (activeInstallation)
27
+ return activeInstallation.uninstall;
28
+ // A zero, negative or non-numeric window would disable the loop guard; use the default instead.
29
+ const windowMs = Number.isFinite(guardWindowMs) && guardWindowMs > 0 ? guardWindowMs : DEFAULT_GUARD_WINDOW_MS;
30
+ const tryRecover = (error, event) => {
31
+ if (!isChunkLoadError(error))
32
+ return;
33
+ let storage;
34
+ try {
35
+ storage = window.sessionStorage;
36
+ const previousValue = storage.getItem(LAST_RELOAD_KEY);
37
+ const previousReload = Number(previousValue);
38
+ const now = Date.now();
39
+ if (previousValue !== null && Number.isFinite(previousReload) && now - previousReload < windowMs)
40
+ return;
41
+ const storedTime = String(now);
42
+ storage.setItem(LAST_RELOAD_KEY, storedTime);
43
+ if (storage.getItem(LAST_RELOAD_KEY) !== storedTime)
44
+ return;
45
+ }
46
+ catch (_a) {
47
+ return;
48
+ }
49
+ event === null || event === void 0 ? void 0 : event.preventDefault();
50
+ reload();
51
+ };
52
+ const onVitePreloadError = (event) => tryRecover(event.payload, event);
53
+ const onUnhandledRejection = (event) => tryRecover(event.reason, event);
54
+ window.addEventListener('vite:preloadError', onVitePreloadError);
55
+ window.addEventListener('unhandledrejection', onUnhandledRejection);
56
+ const uninstall = () => {
57
+ if ((activeInstallation === null || activeInstallation === void 0 ? void 0 : activeInstallation.uninstall) !== uninstall)
58
+ return;
59
+ window.removeEventListener('vite:preloadError', onVitePreloadError);
60
+ window.removeEventListener('unhandledrejection', onUnhandledRejection);
61
+ activeInstallation = null;
62
+ };
63
+ activeInstallation = { uninstall };
64
+ return uninstall;
65
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@micha.bigler/ui-core-micha",
3
- "version": "4.13.0",
3
+ "version": "4.15.0",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.js",
6
6
  "exports": {