@micha.bigler/ui-core-micha 3.9.0 → 3.10.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.
@@ -0,0 +1,304 @@
1
+ # UCM-TEST-1: A kit integration check every app runs in its own suite
2
+
3
+ # A. Envelope, authored by the Expertenchat
4
+
5
+ ## Goal & expected outcome
6
+
7
+ The kit's auth screens are the same code in every app, so their behaviour is accepted once, in the kit.
8
+ What differs per app is **how the app wires the kit in**: its i18n setup, its providers around the kit's
9
+ pages, the `i18next` instance the kit reads. Today each bump order writes its own tests for that, app by
10
+ app, and the operator walked the same auth flows by hand in every app.
11
+
12
+ After this order the kit ships **one exported check**, `checkKitIntegration`, that an app calls from a
13
+ single test in its own suite. It returns findings in the style of `assertThemeComplete`: an empty list
14
+ means the app's wiring is sound. Every later bump in every app then re-checks the wiring automatically.
15
+
16
+ **Operator decisions (2026-10-01):** the check lives centrally in the kit, not as copies per app; a
17
+ separate, automated staging smoke covers the runtime (`workflow-templates` `WFT-CI-31`); bumps already
18
+ in flight are not held up, and apps adopt the check with their next bump.
19
+
20
+ ## Context the operator established
21
+
22
+ - **Precedent for the shape:** `assertThemeComplete(theme)` returns `{ findings }`, is exported from the
23
+ package root (`src/index.js:12`), and apps assert `findings` equals `[]`.
24
+ - **What apps load from the kit for i18n:** `uiCoreTranslations` (`src/i18n/uiCoreTranslations.js`),
25
+ which spreads the auth, charts, messaging, notifications, onboarding, section-nav and user-menu
26
+ catalogues. Apps spread it into their own i18next resources at start-up, **kit keys last** (e.g.
27
+ `survey_app/frontend/i18n/index.js`).
28
+ - **Which `i18next` the kit reads:** `apiClient` imports the **default** `i18next` instance
29
+ (`src/auth/apiClient.jsx:2,13`) to send `Accept-Language`. Kit components read `t` and `i18n` from
30
+ `useTranslation()` (e.g. `src/pages/LoginPage.jsx:30`). `i18next`/`react-i18next` are peer
31
+ dependencies.
32
+ - **What the per-app bump orders tested by hand** (`survey_app` `SVA-DEP-1`/`SVA-DEP-2`): the kit's
33
+ `SignUpPage` and `PasswordInvitePage` render inside the app's providers
34
+ (`survey_app/frontend/src/AuthRoutesIntegration.test.jsx`), and `i18n.exists('Auth.field.email.invalid')`
35
+ holds in the app's own i18n.
36
+ - **The defect this guards against end to end:** a login with a malformed e-mail showed the raw code
37
+ `invalid` (`UCM-AUTH-10`). The kit's resolver fixes it, but only if the app's i18n carries the kit's
38
+ keys and the kit's pages run on the app's instance.
39
+ - **Consumers measured 2026-09-30:** every consumer runs `vitest` with jsdom. Some mount `LoginPage`
40
+ twice (`webshop-guenter` also in `src/pages/pwa/StaffLoginPage.jsx`). Several mock `react-i18next`
41
+ globally in some test files.
42
+
43
+ ## The check (decided)
44
+
45
+ `checkKitIntegration({ i18n, wrapper, pages })` -> `Promise<{ findings }>`, exported from the package
46
+ root. `i18n` is the app's own instance, `wrapper` the app's own provider component (whatever the app
47
+ puts around its routes), `pages` the kit pages the app mounts (default: the kit's auth pages that the
48
+ app imports). Each finding names its check and a reason. Four checks:
49
+
50
+ 1. **Catalogue.** Every key in `uiCoreTranslations` resolves through the app's `i18n` in every language
51
+ that both the kit ships (`de`/`en`/`fr`/`sw`) and the app supports. A missing key is one finding,
52
+ with key and language.
53
+ 2. **Instance.** The default `i18next` instance is initialised and is the instance the app passed in.
54
+ Otherwise the finding says what will break: `Accept-Language` is missing or wrong.
55
+ 3. **Render.** Each page in `pages` renders inside `wrapper` without throwing, and no rendered text
56
+ node is a raw kit key (`Auth.*` or another key of the kit's catalogues) or a bare backend code. The
57
+ check stubs the kit's `apiClient` transport for its own duration, so no request leaves the test, and
58
+ restores it afterwards.
59
+ 4. **Error text.** `LoginPage` inside `wrapper` receives, through that stub, exactly the allauth response
60
+ from the original defect (`400`, `errors[0] = {code: "invalid", param: "email", message: ...}`). The
61
+ shown text equals the app-language text of `Auth.field.email.invalid`.
62
+
63
+ ## Scope + non-goals
64
+
65
+ In scope: the function and its four checks; its export from the package root; a `README.md` section
66
+ "Consumer integration check" with the one-line test an app writes; `CHANGELOG.md`; a **minor** release.
67
+
68
+ Non-goals:
69
+ - No change in any app. Adoption happens per app with its next bump, as its own row.
70
+ - No runtime dependency added for consumers. Rendering uses the existing peers (`react`, `react-dom`).
71
+ - No check of the app's test mocks. A suite whose mocks lack `i18n` still fails in that suite, as today.
72
+ - No replacement for the kit's own tests. They keep owning the kit's behaviour.
73
+ - No staging or browser check (`WFT-CI-31`).
74
+
75
+ ## Tier · precondition / gate
76
+
77
+ - **Tier 3 · tests: each of the four checks with a passing and a failing case; the kit's existing auth
78
+ and i18n tests.** A change inside shared-core, on the auth surface.
79
+ - Precondition: none.
80
+ - Downstream: every app adopts it with its next kit bump. `WFT-CI-31` is independent of this order.
81
+
82
+ ## Risks
83
+
84
+ - **A check that cannot fail is decoration.** Each check needs a test showing it reports the specific
85
+ defect: a missing key, a second `i18next` instance, a wrapper that throws, a raw code on screen.
86
+ - **The transport stub must not leak.** If it is not restored, it silently swallows the requests of the
87
+ tests that run after it. Restore it even when a check throws.
88
+ - **Kit keys that the app intentionally leaves untranslated** for a language it does not offer must not
89
+ become findings. Hence "languages both support" in check 1.
90
+ - **Locally, importing the kit's root module crashes vitest's worker pool on this workstation**
91
+ (`fitness-monitor` `FM-15`). That is an environment issue: CI is the evidence. The check itself must not
92
+ add to the import weight of tests that do not call it.
93
+
94
+ ## Required tests to WRITE (you write them and run YOUR OWN new ones; the Orchestrator's run is the gate)
95
+
96
+ Kit test suite, one new file:
97
+
98
+ 1. A correctly wired fixture app (own `i18n` with `uiCoreTranslations`, a provider wrapper) -> `findings`
99
+ equals `[]`.
100
+ 2. One key removed from the fixture's resources -> exactly one catalogue finding naming that key and
101
+ language.
102
+ 3. The fixture passes a separate `i18next` instance -> an instance finding.
103
+ 4. A wrapper that throws -> a render finding naming the page.
104
+ 5. The resolver bypassed (a fixture that shows `err.code`) -> an error-text finding.
105
+ 6. After the check, a request through `apiClient` is no longer stubbed.
106
+
107
+ Run, do not write: the kit's existing auth and i18n tests.
108
+
109
+ ## Parity guardrail
110
+
111
+ No change to any existing export, component or behaviour. The function is new and test-only in purpose.
112
+
113
+ ---
114
+
115
+ # B. Implementation map, filled by the Orchestrator and ADDRESSED TO THE IMPLEMENTER
116
+
117
+ ## Context package
118
+
119
+ ### Where this lives, and what it may depend on
120
+
121
+ - New file `src/testing/checkKitIntegration.js` (new subdirectory, mirroring how `src/theme/` groups
122
+ `assertThemeComplete`). Export `checkKitIntegration` from `src/index.js` at the root, next to the
123
+ existing theme-completeness exports (line ~10-21) — same section-style comment, same pattern.
124
+ - **Hard constraint from the Non-goals: "Rendering uses the existing peers (react, react-dom)" —
125
+ this explicitly does NOT include `@testing-library/react`.** Every existing kit test uses RTL, but
126
+ RTL is a devDependency of THIS repo, not a declared peer dependency — if the shipped function
127
+ imported it, every consuming app would need RTL in its own `node_modules` at the exact version
128
+ this kit expects, silently, which is exactly the "no runtime dependency added for consumers" this
129
+ WO forbids. Render with plain `react-dom/client` (`createRoot`) and `act` from `react` — verified
130
+ now: `import { act } from 'react'` resolves and is a function on this repo's installed React
131
+ `19.2.6` (`node -e "console.log(typeof require('react').act)"` → `function`), so use that import,
132
+ not the legacy `react-dom/test-utils` path. Read rendered output via plain
133
+ DOM (`container.textContent`, `document.createTreeWalker`), not `screen`/`within`.
134
+ - `react-router-dom` (`^7.15.1`) and `axios` (`^1.16.1`) ARE existing peers — safe to import
135
+ `MemoryRouter` and to manipulate the shared `apiClient` axios instance directly.
136
+
137
+ ### The four checks, in the order the Envelope lists them
138
+
139
+ 1. **Catalogue.** Import `{ uiCoreTranslations }` from `'../i18n/uiCoreTranslations'`. For each key,
140
+ for each language in the INTERSECTION of the kit's shipped languages
141
+ (`['de','en','fr','sw']`) and the app's own supported languages, assert
142
+ `i18n.exists(key, { lng: lang })` — **not** `i18n.exists(key)` alone, which only checks the
143
+ CURRENT active language; i18next's `exists`/`t` both accept an `lng` option to check a specific
144
+ language without switching the instance's active one (verify this against the installed
145
+ `i18next` version's own typings/source before relying on it — do not assume from memory).
146
+ Derive "the app's own supported languages" with this priority (first one that yields a
147
+ non-empty array): `i18n.options?.supportedLngs` (filter out falsy entries and the literal
148
+ string `'cimode'`, which i18next auto-adds) → `Object.keys(i18n.options?.resources || {})` →
149
+ `i18n.languages` (least reliable, only the currently-resolved fallback chain — last resort).
150
+ One finding per missing `(key, lang)` pair, naming both.
151
+ 2. **Instance.** Import the kit's OWN default `i18next` singleton (`import i18next from 'i18next'`
152
+ — the exact same import `src/auth/apiClient.jsx` already uses). Finding if `!i18next.isInitialized`
153
+ OR `i18n !== i18next` (reference inequality — the whole point is catching an app that created a
154
+ SEPARATE instance via `i18next.createInstance()` and wrapped its tree in its own
155
+ `I18nextProvider`, which is exactly the Risk `UCM-AUTH-10` named: the kit's `apiClient` would then
156
+ send `Accept-Language` from an uninitialized, different instance). Name what breaks in the
157
+ reason text (`Accept-Language` will be missing or wrong) — do not just say "mismatch".
158
+ 3. **Render.** For each page component in `pages` (default: `[LoginPage, SignUpPage,
159
+ PasswordInvitePage]` — the three pages `UCM-AUTH-9`/`UCM-AUTH-10` actually touched, and the same
160
+ set `survey_app`'s own `AuthRoutesIntegration.test.jsx` already covers by hand), render
161
+ `<MemoryRouter><Wrapper><Page /></Wrapper></MemoryRouter>` into a fresh detached `div` (own
162
+ `createRoot` per page, `root.unmount()` after each, even on failure — use try/finally per page,
163
+ not one try around the whole loop, so one page's render failure doesn't skip scanning the rest).
164
+ Wrap the render in `act(async () => { ... })` so effects/microtasks settle before you scan.
165
+ Catch a throw during render → one finding naming the page's display name (`Page.displayName ||
166
+ Page.name || 'page'`) and the error message; do NOT let it abort the whole check (catch per-page,
167
+ continue the loop). If it didn't throw, walk every text node
168
+ (`document.createTreeWalker(container, NodeFilter.SHOW_TEXT)`) and flag any whose TRIMMED content
169
+ either (a) exactly equals a key in `uiCoreTranslations` (a literal untranslated key leaking to
170
+ screen — the i18next missing-key echo), or (b) matches a bare lowercase/snake_case single-token
171
+ shape with no spaces, e.g. `/^[a-z][a-z0-9_]*$/` and length > 2 (the exact shape of the original
172
+ defect, a raw backend code like `invalid` — tune this pattern against Required Test #5's fixture
173
+ until it fires on that fixture and not on ordinary rendered prose; do not accept the first regex
174
+ that merely compiles). One finding per offending text node, naming the page and the text found.
175
+ 4. **Error text.** This check is not driven by the `pages` array — it ALWAYS specifically exercises
176
+ `LoginPage` (imported directly by this module), because it is testing the kit's resolver wiring
177
+ through a real submit flow, not generic rendering. Render `LoginPage` the same way as check 3.
178
+ Stub the credentials-login POST specifically — exact path, verified now:
179
+ `/api/auth/browser/v1/auth/login` (`src/auth/authConfig.jsx`'s `HEADLESS_BASE` +
180
+ `src/auth/authApi.jsx:99`'s `loginWithPassword`) — to reject with EXACTLY
181
+ the operator's original defect shape:
182
+ `{ response: { status: 400, data: { errors: [{ code: 'invalid', param: 'email', message: '<some
183
+ backend text>' }] } } }` (a plain object is sufficient — `resolveErrorText`/`extractErrorInfo`
184
+ only ever read `.response?.status`/`.response?.data` off the rejected value, nothing
185
+ AxiosError-specific). Fill the email/password inputs via plain DOM (`input.value = '...'` +
186
+ dispatching a real `input`/`change` `Event` so React's controlled-input `onChange` fires —
187
+ `Object.getOwnPropertyDescriptor` trick may be needed to set a native input value in a way React
188
+ notices; this is a well-known React-testing gotcha independent of any test-utility library, look
189
+ it up if the naive `input.value = x; input.dispatchEvent(new Event('input'))` doesn't trigger the
190
+ controlled state update) and submit (dispatch a `submit` Event on the form, or `.click()` the
191
+ submit button). `await act(async () => { ...await flush... })` until the error text renders.
192
+ Assert the rendered text equals `i18n.t('Auth.field.email.invalid')` evaluated in the APP's
193
+ current active language (`i18n.language`), read via the SAME walk-and-scan helper check 3 uses
194
+ (do not duplicate the scanning logic — factor it into one shared helper both checks call).
195
+
196
+ ### Stubbing `apiClient` — must never leak, must restore even on throw
197
+
198
+ `apiClient` (`src/auth/apiClient.jsx`, default export, an axios instance) is shared, module-singleton
199
+ state — the SAME instance every kit page uses. Capture `const originalAdapter =
200
+ apiClient.defaults.adapter;` BEFORE check 3 starts, install a replacement
201
+ (`apiClient.defaults.adapter = async (config) => { ... }`) that, by default, REJECTS every request
202
+ (so check 3's page renders — which must not make real network calls at all — fail loudly if they
203
+ accidentally do, rather than hanging on a real fetch), and for check 4 specifically, additionally
204
+ matches on `config.url` to return the fixture rejection ONLY for the login endpoint
205
+ (`HEADLESS_BASE`-relative, check `src/auth/authApi.jsx`'s `loginWithPassword` for the exact path) and
206
+ the default reject-everything behaviour for anything else. **Wrap the ENTIRE checks 3+4 body in a
207
+ `try { ... } finally { apiClient.defaults.adapter = originalAdapter; }`** — the restore must run even
208
+ if a render throws an error this code doesn't catch, even if an `expect`-shaped helper you write
209
+ itself throws. This is Required Test #6's whole point and the Risk note's explicit warning.
210
+
211
+ ### `README.md` — "Consumer integration check" section
212
+
213
+ One short section with the one-line test an app writes, e.g.:
214
+ ```js
215
+ import { checkKitIntegration } from '@micha.bigler/ui-core-micha';
216
+ import i18n from '../i18n'; // the app's own initialised default i18next instance
217
+ import { AppProviders } from '../AppProviders'; // whatever the app wraps its routes in
218
+
219
+ it('kit integration is sound', async () => {
220
+ const { findings } = await checkKitIntegration({ i18n, wrapper: AppProviders });
221
+ expect(findings).toEqual([]);
222
+ });
223
+ ```
224
+ Name the default `pages` set explicitly (`LoginPage`, `SignUpPage`, `PasswordInvitePage`) and that an
225
+ app can pass its own `pages` array to cover more/fewer pages.
226
+
227
+ ### Test file — new, next to the existing kit tests (e.g. `tests/checkKitIntegration.test.js`)
228
+
229
+ Build ONE minimal fixture i18next instance + a trivial `Wrapper` (e.g. just renders `children`, or a
230
+ thin `AuthContext.Provider` with a fake user so `LoginPage`'s own context read doesn't throw) reused
231
+ across the 6 Required Tests, each test mutating ONE thing away from "correctly wired":
232
+ 1. Correctly wired fixture (own real `i18next.createInstance()` seeded with `uiCoreTranslations` in
233
+ all 4 kit languages, THIS instance also assigned as the global default — i.e. do not create a
234
+ second competing instance for the "passing" case, since check 2 would then always fail; for a
235
+ realistic "app's own instance IS the default" fixture either call `i18next.init(...)` on the
236
+ real default singleton directly, matching how an app actually does it, or structure the fixture
237
+ so the "instance" check specifically is satisfiable) → `findings` is `[]`.
238
+ 2. Remove one key's resources for one language from the fixture → exactly one catalogue finding
239
+ naming that key and language.
240
+ 3. Pass a SEPARATE `i18next.createInstance()` as `i18n` instead of the default singleton → an
241
+ instance finding.
242
+ 4. A `wrapper` that throws during render → a render finding naming the page.
243
+ 5. **The actual regression proof:** stub the login POST to reject with the operator's exact shape
244
+ but WITHOUT going through the kit's resolver (simulate "the resolver bypassed" by using a fixture
245
+ `LoginPage`-equivalent harness only if you must — more directly: this is best proven by reverting
246
+ `resolveErrorText`'s field-key step locally, confirming check 4 then reports an error-text
247
+ finding instead of passing, then restoring — narrate this in `PROGRESS` as the transient
248
+ mutation proof, same pattern as `UCM-AUTH-11`/`UCM-THEME-15` in this repo, rather than leaving a
249
+ permanently reverted copy in the committed suite).
250
+ 6. After calling `checkKitIntegration(...)` once, assert `apiClient.defaults.adapter` is back to
251
+ whatever it was before the call (capture the reference beforehand) — proves restoration even on
252
+ the success path; also add a case that makes an internal step throw (e.g. a page whose render
253
+ throws) and still assert the adapter was restored afterwards (the `try/finally` must cover the
254
+ failure path too, not just the happy path).
255
+
256
+ Run, do not write: the kit's existing auth and i18n tests (grep `tests/` for
257
+ `i18nAggregate`/`authErrors`/`resolveErrorText`/`loginPageErrorResolution` — these are the
258
+ directly-dependent set the Orchestrator re-runs as the gate).
259
+
260
+ ## Do-not-touch / invariants
261
+
262
+ - No change to any existing export, component, or behaviour (Parity guardrail) — this is a new,
263
+ additive, test-only function.
264
+ - Do not add `@testing-library/react` (or any other new package) to `dependencies`,
265
+ `peerDependencies`, or `devDependencies` for this function's own sake.
266
+ - Do not touch `apiClient.jsx`'s actual interceptors/exports — only reach into
267
+ `apiClient.defaults.adapter` from the NEW module, temporarily, with a guaranteed restore.
268
+
269
+ ---
270
+
271
+ # C. Orchestrator only, NOT ADDRESSED TO THE IMPLEMENTER
272
+
273
+ > **If you are the implementer reading this work order as your own specification: STOP at this line.**
274
+ > Everything below describes what the Orchestrator does AFTER you finish. You do none of it: no
275
+ > reviewers, no verification run, no register edit, no `git add`/`commit`/`push`.
276
+
277
+ ### Execution directive
278
+
279
+ Check `.claude/codex-status.md` first (newest-first; read it with `head`). No line for today means use
280
+ Codex. Before `git push`, run `git log origin/main..HEAD` and push only if every listed commit is this
281
+ order's (parallel sessions share this checkout).
282
+
283
+ ### Review routing
284
+
285
+ Tier 3: independent `reviewer` (all configured lenses) and `ui_reviewer`, concurrent, one batch, before
286
+ the commit. No `sec_reviewer`: the function adds no runtime path, it only reads what is already there.
287
+
288
+ ### Verification
289
+
290
+ Run the check once against a real consumer before release. `survey_app` is on `3.9.x` and has the closest
291
+ existing test (`frontend/src/AuthRoutesIntegration.test.jsx`). Do it from a scratch copy or a local pack,
292
+ never by committing to that repo. Name the result in the register Notiz.
293
+
294
+ ### Register + commit + release
295
+
296
+ Row -> `done` with the review Notiz in the `AGENTS.md` shape and the published version. The publish
297
+ runs on push to `main` when `package.json`/`src/**` change; verify it through the job log
298
+ (`npm view` lags for provenance publishes). Adoption rows per app are added by the Expertenchat when
299
+ each app's next bump is scoped.
300
+
301
+ ### Mini-handover
302
+
303
+ `Orchestrator: implement work-orders/UCM-TEST-1.md in ui-core-micha (main). git pull first, read the WO,
304
+ then follow orchestrate-codex.`