@terpjs/react-core 0.20.0 → 0.21.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@terpjs/react-core",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "type": "module",
5
5
  "description": "Terp React stack core — typed @terpjs/contract client provider, auth session, capability gates, TanStack Router adapter, app shell, page archetypes, DataView and token-styled UI primitives. First frontend stack; see README.md for the component catalog.",
6
6
  "exports": {
@@ -14,7 +14,7 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "@tanstack/react-router": "^1.170.32",
17
- "@terpjs/contract": "^0.20.0"
17
+ "@terpjs/contract": "^0.21.0"
18
18
  },
19
19
  "peerDependencies": {
20
20
  "react": "^19.0.0",
@@ -28,6 +28,12 @@ function LogInOnMount() {
28
28
 
29
29
  describe("RequireAuth", () => {
30
30
  it("shows the fallback while signed out", async () => {
31
+ // A 401 is what a signed-out visitor's browser actually receives: an answer. Letting
32
+ // the fetch fail instead would model a dead backend, which is now a different view.
33
+ vi.stubGlobal(
34
+ "fetch",
35
+ vi.fn<typeof fetch>(async () => new Response("{}", { status: 401 })),
36
+ );
31
37
  render(
32
38
  <TerpProvider baseUrl="https://api.test">
33
39
  <RequireAuth fallback={<span>please-sign-in</span>}>
@@ -1,12 +1,21 @@
1
1
  import type { ReactNode } from "react";
2
2
 
3
+ import { ErrorState } from "./ErrorState";
3
4
  import { useAuth } from "./TerpProvider";
5
+ import { useStrings } from "./uiText";
4
6
 
5
7
  export interface RequireAuthProps {
6
8
  /** Rendered while no user is signed in (e.g. a login view). */
7
9
  fallback: ReactNode;
8
10
  /** Rendered while the provider is checking a persisted session (default: nothing). */
9
11
  pending?: ReactNode;
12
+ /**
13
+ * Rendered when the boot session check got no answer at all — the backend did not
14
+ * respond, or the connection failed. Defaults to a stated failure, never to the
15
+ * login view: offering a sign-in form that cannot possibly succeed sends the reader
16
+ * to check their password for a problem that is not theirs.
17
+ */
18
+ unreachable?: ReactNode;
10
19
  children: ReactNode;
11
20
  }
12
21
 
@@ -14,9 +23,33 @@ export interface RequireAuthProps {
14
23
  * Render `children` only when a user is signed in, otherwise `fallback` (typically a login
15
24
  * view). Pair with the router so the authenticated app mounts only once there is a session;
16
25
  * the backend still enforces authorization on every request.
26
+ *
27
+ * Three states, not two. "Nobody is signed in" and "the server never answered" used to
28
+ * be the same branch, and because a fetch to a dead proxy target hangs instead of
29
+ * failing, the second one rendered `pending` — nothing — for as long as the page was
30
+ * open. A blank screen with an empty console is the least diagnosable failure the stack
31
+ * can produce, so it now says what happened.
17
32
  */
18
- export function RequireAuth({ fallback, pending = null, children }: RequireAuthProps) {
33
+ export function RequireAuth({
34
+ fallback,
35
+ pending = null,
36
+ unreachable,
37
+ children,
38
+ }: RequireAuthProps) {
19
39
  const auth = useAuth();
40
+ const strings = useStrings();
20
41
  if (auth.loading()) return <>{pending}</>;
42
+ if (auth.unreachable()) {
43
+ return (
44
+ <>
45
+ {unreachable ?? (
46
+ <ErrorState
47
+ title={strings.backendUnreachableTitle}
48
+ description={strings.backendUnreachableDescription}
49
+ />
50
+ )}
51
+ </>
52
+ );
53
+ }
21
54
  return <>{auth.currentUser() !== null ? children : fallback}</>;
22
55
  }
@@ -0,0 +1,137 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, render, screen, waitFor } from "@testing-library/react";
3
+ import { afterEach, describe, expect, it, vi } from "vitest";
4
+
5
+ import { RequireAuth } from "./RequireAuth";
6
+ import { BOOT_REQUEST_TIMEOUT_MS, TerpProvider } from "./TerpProvider";
7
+
8
+ afterEach(() => {
9
+ cleanup();
10
+ vi.restoreAllMocks();
11
+ });
12
+
13
+ /**
14
+ * A dead backend used to be indistinguishable from a signed-out visitor, and worse
15
+ * than that: a fetch to a dead proxy target does not fail, it hangs, so the boot
16
+ * refresh never settled, `loading` stayed true and `RequireAuth` rendered its `pending`
17
+ * slot — nothing — for as long as the page stayed open. An empty `#root`, three console
18
+ * messages, zero errors, zero warnings.
19
+ */
20
+ describe("a backend that does not answer the boot check", () => {
21
+ it("gives the boot request a deadline, so a hang becomes a failure", async () => {
22
+ // The mechanism, pinned at the wiring: without a signal there is nothing to make a
23
+ // hanging fetch settle, and every assertion below depends on it settling.
24
+ const timeout = vi.spyOn(AbortSignal, "timeout");
25
+ vi.stubGlobal(
26
+ "fetch",
27
+ vi.fn<typeof fetch>(async () => new Response("{}", { status: 401 })),
28
+ );
29
+
30
+ render(
31
+ <TerpProvider baseUrl="https://api.test">
32
+ <RequireAuth fallback={<span>please-sign-in</span>}>
33
+ <span>app</span>
34
+ </RequireAuth>
35
+ </TerpProvider>,
36
+ );
37
+
38
+ await waitFor(() => expect(screen.getByText("please-sign-in")).toBeInTheDocument());
39
+ expect(timeout).toHaveBeenCalledWith(BOOT_REQUEST_TIMEOUT_MS);
40
+ expect(BOOT_REQUEST_TIMEOUT_MS).toBeGreaterThan(0);
41
+ });
42
+
43
+ it("says so on the screen instead of offering a sign-in that cannot work", async () => {
44
+ // A rejected fetch is what an aborted one produces, and what a refused connection
45
+ // produces: no answer came back at all.
46
+ vi.stubGlobal(
47
+ "fetch",
48
+ vi.fn<typeof fetch>(async () => {
49
+ throw new TypeError("Failed to fetch");
50
+ }),
51
+ );
52
+ vi.spyOn(console, "warn").mockImplementation(() => {});
53
+
54
+ render(
55
+ <TerpProvider baseUrl="https://api.test">
56
+ <RequireAuth fallback={<span>please-sign-in</span>}>
57
+ <span>app</span>
58
+ </RequireAuth>
59
+ </TerpProvider>,
60
+ );
61
+
62
+ await waitFor(() =>
63
+ expect(screen.getByText(/cannot reach its server/i)).toBeInTheDocument(),
64
+ );
65
+ // Not the login view: a sign-in form that cannot possibly succeed sends the reader
66
+ // to check their own password for a problem that is not theirs.
67
+ expect(screen.queryByText("please-sign-in")).not.toBeInTheDocument();
68
+ expect(screen.queryByText("app")).not.toBeInTheDocument();
69
+ });
70
+
71
+ it("is loud in the console too, naming the API it could not reach", async () => {
72
+ vi.stubGlobal(
73
+ "fetch",
74
+ vi.fn<typeof fetch>(async () => {
75
+ throw new TypeError("Failed to fetch");
76
+ }),
77
+ );
78
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
79
+
80
+ render(
81
+ <TerpProvider baseUrl="https://api.test">
82
+ <RequireAuth fallback={<span>please-sign-in</span>}>
83
+ <span>app</span>
84
+ </RequireAuth>
85
+ </TerpProvider>,
86
+ );
87
+
88
+ await waitFor(() => expect(warn).toHaveBeenCalled());
89
+ const message = warn.mock.calls.map((call) => String(call[0])).join("\n");
90
+ expect(message).toContain("https://api.test");
91
+ expect(message).toContain("did not answer");
92
+ });
93
+
94
+ it("renders a caller's own unreachable view when it has one", async () => {
95
+ vi.stubGlobal(
96
+ "fetch",
97
+ vi.fn<typeof fetch>(async () => {
98
+ throw new TypeError("Failed to fetch");
99
+ }),
100
+ );
101
+ vi.spyOn(console, "warn").mockImplementation(() => {});
102
+
103
+ render(
104
+ <TerpProvider baseUrl="https://api.test">
105
+ <RequireAuth
106
+ fallback={<span>please-sign-in</span>}
107
+ unreachable={<span>our-own-message</span>}
108
+ >
109
+ <span>app</span>
110
+ </RequireAuth>
111
+ </TerpProvider>,
112
+ );
113
+
114
+ await waitFor(() => expect(screen.getByText("our-own-message")).toBeInTheDocument());
115
+ });
116
+
117
+ it("keeps 'nobody is signed in' a separate answer from 'nobody answered'", async () => {
118
+ // The distinction the old code could not make. A 401 IS an answer, so this must
119
+ // render the login view and never the failure — an assertion that only checked for
120
+ // the failure's absence would pass on a provider that showed nothing at all.
121
+ vi.stubGlobal(
122
+ "fetch",
123
+ vi.fn<typeof fetch>(async () => new Response("{}", { status: 401 })),
124
+ );
125
+
126
+ render(
127
+ <TerpProvider baseUrl="https://api.test">
128
+ <RequireAuth fallback={<span>please-sign-in</span>}>
129
+ <span>app</span>
130
+ </RequireAuth>
131
+ </TerpProvider>,
132
+ );
133
+
134
+ await waitFor(() => expect(screen.getByText("please-sign-in")).toBeInTheDocument());
135
+ expect(screen.queryByText(/cannot reach its server/i)).not.toBeInTheDocument();
136
+ });
137
+ });
@@ -70,8 +70,34 @@ export interface TerpProviderProps {
70
70
  children: ReactNode;
71
71
  }
72
72
 
73
+ /**
74
+ * How long the boot session check waits for an answer before giving up.
75
+ *
76
+ * Loud on purpose, and the reason this number exists at all: a fetch to a dead proxy
77
+ * target does not fail, it *hangs*. The boot refresh therefore never settled, `loading`
78
+ * stayed true for the lifetime of the page, and `RequireAuth` rendered its `pending`
79
+ * slot — nothing, by default. The symptom was an empty `#root` with three console
80
+ * messages, zero errors and zero warnings: the single least diagnosable failure in the
81
+ * stack, for the most ordinary cause there is.
82
+ *
83
+ * Boot only, deliberately not a client-wide default. A file upload through the files
84
+ * capability legitimately runs longer than any timeout that would help here, so a
85
+ * blanket one would abort correct work to fix a diagnosis problem.
86
+ */
87
+ export const BOOT_REQUEST_TIMEOUT_MS = 10_000;
88
+
89
+ /** An abort signal for one boot request, or undefined where the runtime has none. */
90
+ function bootTimeout(): AbortSignal | undefined {
91
+ // Guarded rather than assumed: this also runs under a test renderer and in SSR, and a
92
+ // missing AbortSignal.timeout must degrade to the old behaviour rather than throw
93
+ // during boot -- which would be a worse failure than the one being fixed.
94
+ return typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function"
95
+ ? AbortSignal.timeout(BOOT_REQUEST_TIMEOUT_MS)
96
+ : undefined;
97
+ }
98
+
73
99
  async function loadCurrentUser(client: TerpClient): Promise<CurrentUser> {
74
- const { data, error } = await client.GET("/api/v1/me/", {});
100
+ const { data, error } = await client.GET("/api/v1/me/", { signal: bootTimeout() });
75
101
  if (error || !data) {
76
102
  throw new Error("failed to load the current user");
77
103
  }
@@ -95,6 +121,11 @@ export function TerpProvider({
95
121
  const [user, setUser] = useState<CurrentUser | null>(null);
96
122
  const [loading, setLoading] = useState(true);
97
123
  const [ssoError, setSsoError] = useState<unknown>(null);
124
+ const [unreachable, setUnreachable] = useState(false);
125
+ // Set by the refresh attempt, read by the boot effect. A rejected fetch means no
126
+ // answer came back at all; a resolved one carrying `error` means the backend
127
+ // answered "no session", which is a completely different thing to tell the reader.
128
+ const noAnswerRef = useRef(false);
98
129
 
99
130
  // Captured once per provider lifetime (before the URL is cleaned), so a StrictMode
100
131
  // double boot effect cannot replay the single-use OIDC state against the backend.
@@ -129,15 +160,21 @@ export function TerpProvider({
129
160
  const existing = refreshInFlightRef.current;
130
161
  if (existing) return existing;
131
162
  const attempt = refreshClient
132
- .POST("/api/v1/auth/refresh", {})
163
+ .POST("/api/v1/auth/refresh", { signal: bootTimeout() })
133
164
  .then(({ data, error }) => {
165
+ // An answer arrived, whatever it said: the backend is reachable.
166
+ noAnswerRef.current = false;
134
167
  if (error || !data) {
135
168
  return null;
136
169
  }
137
170
  tokenRef.current = data.access_token;
138
171
  return data.access_token;
139
172
  })
140
- .catch(() => null)
173
+ .catch(() => {
174
+ // No answer: a refused connection, a dead proxy target, or the timeout above.
175
+ noAnswerRef.current = true;
176
+ return null;
177
+ })
141
178
  .finally(() => {
142
179
  refreshInFlightRef.current = null;
143
180
  });
@@ -166,6 +203,7 @@ export function TerpProvider({
166
203
  }
167
204
  tokenRef.current = data.access_token;
168
205
  const me = await loadCurrentUser(client);
206
+ setUnreachable(false);
169
207
  setUser(me);
170
208
  return me;
171
209
  },
@@ -233,6 +271,18 @@ export function TerpProvider({
233
271
  return;
234
272
  }
235
273
  await refresh();
274
+ if (noAnswerRef.current) {
275
+ // The console half of the same message. The screen tells whoever is looking at
276
+ // the app; this tells whoever has devtools open, which for this failure is the
277
+ // person most likely to be looking for it.
278
+ console.warn(
279
+ `[terp] the API at ${baseUrl} did not answer the boot session check within ` +
280
+ `${BOOT_REQUEST_TIMEOUT_MS}ms. Is the backend running, and is the dev ` +
281
+ "server's proxy target pointing at it? Nothing else will render until it " +
282
+ "answers.",
283
+ );
284
+ setUnreachable(true);
285
+ }
236
286
  };
237
287
  void boot().finally(() => {
238
288
  if (!cancelled) setLoading(false);
@@ -240,7 +290,7 @@ export function TerpProvider({
240
290
  return () => {
241
291
  cancelled = true;
242
292
  };
243
- }, [completePendingSso, refresh]);
293
+ }, [baseUrl, completePendingSso, refresh]);
244
294
 
245
295
  const auth = useMemo<AuthSession>(
246
296
  () => ({
@@ -249,6 +299,7 @@ export function TerpProvider({
249
299
  refresh,
250
300
  currentUser: () => user,
251
301
  loading: () => loading,
302
+ unreachable: () => unreachable,
252
303
  // `module` names the module the action happens in, so a per-module rung can raise the
253
304
  // answer. Omitted, the gate is the global rank exactly as before — which is the honest
254
305
  // default for a screen that is not a module's own, and keeps every existing caller
@@ -263,7 +314,7 @@ export function TerpProvider({
263
314
  )
264
315
  : false,
265
316
  }),
266
- [login, logout, refresh, user, loading, thresholds],
317
+ [login, logout, refresh, user, loading, unreachable, thresholds],
267
318
  );
268
319
 
269
320
  const beginSso = useCallback(
@@ -1,13 +1,26 @@
1
1
  // @vitest-environment jsdom
2
2
  import { cleanup, screen, waitFor } from "@testing-library/react";
3
- import { afterEach, describe, expect, it } from "vitest";
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
4
  import { defineModuleManifest } from "@terpjs/contract";
5
5
 
6
6
  import { collectModules, renderTerpApp } from "./bootstrap";
7
7
  import { useErrorMessage } from "./errorMessages";
8
8
 
9
+ // A signed-out visitor's browser gets a 401 from the boot session check — an ANSWER.
10
+ // These tests used to model "signed out" by letting the fetch fail outright, which is
11
+ // the same state a dead backend produces, and the provider now tells those two apart:
12
+ // no answer at all renders the unreachable view rather than a login form that cannot
13
+ // work. So the fixture says what it means.
14
+ beforeEach(() => {
15
+ vi.stubGlobal(
16
+ "fetch",
17
+ vi.fn<typeof fetch>(async () => new Response("{}", { status: 401 })),
18
+ );
19
+ });
20
+
9
21
  afterEach(() => {
10
22
  cleanup();
23
+ vi.restoreAllMocks();
11
24
  });
12
25
 
13
26
  const notesModule = {
@@ -56,6 +69,7 @@ describe("renderTerpApp", () => {
56
69
 
57
70
  renderTerpApp({
58
71
  title: "Test",
72
+ baseUrl: "https://api.test",
59
73
  modules: { "./modules/notes/module.tsx": notesModule },
60
74
  rootElement: root,
61
75
  });
@@ -93,6 +107,7 @@ describe("renderTerpApp", () => {
93
107
 
94
108
  renderTerpApp({
95
109
  title: "Test",
110
+ baseUrl: "https://api.test",
96
111
  modules: { "./modules/notes/module.tsx": notesModule },
97
112
  rootElement: root,
98
113
  login: <ShowsAnError />,
package/src/locale.tsx CHANGED
@@ -192,6 +192,10 @@ export const LOCALE_NL: LocaleCatalog = {
192
192
  moduleNavigationLabel: "Modulenavigatie",
193
193
  moreActions: "Meer acties",
194
194
  errorTitle: "Er is iets misgegaan.",
195
+ backendUnreachableTitle: "De applicatie kan de server niet bereiken.",
196
+ backendUnreachableDescription:
197
+ "Er kwam geen antwoord van de API. Mogelijk start deze nog op, of staat "
198
+ + "hij uit. Vernieuw de pagina zodra hij draait.",
195
199
  confirm: "Bevestigen",
196
200
  cancel: "Annuleren",
197
201
  successTitle: "Gelukt",
package/src/uiText.tsx CHANGED
@@ -98,6 +98,10 @@ export interface TerpStrings {
98
98
  moreActions: string;
99
99
  /** Default {@link ErrorState} title. */
100
100
  errorTitle: string;
101
+ /** Title shown by `RequireAuth` when the backend did not answer the boot check. */
102
+ backendUnreachableTitle: string;
103
+ /** Explanation shown with {@link TerpStrings.backendUnreachableTitle}. */
104
+ backendUnreachableDescription: string;
101
105
  /** Default confirm-button label of {@link ConfirmDialog}. */
102
106
  confirm: string;
103
107
  /** Default cancel-button label of {@link ConfirmDialog}. */
@@ -333,6 +337,10 @@ export const DEFAULT_STRINGS: TerpStrings = {
333
337
  moduleNavigationLabel: "Module navigation",
334
338
  moreActions: "More actions",
335
339
  errorTitle: "Something went wrong.",
340
+ backendUnreachableTitle: "The application cannot reach its server.",
341
+ backendUnreachableDescription:
342
+ "No answer came back from the API. It may still be starting, or stopped. "
343
+ + "Reload once it is running.",
336
344
  confirm: "Confirm",
337
345
  cancel: "Cancel",
338
346
  successTitle: "Success",