@citolab/ctu-student-core 0.0.0-stage → 0.2.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/README.md CHANGED
@@ -1,3 +1,367 @@
1
- # Temporary Holding Version
1
+ # @cito-test-uit/student-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The student side of the Cito Test Uit (CTU) backend, without UI: start or resume a session by
4
+ code, load the assessment, save answers (with an offline-safe outbox), hand in, follow the
5
+ teacher's lock and read-aloud decisions, and prepare QTI items and tests for
6
+ `@citolab/qti-components`.
7
+
8
+ The CTU student app (`apps/student`) runs on it; other apps that render QTI their own way (first:
9
+ diggel-qti) use the same package, so every app writes the same server data — teacher review,
10
+ server scoring and resume work the same whichever app the student used.
11
+
12
+ - **`@cito-test-uit/student-core`** — framework-free. No React, no router, no toasts, no
13
+ telemetry, no `import.meta.env`: the host passes its configuration in.
14
+ - **`@cito-test-uit/student-core/react`** — a thin React layer (provider + React Query hooks) over
15
+ the same functions. Used by the CTU app; optional for anyone else.
16
+
17
+ ## API overview
18
+
19
+ | Area | Main entry (framework-free) |
20
+ |------|-----------------------------|
21
+ | Client | `createStudentClient({ apiBaseUrl, contentBaseUrl?, storageKeyPrefix?, onUnauthorized?, logger?, messages?, timeoutMs? })` → `connect()`, `disconnect()`, `api` (the `QtiApi`), `axios`, `outbox`, `storageKeys`, `fail(code)`, `message(code)` |
22
+ | Session | `createStudentSessionStore(client, { storageKey?, describeError? })` — a zustand vanilla store (`getState`, `setState`, `subscribe`). Actions: `initializeApi`, `startSession(code)`, `startNextSession`, `reloadSession`, `setIdentification`, `saveTestContext`, `saveTestState`, `saveFromQtiTest`, `getTestState`, `markCurrentItem`, `logAction`, `recordItemAttempt`, `handIn(options)`, `finishSession`, `scoreSession`, `resetSession`, `clearApi` |
23
+ | Endpoints | `startSessionByCode`, `fetchPlayerApp`, `getTestContext`, `putTestContext`, `updateSession`, `abandonSession`, `logSessionAction`, `postItemAttempt`, `fetchSubmittedItems`, `fetchPlayerConfig`, `lockSession`, `requestTextToSpeech`, `scoreSession`, `fetchSessionScoringProgress`, `fetchSessionFeedback`, `fetchSessionSequence` — plain functions over a connected `QtiApi` |
24
+ | Loading | `loadAssessmentForSession(api, session, client)`, `getSessionStart({ session, testContext, items })` (seed, item to open, `QtiTestState` to restore) |
25
+ | Toetssets | `startSessionSequenceWatch(client, code, { onChange })` → `stop()`, `refresh()`; `canStartNext`, `isWaitingForRelease`, `isSurveyPending`; store action `startNextSession()`; `confirmSessionSurvey` (see "Toetssets") |
26
+ | Lock / config | `startSessionLock(client, code, { onChange })` → `reportLock()`, `refresh()`, `stop()`; lower level `watchPlayerConfig`, `sendPendingLock`, `needsLivePoll` |
27
+ | QTI | `createItemTransform(options)`, `createTestTransform(options)`, `buildTestUrl`, `resolvePackageBase`, `testStateToContext`, `testContextToState` |
28
+ | Outbox | `createPendingSaves({ storagePrefix })` (the client owns one) |
29
+ | Process log | `createProcessLogger({ client, sessionCode, flushIntervalMs?, maxBatch?, storage?, now? })` → `log(action, content?, { itemId?, context? })`, `flush({ keepalive? })`, `dispose()`, `enabled` (see "Process log") |
30
+ | Player apps | `readPlayerAppCode(location.search)`, `playerAppRedirectUrl(app, code, origin)`, `PLAYER_APP_CODE_PARAM` (see "Arriving from the CTU app") |
31
+ | Errors | `StudentCoreError` (`code`: `StudentErrorCode`), `classifyApiError(error)` (kinds incl. `personal_code_required`, `origin_not_allowed`), `PERSONAL_CODE_REQUIRED_MESSAGE`, `ORIGIN_NOT_ALLOWED_MESSAGE` |
32
+
33
+ | `/react` | |
34
+ |----------|---|
35
+ | Provider | `StudentCoreProvider client store`, `useStudentClient`, `useStudentSession(selector)`, `bindSessionStore(store)` |
36
+ | Queries | `useAssessmentForSessionQuery`, `useResultsQuery`, `useSessionFeedbackQuery`, `useSessionScoringProgressQuery`, `studentQueryKeys` |
37
+ | Mutations | `useStartSessionMutation`, `useReloadSessionMutation`, `useHandIn` / `useHandInMutation`, `useScoreSessionMutation`, `studentMutationKeys` |
38
+ | Player | `useSessionLock`, `useTextToSpeechRequest`, `useItemAttempts`, `useLogAction`, `useLogSessionStartedOnce`, `useSessionSequence` |
39
+
40
+ ## Wiring an app
41
+
42
+ ```ts
43
+ import { createStudentClient, createStudentSessionStore } from '@cito-test-uit/student-core';
44
+
45
+ export const client = createStudentClient({
46
+ apiBaseUrl: 'https://ctu-api.example.org/api',
47
+ // Keep your app's storage apart from other student apps on the same origin.
48
+ storageKeyPrefix: 'diggel-',
49
+ onUnauthorized: () => {
50
+ // The student's token was refused: the client has logged out. Back to the code screen.
51
+ location.assign('/');
52
+ },
53
+ // Optional: messages: { unknown_code: 'Onbekende code', … } — texts for StudentCoreError codes.
54
+ });
55
+
56
+ export const session = createStudentSessionStore(client);
57
+ await session.getState().initializeApi(); // anonymous token, reused from storage when present
58
+ ```
59
+
60
+ - **`apiBaseUrl`** — the CTU API (`…/api`). **CORS:** the API must list your app's origin; requests
61
+ carry a bearer token (no cookies) and the headers `Authorization`, `x-code`, `x-name`,
62
+ `Content-Type`. Ask whoever runs the CTU backend to add your origin.
63
+ - **`contentBaseUrl`** — base for the package files (test XML, items, assets); defaults to
64
+ `apiBaseUrl`.
65
+ - **`storageKeyPrefix`** (default `student-`, the CTU app's) — every key the package writes:
66
+ localStorage `{prefix}assessment-storage-{host}` (the session), `{prefix}pending-save-{code}`
67
+ (unsent answers), `{prefix}lock-pending-{code}`, and sessionStorage
68
+ `{prefix}session-started-pending:{code}`. The student's token is stored by `QtiApi` under
69
+ `userInfos-{api host}-dotnet-student-auth`.
70
+
71
+ ### Auth flow by session code
72
+
73
+ 1. `initializeApi()` — `POST /auth/anonymous` gives an anonymous student token (refreshed with
74
+ `POST /auth/refresh`).
75
+ 2. `startSession(code)` — a **4-character** code is a delivery code (`POST /delivery/session/start`,
76
+ a new session); a **6-character** code is the student's own session code
77
+ (`POST /session/start`, resume). A 401 here is retried once with a fresh anonymous token. The
78
+ session, assessment, items and stored answers are then in the store; the session's own code is
79
+ `getState().session.code` (show it to the student so they can resume).
80
+ 3. Every later request carries the token. A 401 outside step 2 logs out and calls
81
+ `onUnauthorized`.
82
+
83
+ ### Arriving from the CTU app (`?code=`)
84
+
85
+ A toets can be set to your app (`playerApp`, see
86
+ [`backend/docs/player-apps.md`](../../../backend/docs/player-apps.md)). A student who types its code
87
+ into the CTU app is sent to `{your configured url}?code=XXXX`; log in with it straight away:
88
+
89
+ ```ts
90
+ import { readPlayerAppCode } from '@cito-test-uit/student-core';
91
+
92
+ const code = readPlayerAppCode(location.search); // 'ABCD' / 'ABC123' or null
93
+ if (code) await session.getState().startSession(code);
94
+ ```
95
+
96
+ `fetchPlayerApp(api, code)` tells which app delivers a code (null when unknown), and
97
+ `fetchPlayerConfig` returns it as `playerApp` during the session.
98
+
99
+ ### Toetssets: several toetsen with one code
100
+
101
+ In a Peiling afname a student can sit a **toetsset**: toetsen one after the other under one login
102
+ code ([`backend/docs/peiling-afnames.md`](../../../backend/docs/peiling-afnames.md)). Each toets is a
103
+ session of its own, and the server decides which one a code lands on, so the app needs no new login:
104
+
105
+ - `startSession(code)` with the student's code starts or resumes the toets they are at. The session
106
+ in the store is that toets' session; its `code` is the session's own, not the login code.
107
+ - After hand-in, ask where the student is and follow it while they wait:
108
+
109
+ ```ts
110
+ import { canStartNext, isWaitingForRelease, startSessionSequenceWatch } from '@cito-test-uit/student-core';
111
+
112
+ const watch = startSessionSequenceWatch(client, session.getState().session!.code, {
113
+ onChange: (sequence) => {
114
+ // null: not part of a toetsset — the ordinary "handed in" screen.
115
+ // sequence.index / count: "Toets 1 van 3 klaar".
116
+ // canStartNext(sequence): show "Start volgende toets".
117
+ // isWaitingForRelease(sequence): the teacher has to release the next toets; this is called
118
+ // again the moment they do (a long poll, no timer of your own).
119
+ // sequence.next === null: this was the last toets.
120
+ // isSurveyPending(sequence): the set ends with a survey the student still has to do.
121
+ },
122
+ });
123
+ // … watch.stop() when the screen goes away.
124
+ ```
125
+
126
+ - A set can end with a **survey on another site**. After the last toets `sequence.survey` is
127
+ `{ url, done }` — the URL already carries this student's id — and `isSurveyPending(sequence)` is
128
+ true until the student says they finished it: show the link (open it in a new tab) and a button
129
+ that calls `confirmSessionSurvey(client.api, code)`, which answers with the updated sequence
130
+ (`watch.refresh()` reads it again too). The server cannot see the other site, so this click is the
131
+ only signal there is.
132
+ - "Start volgende toets" is `await session.getState().startNextSession()`: the next toets is in the
133
+ store like after `startSession`. While the next toets is not released, it resolves with the
134
+ handed-in session again.
135
+
136
+ With React: `const sequence = useSessionSequence(sessionCode)` (`undefined` while it is read).
137
+ Lower level: `fetchSessionSequence(api, code, waitSeconds?, knownStatus?)`, `watchSessionSequence`.
138
+
139
+ ## Rendering with qti-components
140
+
141
+ ```ts
142
+ import { createItemTransform, createTestTransform, buildTestUrl, getSessionStart } from '@cito-test-uit/student-core';
143
+
144
+ const { session: s, currentAssessment, testContext, items } = session.getState();
145
+ const start = getSessionStart({ session: s, testContext, items });
146
+
147
+ const coreItemTransform = createItemTransform({
148
+ contentBaseUrl: client.contentBaseUrl,
149
+ packageBaseHref: currentAssessment?.packageBaseHref,
150
+ ctuStyling: false, // no CTU classes on qti-item-body; your own styling
151
+ });
152
+
153
+ // Your own step after the core pipeline: chain on the transformer it returns.
154
+ const itemTransform = async (transformer, itemRef) =>
155
+ (await coreItemTransform(transformer, itemRef)).fn((xml) => {
156
+ xml.querySelectorAll('[class^="type:"]').forEach((el) => { /* rename, lift, … */ });
157
+ return xml;
158
+ });
159
+
160
+ qtiTest.postLoadTransformCallback = itemTransform;
161
+ qtiTest.postLoadTestTransformCallback = createTestTransform({ shuffleSeed: start.seed });
162
+ qtiTest.qtiContext = start.withSeed(qtiTest.qtiContext); // same shuffle on every resume
163
+ if (start.state) qtiTest.state = start.state; // restore answers + position
164
+ testContainer.testURL = buildTestUrl(client.contentBaseUrl, currentAssessment?.assessmentHref); // <test-container test-url>
165
+ ```
166
+
167
+ The item transform does what the CTU player does: qti-convert cleanup (legacy objects to
168
+ audio/video/img, extended DEP interactions, SSML), asset `src`/`href` made absolute against the
169
+ item's folder, PCI modules resolved (`configurePci`, reading the package's module-resolution
170
+ config), stylesheets inlined, `title` attributes dropped. Authored classes (`type:…`, `block:…`),
171
+ `qti-rubric-block`s and PCI markup are left as they are. `ctuStyling: true` (the default) adds
172
+ `custom-qti-style content` (and `cito-style` for items linking a cito_itemstyle sheet) to
173
+ `qti-item-body`.
174
+
175
+ ### Saving and resuming
176
+
177
+ Feed `qti-test`'s state to the session; it is stored as the same server context the CTU player
178
+ writes (with the variable declarations server scoring needs, taken from `qtiTest.testContext`):
179
+
180
+ ```ts
181
+ qtiTest.addEventListener('qti-state-changed', () => {
182
+ void session.getState().saveFromQtiTest(qtiTest); // throttled; { urgent: true } sends now
183
+ });
184
+ ```
185
+
186
+ Saves are written to localStorage at once and sent at most every 5 s (urgent: now), retried until
187
+ the server has them, and numbered so a late request cannot roll answers back. Answers left behind
188
+ by a student who closed the tab offline are delivered on the next `initializeApi()`. `saveStatus`
189
+ in the store is `saved | saving | failing` — show a warning on `failing`.
190
+
191
+ To resume, `getSessionStart(…).state` (or `session.getState().getTestState()`) is the stored
192
+ `QtiTestState`. `testStateToContext` / `testContextToState` are the mapping itself.
193
+
194
+ ### Hand-in from a DOM event
195
+
196
+ ```ts
197
+ document.addEventListener('test-end', async () => {
198
+ await session.getState().handIn({
199
+ flush: () => session.getState().saveFromQtiTest(qtiTest, { urgent: true }),
200
+ });
201
+ // session.getState().session.sessionState === 'finished'; show your end screen.
202
+ });
203
+ ```
204
+
205
+ `handIn` flushes, sends the answers, stores the context as `finished`, logs
206
+ `assessment_handed_in`, marks the session finished and drops the local outbox; without
207
+ `backendScoring: true` it then reads the scored answers back into the store.
208
+
209
+ ### Lock and read-aloud
210
+
211
+ ```ts
212
+ const lock = startSessionLock(client, code, { onChange: (s) => render(s.isLocked, s.effectiveSettings) });
213
+ document.addEventListener('fullscreenchange', () => { if (!document.fullscreenElement) lock.reportLock(); });
214
+ // later: lock.stop();
215
+ ```
216
+
217
+ ### Process log
218
+
219
+ Process data for research — what the student clicks, types and pastes — goes to
220
+ `POST /session/{code}/process-log` as `{ events: [{ seq, occurredAt, itemId, action, content, context }] }`.
221
+ One logger per session:
222
+
223
+ ```ts
224
+ import { createProcessLogger } from '@cito-test-uit/student-core';
225
+
226
+ const processLog = createProcessLogger({ client, sessionCode: session.getState().session!.code });
227
+
228
+ processLog.log('item_start', null, { itemId: 'item-3' });
229
+ processLog.log('tekst_invoer', textarea.value, { itemId: 'item-3', context: 'RESPONSE' });
230
+ processLog.log('plakken', pasted, { itemId: 'item-3' });
231
+
232
+ // Leaving the session (hand-in, back to the code screen):
233
+ processLog.dispose();
234
+ ```
235
+
236
+ - **Nothing is lost.** Each `log` is written to localStorage at once
237
+ (`{storageKeyPrefix}process-log:{code}`: the events and the next `seq`) and only removed when the
238
+ server has accepted it. A reload creates a new logger that sends what was left and continues the
239
+ sequence. The server stores each `(code, seq)` once, so a batch sent twice is harmless.
240
+ - **`seq`** increases per session; a session without a stored queue (first start, or a resume on
241
+ another device) starts it at the clock (`Date.now()`), so new events never collide with ones sent
242
+ earlier. **`occurredAt`** is the client's time.
243
+ - **Validation** never throws: `action` is lower-cased and must match `[a-z0-9_-]{1,64}` (else the
244
+ event is dropped with a console warning); `content` is cut at 20 000 characters, `context` at 200.
245
+ - **Sending:** every `flushIntervalMs` (5 s), at once when the queue reaches `maxBatch` (200, at
246
+ most 500), and on `pagehide` / `visibilitychange` to hidden and on `dispose()` with
247
+ `fetch(…, { keepalive: true })`. Keepalive bodies are limited to 64 KB, so that request carries
248
+ the oldest events that fit and leaves the rest for the next page. Normal sends go through the
249
+ client's axios (token refresh included); the keepalive request carries the bearer token from
250
+ `client.api.userInfo.token`.
251
+ - **Answers:** network errors, 401, 408, 429 and 5xx are retried with backoff (1 s … 30 s); a 400
252
+ drops the batch (with a warning); **404** means the backend has process logging off (or does not
253
+ know the session): `enabled` becomes false, the queue is dropped and later `log` calls do
254
+ nothing; **403** (`Origin not allowed`) stops sending but keeps the queue — the app shows its own
255
+ error.
256
+
257
+ ## A minimal Lit element
258
+
259
+ ```ts
260
+ import { LitElement, html } from 'lit';
261
+ import { customElement, state } from 'lit/decorators.js';
262
+ import { createStudentClient, createStudentSessionStore, type StudentSessionStoreState } from '@cito-test-uit/student-core';
263
+
264
+ const client = createStudentClient({ apiBaseUrl: 'https://ctu-api.example.org/api', storageKeyPrefix: 'demo-' });
265
+ const session = createStudentSessionStore(client);
266
+
267
+ @customElement('code-login')
268
+ export class CodeLogin extends LitElement {
269
+ @state() private s: StudentSessionStoreState = session.getState();
270
+ private unsubscribe = () => {};
271
+
272
+ connectedCallback() {
273
+ super.connectedCallback();
274
+ this.unsubscribe = session.subscribe((s) => (this.s = s));
275
+ void session.getState().initializeApi();
276
+ }
277
+ disconnectedCallback() {
278
+ this.unsubscribe();
279
+ super.disconnectedCallback();
280
+ }
281
+
282
+ private async submit(e: Event) {
283
+ e.preventDefault();
284
+ const code = new FormData(e.target as HTMLFormElement).get('code') as string;
285
+ await session.getState().startSession(code).catch(() => undefined); // error lands in s.error
286
+ }
287
+
288
+ render() {
289
+ if (this.s.session) return html`<p>Started ${this.s.session.assessmentName} — your code: ${this.s.session.code}</p>`;
290
+ return html`<form @submit=${this.submit}>
291
+ <input name="code" maxlength="6" ?disabled=${!this.s.isAuthReady} />
292
+ <button>Start</button>
293
+ ${this.s.error ? html`<p role="alert">${this.s.error}</p>` : null}
294
+ </form>`;
295
+ }
296
+ }
297
+ ```
298
+
299
+ ## React
300
+
301
+ ```tsx
302
+ import { StudentCoreProvider, useStartSessionMutation, useStudentSession } from '@cito-test-uit/student-core/react';
303
+
304
+ <QueryClientProvider client={queryClient}>
305
+ <StudentCoreProvider client={client} store={session}>…</StudentCoreProvider>
306
+ </QueryClientProvider>
307
+ ```
308
+
309
+ Needs `react` and `@tanstack/react-query` (optional peers; only this entry imports them).
310
+
311
+ ## Building and consuming from another repo
312
+
313
+ ```bash
314
+ cd CitoTestUit/frontend
315
+ yarn workspace @cito-test-uit/student-core build # → packages/student-core/dist
316
+ ```
317
+
318
+ `dist/` is a complete package: ESM (`index.js`, `react.js`) with `.d.ts`, its own `package.json`
319
+ (exports `.` and `./react`). The workspace packages it uses (`@cito-test-uit/api-client`, `data`,
320
+ `types`) are bundled into it — only the modules student-core needs. Not bundled:
321
+
322
+ | Kind | Packages | Why |
323
+ |------|----------|-----|
324
+ | dependencies | `axios`, `zustand`, `@citolab/qti-convert` | ordinary libraries, installed and deduplicated by your package manager. zustand is a dependency, not a peer: the store is internal (you use it through `getState`/`subscribe`), so its version does not need to match yours |
325
+ | peers | `@citolab/qti-api` ^9, `@citolab/qti-components` ^9.6 | must be the same instances your app renders with (custom-element registration, `QtiApi` types) |
326
+ | optional peers | `react`, `react-dom`, `@tanstack/react-query` | only for `/react` |
327
+
328
+ ### From npm
329
+
330
+ `dist/` is published to npm as **`@citolab/ctu-student-core`** (`npmName` in `package.json`).
331
+ Install it under its workspace name with an alias, so imports read the same in every app:
332
+
333
+ ```jsonc
334
+ // package.json
335
+ "dependencies": {
336
+ "@cito-test-uit/student-core": "npm:@citolab/ctu-student-core@0.2.0",
337
+ "@citolab/qti-api": "9.0.0",
338
+ "@citolab/qti-components": "^9.6.2"
339
+ }
340
+ ```
341
+
342
+ To release, by hand: raise `version` in `package.json`, commit and push it to `main`, then
343
+
344
+ ```bash
345
+ cd CitoTestUit/frontend
346
+ yarn workspace @cito-test-uit/student-core release --dry-run # optional: everything but the publish
347
+ yarn workspace @cito-test-uit/student-core release
348
+ ```
349
+
350
+ `scripts/release.mjs` stops unless the checkout is clean and at `origin/main`, the version is new on
351
+ npm and you are logged in (`npm login`). It runs lint, typecheck, tests and the build, publishes
352
+ `dist/` (npm asks for your 2FA code), and tags the commit `student-core-v<version>`.
353
+
354
+ ### From a checkout
355
+
356
+ While changing student-core and an app together, point the app at `dist/` with `portal:` (follows
357
+ the package's own dependencies; rebuild to update) or `file:` (a copy; `yarn up` after a rebuild):
358
+
359
+ ```jsonc
360
+ "@cito-test-uit/student-core": "portal:../CitoTestUit/frontend/packages/student-core/dist"
361
+ ```
362
+
363
+ Register the qti-components elements yourself, once, before any test renders (the CTU app imports
364
+ `@citolab/qti-components/corrections`); student-core imports only `qti-transformers` and types.
365
+
366
+ Inside this monorepo nothing needs building: the CTU app compiles the sources through the
367
+ `@cito-test-uit/student-core` path alias.