@terpjs/react-core 0.19.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.19.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,24 +14,24 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "@tanstack/react-router": "^1.170.32",
17
- "@terpjs/contract": "^0.19.0"
17
+ "@terpjs/contract": "^0.21.0"
18
18
  },
19
19
  "peerDependencies": {
20
20
  "react": "^19.0.0",
21
21
  "react-dom": "^19.0.0"
22
22
  },
23
23
  "devDependencies": {
24
- "@testing-library/jest-dom": "^6.9.1",
24
+ "@testing-library/jest-dom": "^7.0.1",
25
25
  "@testing-library/react": "^16.3.3",
26
26
  "@types/react": "^19.2.18",
27
27
  "@types/react-dom": "^19.2.7",
28
28
  "@vitejs/plugin-react": "^6.1.1",
29
- "jsdom": "^29.1.1",
29
+ "jsdom": "^30.0.1",
30
30
  "react": "^19.2.7",
31
31
  "react-dom": "^19.2.7",
32
32
  "typescript": "^5.9.3",
33
33
  "vite": "^8.2.2",
34
- "vitest": "^4.1.9"
34
+ "vitest": "^5.0.0"
35
35
  },
36
36
  "license": "Apache-2.0",
37
37
  "repository": {
@@ -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(
@@ -0,0 +1,24 @@
1
+ import { getConfig } from "@testing-library/dom";
2
+ import { expect, it } from "vitest";
3
+
4
+ // Testing Library's 1000ms default is not enough for this suite, and the way it fails is
5
+ // the problem: intermittently, on whichever test the machine happened to be busy during.
6
+ // Five failures across one day, four different tests, each passing alone and on a re-run —
7
+ // and one of them red in CI on a branch whose own change was fine.
8
+ //
9
+ // What this file holds is that the `configure` call in vitest.setup.ts actually TOOK
10
+ // EFFECT. Reading the number back out of the setup file would pass with the call deleted
11
+ // and the constant left behind, which is the one failure mode a config guard must not
12
+ // have. The bounds it has to sit between — above the default, below a toast's
13
+ // auto-dismiss, below `testTimeout` — span three files, so they are held from the Python
14
+ // side in `test_frontend_async_budget.py`, the way this repository holds its other
15
+ // cross-file config invariants. This package compiles with `types: []`, and reading files
16
+ // here would need node types it deliberately does not have.
17
+
18
+ const _WELL_ABOVE_THE_DEFAULT_MS = 2_000;
19
+
20
+ it("configures an async budget the loaded machine can actually meet", () => {
21
+ // Not a render: `findBy*` in these tests spans a resolved fetch, the state it sets and
22
+ // the re-render that puts the text on screen. One second covers that only when idle.
23
+ expect(getConfig().asyncUtilTimeout).toBeGreaterThanOrEqual(_WELL_ABOVE_THE_DEFAULT_MS);
24
+ });
@@ -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",
package/vite.config.ts CHANGED
@@ -10,5 +10,22 @@ export default defineConfig({
10
10
  environment: "node",
11
11
  setupFiles: ["./vitest.setup.ts"],
12
12
  include: ["src/**/*.test.ts", "src/**/*.test.tsx"],
13
+ // Above the `asyncUtilTimeout` the setup file configures, so a matcher that cannot
14
+ // find its element loses first and says which element. Equal budgets would let the
15
+ // test time out mid-wait and report nothing useful about the assertion. The ordering
16
+ // is held from the Python side in `test_frontend_async_budget.py`, which is why this
17
+ // comment names no number: an earlier version said "the 5s asyncUtilTimeout" while
18
+ // the setup file configured 3s, and a comment that misstates the code it explains is
19
+ // worse than none.
20
+ testTimeout: 15_000,
21
+ // These tests contend for the machine rather than with each other, and losing that
22
+ // contention is how they fail: four different fetch-bound assertions across four CI
23
+ // runs, always one file of eighty-one, each passing on its own. Widening the async
24
+ // budget was tried first and did not fix it (1s to 3s to 4s), and it has nowhere left
25
+ // to go -- a toast's 5s lifetime is the ceiling. So remove the cause rather than the
26
+ // tolerance: a jsdom + React + fetch file is heavy, a small runner has four vCPUs, and
27
+ // eighty-one of them at once starve each other's timers. It costs wall clock and buys
28
+ // a green that means something.
29
+ fileParallelism: false,
13
30
  },
14
31
  });
package/vitest.setup.ts CHANGED
@@ -3,6 +3,37 @@
3
3
  // the jsdom component tests.
4
4
  import "@testing-library/jest-dom/vitest";
5
5
 
6
+ import { configure } from "@testing-library/dom";
7
+
8
+ // `findBy*` and `waitFor` default to a 1000ms budget, and the component tests spend it on
9
+ // a path that is not a render: a mocked fetch resolving, then the state it sets, then the
10
+ // re-render that finally puts the text on screen. One second is enough on an idle machine
11
+ // and not on a loaded one, so the suite failed intermittently — five times across one day,
12
+ // four different tests, every one passing alone and on a re-run, and one of them red in CI
13
+ // on a branch whose own change was fine.
14
+ //
15
+ // The budget is raised rather than the tests retried. A retry would hide a genuinely
16
+ // intermittent product bug, and these assertions are not flaky in what they claim: the
17
+ // text does appear, and a matcher that waits longer asserts exactly the same thing. What
18
+ // it costs is that a test which SHOULD fail now takes longer to say so, which is why
19
+ // `testTimeout` moves too — the matcher must lose before the test does, or the failure
20
+ // arrives as an unhelpful "test timed out" instead of naming the element it could not find.
21
+ //
22
+ // It has a CEILING, and the first attempt at this walked straight into it. A toast
23
+ // auto-dismisses after `DEFAULT_DURATION_MS` (5s, toast.tsx), and several admin tests wait
24
+ // for a field error and then assert the toast SYNCHRONOUSLY. Set the budget to 5s and a
25
+ // wait that takes long enough outlives the toast the next line is about to look for — one
26
+ // flake traded for another, and a worse one, because it looks like a product bug. So the
27
+ // budget sits between the two: comfortably past a fetch and a re-render, comfortably short
28
+ // of a toast's life. `async-budget.test.ts` holds both ends.
29
+ //
30
+ // Raised from 3s to 4s on 2026-09-08: 3s was still not enough under CI load. Two
31
+ // consecutive runs failed on two different fetch-bound tests, and main failed a third
32
+ // time in the same window -- always "unable to find element", always one file of
33
+ // eighty-one. 4s keeps a full second below the toast, which is the last of the
34
+ // headroom this lever has: the next move is less contention, not a longer wait.
35
+ configure({ asyncUtilTimeout: 4_000 });
36
+
6
37
  // jsdom's File / Blob / FormData are structurally incompatible with Node's built-in
7
38
  // (undici) fetch: a jsdom File inside a FormData body serializes as an empty, nameless
8
39
  // part, and on Node >= 24 `Request.formData()` brand-checks reject jsdom instances
@@ -27,6 +58,25 @@ if (typeof window !== "undefined") {
27
58
  ).constructor as typeof FormData;
28
59
  globalThis.FormData = NativeFormData;
29
60
  window.FormData = NativeFormData;
61
+
62
+ // Vitest's jsdom environment installs a `Request` SUBCLASS whose constructor
63
+ // pre-processes `init.body` for jsdom's Blob internals (it reads `_buffer`).
64
+ // With the swap above that body is a Node FormData holding a Node File, so the
65
+ // shim throws on the one thing these tests exist to check — and handed a jsdom
66
+ // FormData instead it does not recognise it as form data at all and serialises
67
+ // the body as a string, so the request goes out as `text/plain` and the
68
+ // multipart assertion fails for a second, quieter reason. Unwrapping to the
69
+ // class it extends restores Node's own constructor, which serialises a Node
70
+ // FormData as multipart with a boundary.
71
+ //
72
+ // Guarded on the shim actually being there: a real `Request` is a base class,
73
+ // so its prototype is `Function.prototype`. If a later Vitest stops wrapping,
74
+ // this becomes a no-op rather than reaching for something that is not a class.
75
+ const RequestBase = Object.getPrototypeOf(globalThis.Request) as typeof Request;
76
+ if (typeof RequestBase === "function" && (RequestBase as unknown) !== Function.prototype) {
77
+ globalThis.Request = RequestBase;
78
+ window.Request = RequestBase;
79
+ }
30
80
  }
31
81
 
32
82
  // jsdom does not implement scrollTo, which TanStack Router calls on navigation; stub it so