@intellectif/lk-core 0.5.0 → 0.7.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.
Files changed (46) hide show
  1. package/README.md +12 -4
  2. package/dist/{activity-wkzRemHx.d.cts → activity-gelWNZ6V.d.cts} +49 -10
  3. package/dist/{activity-wkzRemHx.d.ts → activity-gelWNZ6V.d.ts} +49 -10
  4. package/dist/{chunk-WV5WQ3SZ.js → chunk-2SQ75JTE.js} +2 -2
  5. package/dist/{chunk-4JR3UXX6.cjs → chunk-5RE3ZRSA.cjs} +8 -1
  6. package/dist/chunk-5RE3ZRSA.cjs.map +1 -0
  7. package/dist/{chunk-FCM5VJBS.cjs → chunk-7NIH5IL3.cjs} +16 -13
  8. package/dist/chunk-7NIH5IL3.cjs.map +1 -0
  9. package/dist/{chunk-R7PDJBRX.cjs → chunk-AFIQQADJ.cjs} +4 -4
  10. package/dist/{chunk-R7PDJBRX.cjs.map → chunk-AFIQQADJ.cjs.map} +1 -1
  11. package/dist/{chunk-SM5HUGYU.cjs → chunk-MVZKEWZN.cjs} +21 -11
  12. package/dist/chunk-MVZKEWZN.cjs.map +1 -0
  13. package/dist/{chunk-DUQVGLQ3.js → chunk-NOBJYDOB.js} +15 -5
  14. package/dist/chunk-NOBJYDOB.js.map +1 -0
  15. package/dist/{chunk-LSHDNA2T.js → chunk-XL75ZZVM.js} +6 -3
  16. package/dist/chunk-XL75ZZVM.js.map +1 -0
  17. package/dist/{chunk-NUCEUU4P.js → chunk-YCXIHFLG.js} +8 -1
  18. package/dist/chunk-YCXIHFLG.js.map +1 -0
  19. package/dist/{index-BKyZrd94.d.cts → index-B_RLyeEj.d.ts} +101 -14
  20. package/dist/{index-CLmXzBhB.d.ts → index-CDWH2WIg.d.cts} +101 -14
  21. package/dist/index.cjs +336 -25
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +360 -6
  24. package/dist/index.d.ts +360 -6
  25. package/dist/index.js +317 -6
  26. package/dist/index.js.map +1 -1
  27. package/dist/schemas.cjs +3 -3
  28. package/dist/schemas.d.cts +2 -2
  29. package/dist/schemas.d.ts +2 -2
  30. package/dist/schemas.js +2 -2
  31. package/dist/scoring.cjs +3 -3
  32. package/dist/scoring.d.cts +2 -2
  33. package/dist/scoring.d.ts +2 -2
  34. package/dist/scoring.js +2 -2
  35. package/dist/xapi.cjs +3 -3
  36. package/dist/xapi.d.cts +1 -1
  37. package/dist/xapi.d.ts +1 -1
  38. package/dist/xapi.js +2 -2
  39. package/package.json +1 -1
  40. package/dist/chunk-4JR3UXX6.cjs.map +0 -1
  41. package/dist/chunk-DUQVGLQ3.js.map +0 -1
  42. package/dist/chunk-FCM5VJBS.cjs.map +0 -1
  43. package/dist/chunk-LSHDNA2T.js.map +0 -1
  44. package/dist/chunk-NUCEUU4P.js.map +0 -1
  45. package/dist/chunk-SM5HUGYU.cjs.map +0 -1
  46. /package/dist/{chunk-WV5WQ3SZ.js.map → chunk-2SQ75JTE.js.map} +0 -0
package/dist/index.js CHANGED
@@ -10,14 +10,14 @@ import {
10
10
  outcomeFromGrade,
11
11
  roundGrade,
12
12
  score
13
- } from "./chunk-DUQVGLQ3.js";
13
+ } from "./chunk-NOBJYDOB.js";
14
14
  import {
15
15
  XAPIVerb,
16
16
  XAPI_VERB_DISPLAY,
17
17
  validateXAPIStatement,
18
18
  xAPIBuilder,
19
19
  xapiDefinitionFor
20
- } from "./chunk-WV5WQ3SZ.js";
20
+ } from "./chunk-2SQ75JTE.js";
21
21
  import {
22
22
  ItemGroupSchema,
23
23
  RedactedItemGroupSchema,
@@ -31,7 +31,7 @@ import {
31
31
  validateActivity,
32
32
  validateItemGroup,
33
33
  writtenResponseJsonSchema
34
- } from "./chunk-LSHDNA2T.js";
34
+ } from "./chunk-XL75ZZVM.js";
35
35
  import {
36
36
  ActivitySchemaError,
37
37
  BlankConfigSchema,
@@ -63,7 +63,63 @@ import {
63
63
  registerActivityType,
64
64
  registeredActivityTypes,
65
65
  writtenResponseType
66
- } from "./chunk-NUCEUU4P.js";
66
+ } from "./chunk-YCXIHFLG.js";
67
+
68
+ // src/content-hash.ts
69
+ function canonicalJson(value, seen = /* @__PURE__ */ new Set()) {
70
+ if (value === null) {
71
+ return "null";
72
+ }
73
+ if (typeof value === "number") {
74
+ return Number.isFinite(value) ? JSON.stringify(value === 0 ? 0 : value) : `"#${String(value)}"`;
75
+ }
76
+ if (typeof value === "string" || typeof value === "boolean") {
77
+ return JSON.stringify(value);
78
+ }
79
+ if (typeof value === "bigint") {
80
+ return `"#${value.toString()}n"`;
81
+ }
82
+ if (typeof value === "object") {
83
+ if (seen.has(value)) {
84
+ throw new Error(
85
+ "canonicalJson: the value contains a circular reference and cannot be fingerprinted."
86
+ );
87
+ }
88
+ seen.add(value);
89
+ try {
90
+ if (Array.isArray(value)) {
91
+ return `[${value.map((element) => element === void 0 ? "null" : canonicalJson(element, seen)).join(",")}]`;
92
+ }
93
+ const source = value;
94
+ const parts = [];
95
+ for (const key of Object.keys(source).sort()) {
96
+ const entry = source[key];
97
+ if (entry === void 0) {
98
+ continue;
99
+ }
100
+ parts.push(`${JSON.stringify(key)}:${canonicalJson(entry, seen)}`);
101
+ }
102
+ return `{${parts.join(",")}}`;
103
+ } finally {
104
+ seen.delete(value);
105
+ }
106
+ }
107
+ return "null";
108
+ }
109
+ var FNV_OFFSET = 14695981039346656037n;
110
+ var FNV_PRIME = 1099511628211n;
111
+ var MASK64 = (1n << 64n) - 1n;
112
+ function fingerprint(input) {
113
+ const bytes = new TextEncoder().encode(input);
114
+ let hash = FNV_OFFSET;
115
+ for (const byte of bytes) {
116
+ hash = (hash ^ BigInt(byte)) * FNV_PRIME & MASK64;
117
+ }
118
+ return hash.toString(16).padStart(16, "0");
119
+ }
120
+ function contentHash(value) {
121
+ return fingerprint(canonicalJson(value));
122
+ }
67
123
 
68
124
  // src/shuffle.ts
69
125
  function hashSeed(input) {
@@ -92,6 +148,23 @@ function seededShuffle(items, seed, options = {}) {
92
148
  function isItemGroup(entry) {
93
149
  return entry.type === "item-group";
94
150
  }
151
+ function keyOf(entry) {
152
+ const key = entry.slotKey;
153
+ if (key === void 0) {
154
+ return void 0;
155
+ }
156
+ if (typeof key !== "string" || key.length === 0) {
157
+ throw new Error(
158
+ `flattenSequence: slotKey must be a non-empty string, received ${String(key)}.`
159
+ );
160
+ }
161
+ if (key.includes(".")) {
162
+ throw new Error(
163
+ `flattenSequence: slotKey "${key}" contains a "." , which separates a group from its item in a slot id. Choose a key without it, or the two become indistinguishable.`
164
+ );
165
+ }
166
+ return key;
167
+ }
95
168
  function flattenSequence(entries, options = {}) {
96
169
  const shuffleEntries = options.shuffleEntries === true;
97
170
  const needsSeed = shuffleEntries || entries.some((entry) => isItemGroup(entry) && entry.shuffle === "within-group");
@@ -105,8 +178,9 @@ function flattenSequence(entries, options = {}) {
105
178
  const ordered = shuffleEntries ? seededShuffle(authored, `${seed}:entries`) : authored;
106
179
  const slots = [];
107
180
  for (const { entry, entryIndex } of ordered) {
181
+ const entryKey = keyOf(entry) ?? String(entryIndex);
108
182
  if (!isItemGroup(entry)) {
109
- slots.push({ slotId: String(entryIndex), index: slots.length, activity: entry });
183
+ slots.push({ slotId: entryKey, index: slots.length, activity: entry });
110
184
  continue;
111
185
  }
112
186
  if (entry.items.length === 0) {
@@ -119,7 +193,7 @@ function flattenSequence(entries, options = {}) {
119
193
  const size = presented.length;
120
194
  presented.forEach(({ item, itemIndex }, position) => {
121
195
  slots.push({
122
- slotId: `${entryIndex}.${itemIndex}`,
196
+ slotId: `${entryKey}.${keyOf(item) ?? String(itemIndex)}`,
123
197
  index: slots.length,
124
198
  activity: item,
125
199
  group: {
@@ -132,9 +206,234 @@ function flattenSequence(entries, options = {}) {
132
206
  });
133
207
  });
134
208
  }
209
+ const seenSlotIds = /* @__PURE__ */ new Set();
210
+ const seenEntryKeys = /* @__PURE__ */ new Set();
211
+ for (const slot of slots) {
212
+ if (seenSlotIds.has(slot.slotId)) {
213
+ throw new Error(
214
+ `flattenSequence: duplicate slot id "${slot.slotId}". Two entries declare the same slotKey, so responses stored against them could not be told apart.`
215
+ );
216
+ }
217
+ seenSlotIds.add(slot.slotId);
218
+ }
219
+ for (const { entry, entryIndex } of ordered) {
220
+ const entryKey = keyOf(entry) ?? String(entryIndex);
221
+ if (seenEntryKeys.has(entryKey)) {
222
+ throw new Error(
223
+ `flattenSequence: duplicate entry key "${entryKey}". A loose activity and an item group cannot share a slotKey \u2014 their slot ids would not collide, but everything that reads the entry they belong to would treat them as one entry.`
224
+ );
225
+ }
226
+ seenEntryKeys.add(entryKey);
227
+ }
135
228
  return slots;
136
229
  }
137
230
 
231
+ // src/attempt-plan.ts
232
+ function contentOf(activity) {
233
+ if (!Object.hasOwn(activity, "slotKey")) {
234
+ return activity;
235
+ }
236
+ const { slotKey: _slotKey, ...content } = activity;
237
+ return content;
238
+ }
239
+ function planSlot(slot, points) {
240
+ if (!Number.isFinite(points) || points < 0) {
241
+ throw new Error(
242
+ `planAttempt: slot "${slot.slotId}" resolved to ${String(points)} points. Points must be a finite, non-negative number, or the paper has no defensible total.`
243
+ );
244
+ }
245
+ return {
246
+ slotId: slot.slotId,
247
+ index: slot.index,
248
+ activityId: slot.activity.id,
249
+ activityType: slot.activity.type,
250
+ points,
251
+ contentHash: contentHash(contentOf(slot.activity)),
252
+ ...slot.group !== void 0 ? {
253
+ group: {
254
+ id: slot.group.id,
255
+ ...slot.group.title !== void 0 ? { title: slot.group.title } : {},
256
+ stimulusHash: contentHash(slot.group.stimulus)
257
+ }
258
+ } : {}
259
+ };
260
+ }
261
+ function planAttempt(entries, options = {}) {
262
+ const { seed, shuffleEntries, points } = options;
263
+ const slots = flattenSequence(entries, {
264
+ ...shuffleEntries !== void 0 ? { shuffleEntries } : {},
265
+ ...seed !== void 0 ? { seed } : {}
266
+ });
267
+ const planned = slots.map((slot) => planSlot(slot, points?.(slot) ?? 1));
268
+ const totalPoints = planned.reduce((sum, slot) => sum + slot.points, 0);
269
+ return {
270
+ planVersion: "1.0",
271
+ ...seed !== void 0 ? { seed } : {},
272
+ ...shuffleEntries !== void 0 ? { shuffleEntries } : {},
273
+ // The plan's own fingerprint covers the slots verbatim — identity, order,
274
+ // points and content hashes — so one stored value answers "is this still
275
+ // the paper that was sat?" and the per-slot hashes then say what moved.
276
+ planHash: contentHash(planned),
277
+ slots: planned,
278
+ totalPoints
279
+ };
280
+ }
281
+ function verifyAttemptPlan(plan, current) {
282
+ const before = new Map(plan.slots.map((slot) => [slot.slotId, slot]));
283
+ const after = new Map(current.slots.map((slot) => [slot.slotId, slot]));
284
+ const missingSlotIds = plan.slots.filter((s) => !after.has(s.slotId)).map((s) => s.slotId);
285
+ const addedSlotIds = current.slots.filter((s) => !before.has(s.slotId)).map((s) => s.slotId);
286
+ const changedSlotIds = [];
287
+ const changedStimulusSlotIds = [];
288
+ const changedPointsSlotIds = [];
289
+ const reorderedSlotIds = [];
290
+ for (const slot of plan.slots) {
291
+ const now = after.get(slot.slotId);
292
+ if (now === void 0) {
293
+ continue;
294
+ }
295
+ if (now.contentHash !== slot.contentHash) {
296
+ changedSlotIds.push(slot.slotId);
297
+ }
298
+ if (now.group?.stimulusHash !== slot.group?.stimulusHash) {
299
+ changedStimulusSlotIds.push(slot.slotId);
300
+ }
301
+ if (now.points !== slot.points) {
302
+ changedPointsSlotIds.push(slot.slotId);
303
+ }
304
+ if (now.index !== slot.index) {
305
+ reorderedSlotIds.push(slot.slotId);
306
+ }
307
+ }
308
+ return {
309
+ matches: missingSlotIds.length === 0 && addedSlotIds.length === 0 && changedSlotIds.length === 0 && changedStimulusSlotIds.length === 0 && changedPointsSlotIds.length === 0 && reorderedSlotIds.length === 0,
310
+ missingSlotIds,
311
+ addedSlotIds,
312
+ changedSlotIds,
313
+ changedStimulusSlotIds,
314
+ changedPointsSlotIds,
315
+ reorderedSlotIds
316
+ };
317
+ }
318
+ function missingOutcome(slot, policy) {
319
+ if (typeof policy === "function") {
320
+ return policy(slot);
321
+ }
322
+ if (policy === "zero") {
323
+ return { status: "scored", score: 0, maxScore: 1, passed: false, feedback: null, details: [] };
324
+ }
325
+ return { status: "deferred", reason: "no_response_recorded", maxScore: 1 };
326
+ }
327
+ function scoredItemsFromPlan(plan, outcomes, options = {}) {
328
+ const policy = options.missing ?? "deferred";
329
+ return plan.slots.map((slot) => ({
330
+ slotId: slot.slotId,
331
+ activityId: slot.activityId,
332
+ points: slot.points,
333
+ // `Object.hasOwn`, not a bare lookup: slot ids come from authored
334
+ // `slotKey`s, and a key of `constructor` or `toString` would otherwise
335
+ // resolve through the prototype chain and hand a FUNCTION to the scorer
336
+ // in place of an outcome.
337
+ outcome: Object.hasOwn(outcomes, slot.slotId) ? outcomes[slot.slotId] : missingOutcome(slot, policy)
338
+ }));
339
+ }
340
+
341
+ // src/attempt-state.ts
342
+ function cloneResponses(responses) {
343
+ return typeof structuredClone === "function" ? structuredClone(responses) : JSON.parse(JSON.stringify(responses));
344
+ }
345
+ function unknownKeys(plan, keys) {
346
+ const known = new Set(plan.slots.map((slot) => slot.slotId));
347
+ return keys.filter((key) => !known.has(key));
348
+ }
349
+ function serializeAttemptState(plan, progress) {
350
+ const responseKeys = Object.keys(progress.responses);
351
+ const submittedSlotIds = [...progress.submittedSlotIds ?? []];
352
+ const strayResponses = unknownKeys(plan, responseKeys);
353
+ if (strayResponses.length > 0) {
354
+ throw new Error(
355
+ `serializeAttemptState: response recorded for slot(s) the plan does not contain: ${strayResponses.join(", ")}. A response that belongs to no question cannot be scored and would be lost silently.`
356
+ );
357
+ }
358
+ const straySubmitted = unknownKeys(plan, submittedSlotIds);
359
+ if (straySubmitted.length > 0) {
360
+ throw new Error(
361
+ `serializeAttemptState: submitted slot(s) the plan does not contain: ${straySubmitted.join(", ")}.`
362
+ );
363
+ }
364
+ const index = progress.index ?? 0;
365
+ const lastIndex = Math.max(0, plan.slots.length - 1);
366
+ if (!Number.isInteger(index) || index < 0 || index > lastIndex) {
367
+ throw new Error(
368
+ `serializeAttemptState: index ${String(index)} is not a position in a ${plan.slots.length}-slot plan.`
369
+ );
370
+ }
371
+ return {
372
+ stateVersion: "1.0",
373
+ planHash: plan.planHash,
374
+ // Copied DEEPLY, not aliased: a snapshot that keeps mutating with the
375
+ // live attempt is not a snapshot. See cloneResponses.
376
+ responses: cloneResponses(progress.responses),
377
+ submittedSlotIds,
378
+ index,
379
+ ...progress.savedAt !== void 0 ? { savedAt: progress.savedAt } : {}
380
+ };
381
+ }
382
+ function restoreAttemptState(plan, state) {
383
+ if (state === null || typeof state !== "object") {
384
+ throw new Error("restoreAttemptState: the snapshot is not an object.");
385
+ }
386
+ if (state.stateVersion !== "1.0") {
387
+ throw new Error(
388
+ `restoreAttemptState: unsupported stateVersion ${JSON.stringify(state.stateVersion)}. This build understands "1.0"; a newer snapshot must be migrated before it is restored.`
389
+ );
390
+ }
391
+ if (state.responses === null || typeof state.responses !== "object") {
392
+ throw new Error(
393
+ "restoreAttemptState: the snapshot carries no responses object (a NULL column, or a partially written row)."
394
+ );
395
+ }
396
+ if (state.planHash !== plan.planHash) {
397
+ throw new Error(
398
+ `restoreAttemptState: this snapshot belongs to a different paper (snapshot ${state.planHash}, plan ${plan.planHash}). Restoring it would attach the learner's answers to questions they never saw.`
399
+ );
400
+ }
401
+ return serializeAttemptState(plan, {
402
+ responses: state.responses,
403
+ submittedSlotIds: state.submittedSlotIds,
404
+ index: state.index,
405
+ ...state.savedAt !== void 0 ? { savedAt: state.savedAt } : {}
406
+ });
407
+ }
408
+ function diffResponses(before, after) {
409
+ const slotIds = [.../* @__PURE__ */ new Set([...Object.keys(before.responses), ...Object.keys(after.responses)])];
410
+ slotIds.sort();
411
+ const entries = [];
412
+ for (const slotId of slotIds) {
413
+ const had = Object.hasOwn(before.responses, slotId);
414
+ const has = Object.hasOwn(after.responses, slotId);
415
+ const from = before.responses[slotId];
416
+ const to = after.responses[slotId];
417
+ if (had && !has) {
418
+ entries.push({ slotId, change: "removed", ...from !== void 0 ? { before: from } : {} });
419
+ continue;
420
+ }
421
+ if (!had && has) {
422
+ entries.push({ slotId, change: "added", ...to !== void 0 ? { after: to } : {} });
423
+ continue;
424
+ }
425
+ if (canonicalJson(from) !== canonicalJson(to)) {
426
+ entries.push({
427
+ slotId,
428
+ change: "changed",
429
+ ...from !== void 0 ? { before: from } : {},
430
+ ...to !== void 0 ? { after: to } : {}
431
+ });
432
+ }
433
+ }
434
+ return entries;
435
+ }
436
+
138
437
  // src/redact.ts
139
438
  function mergePolicy(base, overrides) {
140
439
  if (overrides === void 0) {
@@ -273,6 +572,9 @@ var ITEM_GROUP_FIELD_POLICY = {
273
572
  type: "public",
274
573
  id: "public",
275
574
  title: "public",
575
+ // See the note on the built-in activity policies: a slot key is identity,
576
+ // and identity has to cross the redaction boundary intact.
577
+ slotKey: "public",
276
578
  shuffle: "public",
277
579
  stimulus: STIMULUS_FIELD_POLICY
278
580
  };
@@ -374,14 +676,18 @@ export {
374
676
  XAPI_VERB_DISPLAY,
375
677
  assertRedacted,
376
678
  assertRedactedItemGroup,
679
+ canonicalJson,
377
680
  classifyBand,
378
681
  composeAssessmentScore,
379
682
  computePassThreshold,
683
+ contentHash,
380
684
  countWords,
381
685
  defineActivityType,
686
+ diffResponses,
382
687
  evaluate,
383
688
  fillInTheBlanksJsonSchema,
384
689
  fillInTheBlanksType,
690
+ fingerprint,
385
691
  flattenSequence,
386
692
  getActivityTypeDescriptor,
387
693
  gradeFromRubric,
@@ -396,17 +702,22 @@ export {
396
702
  multipleChoiceJsonSchema,
397
703
  multipleChoiceType,
398
704
  outcomeFromGrade,
705
+ planAttempt,
399
706
  redact,
400
707
  redactItemGroup,
401
708
  registerActivityType,
402
709
  registeredActivityTypes,
710
+ restoreAttemptState,
403
711
  roundGrade,
404
712
  score,
713
+ scoredItemsFromPlan,
405
714
  seededShuffle,
715
+ serializeAttemptState,
406
716
  stimulusJsonSchema,
407
717
  validateActivity,
408
718
  validateItemGroup,
409
719
  validateXAPIStatement,
720
+ verifyAttemptPlan,
410
721
  writtenResponseJsonSchema,
411
722
  writtenResponseType,
412
723
  xAPIBuilder,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shuffle.ts","../src/item-group.ts","../src/redact.ts"],"sourcesContent":["/**\n * Seeded, deterministic shuffling — the ONE algorithm every presentation-order\n * decision in the SDK goes through: option order in a multiple-choice item,\n * item order inside an item group, entry order in a sequence. A server and a\n * client holding the same seed derive the same order, and an order recorded\n * against an attempt can be rebuilt later from nothing but its seed.\n *\n * STABILITY: the hash and the generator are part of the wire contract. A\n * stored attempt may hold only a seed and rely on this function to reproduce\n * the order it presented; changing either would silently re-order every\n * recorded attempt. Any change here is a package major, and the pinned\n * permutation test exists so an accidental one fails loudly.\n */\n\n/** FNV-1a hash of a string → unsigned 32-bit integer. */\nexport function hashSeed(input: string): number {\n let h = 2166136261 >>> 0;\n for (let i = 0; i < input.length; i += 1) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 16777619) >>> 0;\n }\n return h;\n}\n\n/**\n * Which draw the Fisher–Yates step uses.\n *\n * - `1` — the original. Takes the index from the LCG's LOW bits (`s % (i+1)`).\n * - `2` — takes it from the HIGH bits. Same LCG, same seed, different draw.\n *\n * The difference is not cosmetic. In a linear congruential generator with a\n * power-of-two modulus, the low bits have drastically short periods: bit 0\n * alternates, bit 1 has period 4, and so on. `% (i+1)` reads exactly those\n * bits, so consecutive draws are correlated and most permutations become\n * unreachable FOR EVERY SEED THAT WILL EVER EXIST:\n *\n * | items | permutations | reachable under v1 | under v2 |\n * | ----- | ------------ | ------------------ | -------- |\n * | 4 | 24 | 12 | 24 |\n * | 5 | 120 | 60 | 120 |\n * | 6 | 720 | 180 | 720 |\n *\n * It also biases WHERE an option lands. On a four-option item under v1 the\n * last authored option takes the first presented position 8.3% of the time\n * and the second position 41.7%, against 25% each — a systematic advantage to\n * anyone who notices. For a summative exam that is a fairness defect, not a\n * curiosity.\n *\n * v1 remains the DEFAULT regardless, because these permutations are a wire\n * contract: an attempt may be stored with nothing but its seed, and a review\n * render of that attempt has to reproduce the order the learner actually saw.\n * Switching the default would silently re-order every recorded attempt, so it\n * is a package major — scheduled, not smuggled in. Choose v2 for new content\n * where no attempt has been recorded yet.\n */\nexport type ShuffleVersion = 1 | 2;\n\n/** Options for {@link seededShuffle}. */\nexport interface SeededShuffleOptions {\n /** Draw algorithm. Defaults to `1` — see {@link ShuffleVersion}. */\n version?: ShuffleVersion;\n}\n\n/** LCG-driven Fisher–Yates over a 32-bit seed; returns a permutation (no loss, no duplicate). */\nfunction shuffleWithSeed<T>(items: readonly T[], seed: number, version: ShuffleVersion): T[] {\n const out = [...items];\n let s = seed >>> 0 || 1;\n for (let i = out.length - 1; i > 0; i -= 1) {\n s = (Math.imul(s, 1664525) + 1013904223) >>> 0;\n // v1 reads the low bits; v2 scales the whole 32-bit word, which uses the\n // high bits and reaches every permutation.\n const j = version === 2 ? Math.floor((s / 4294967296) * (i + 1)) : s % (i + 1);\n [out[i], out[j]] = [out[j] as T, out[i] as T];\n }\n return out;\n}\n\n/**\n * Returns a new array holding a permutation of `items` determined entirely by\n * `seed` (and the chosen {@link ShuffleVersion}): same inputs, same order —\n * across processes, runtimes and releases. The input is never mutated.\n *\n * Compose the seed from the attempt identity AND the thing being shuffled\n * (`${attemptId}:${itemId}`), so two shuffles in one attempt do not share an\n * order.\n */\nexport function seededShuffle<T>(\n items: readonly T[],\n seed: string,\n options: SeededShuffleOptions = {},\n): T[] {\n return shuffleWithSeed(items, hashSeed(seed), options.version ?? 1);\n}\n","import { seededShuffle } from './shuffle.js';\nimport type { ItemGroup, SequenceEntry, SequenceSlot } from './types/item-group.js';\n\n/** Narrows a sequence entry to an item group. */\nexport function isItemGroup<TItem extends { type: string }>(\n entry: SequenceEntry<TItem>,\n): entry is ItemGroup<TItem> {\n return entry.type === 'item-group';\n}\n\n/** Options for {@link flattenSequence}. */\nexport interface FlattenSequenceOptions {\n /**\n * Shuffle the top-level entries. A group moves as ONE block — its items are\n * never interleaved with other entries — which is the reason a group exists\n * as a container rather than as a flag on each item.\n */\n shuffleEntries?: boolean;\n /**\n * Seed for every shuffle in this call: the entries, and each group whose\n * `shuffle` is `within-group`. REQUIRED whenever anything shuffles. The SDK\n * never invents one, because the server that stores an attempt and the\n * client that renders it must derive the SAME order, and only a shared seed\n * makes that true. The attempt id is the natural choice.\n */\n seed?: string;\n}\n\n/**\n * Turns a sequence definition — loose activities and item groups, in authored\n * order — into the ordered list of slots to present. Pure and deterministic:\n * call it on the server to record an attempt's order, and on the client to\n * render it, and the two agree.\n *\n * Shuffling is opt-in and seeded. Groups are shuffle-atomic: with\n * `shuffleEntries` a group changes position but stays one contiguous block,\n * and only a group that declares `shuffle: 'within-group'` has its items\n * reordered. Every slot carries a `slotId` derived from the authored\n * position, so identities survive shuffling.\n *\n * @throws Error when a shuffle is requested without a `seed`.\n */\nexport function flattenSequence<TItem extends { id: string; type: string }>(\n entries: readonly SequenceEntry<TItem>[],\n options: FlattenSequenceOptions = {},\n): SequenceSlot<TItem>[] {\n const shuffleEntries = options.shuffleEntries === true;\n const needsSeed =\n shuffleEntries ||\n entries.some((entry) => isItemGroup(entry) && entry.shuffle === 'within-group');\n if (needsSeed && options.seed === undefined) {\n throw new Error(\n 'flattenSequence: a seed is required when shuffling (shuffleEntries, or a group with ' +\n 'shuffle: \"within-group\"). Pass the attempt id so the server and the client derive the same order.',\n );\n }\n const seed = options.seed ?? '';\n\n // Carry the AUTHORED index through the shuffle: slot identity comes from\n // where an entry was written, never from where it happens to be shown.\n const authored = entries.map((entry, entryIndex) => ({ entry, entryIndex }));\n const ordered = shuffleEntries ? seededShuffle(authored, `${seed}:entries`) : authored;\n\n const slots: SequenceSlot<TItem>[] = [];\n for (const { entry, entryIndex } of ordered) {\n if (!isItemGroup(entry)) {\n slots.push({ slotId: String(entryIndex), index: slots.length, activity: entry });\n continue;\n }\n // An empty group contributes no slots, so it would DISAPPEAR — stimulus,\n // questions and all — from a sequence that still looks well-formed. A\n // listening section filtered to nothing upstream would leave an 18-slot\n // paper presented as 12 slots, and `composeAssessmentScore` would then\n // report a `final` grade over the survivors with nothing pending. The\n // type already declares `items` non-empty; this makes that enforceable at\n // the point where the omission would otherwise become invisible.\n if (entry.items.length === 0) {\n throw new Error(\n `flattenSequence: item group \"${entry.id}\" has no items. An empty group would silently ` +\n 'remove its stimulus and its questions from the presented sequence.',\n );\n }\n const items = entry.items.map((item, itemIndex) => ({ item, itemIndex }));\n const presented =\n entry.shuffle === 'within-group' ? seededShuffle(items, `${seed}:group:${entry.id}`) : items;\n const size = presented.length;\n presented.forEach(({ item, itemIndex }, position) => {\n slots.push({\n slotId: `${entryIndex}.${itemIndex}`,\n index: slots.length,\n activity: item,\n group: {\n id: entry.id,\n ...(entry.title !== undefined ? { title: entry.title } : {}),\n stimulus: entry.stimulus,\n position,\n size,\n },\n });\n });\n }\n return slots;\n}\n","import { ActivitySchemaError, UnknownActivityTypeError } from './errors.js';\nimport { getActivityTypeDescriptor } from './registry/index.js';\nimport type { FieldPolicy, Sensitivity } from './registry/registry.js';\nimport { RedactedItemGroupSchema } from './schemas/item-group.js';\nimport type { ItemGroup } from './types/item-group.js';\n\n/**\n * A learner-safe projection of activity data produced by {@link redact}:\n * the activity's public fields plus the `redacted: true` marker. Renderable\n * and validatable (each built-in type registers a strict redacted schema),\n * but stripped of the answer key, scoring rules, authored feedback, and\n * author-only assets.\n */\nexport interface RedactedActivityData {\n redacted: true;\n schemaVersion: string;\n type: string;\n id: string;\n title: string;\n [key: string]: unknown;\n}\n\n/** Options for {@link redact}. */\nexport interface RedactOptions {\n /**\n * Which sensitivity tiers to keep beyond `public`:\n * - `'none'` (default) — public fields only; the output satisfies the\n * type's strict redacted schema and `assertRedacted`.\n * - `'after-submit'` — public + answer-key fields (for post-submission\n * review renders). `author-only` fields and unclassified fields are\n * STILL removed; the output will NOT pass `assertRedacted`.\n */\n reveal?: 'none' | 'after-submit';\n /**\n * Per-call sensitivity overrides, merged over the type's registered\n * `fieldPolicy` (top-level keys replace; nested objects merge one level).\n *\n * Sensitivity is partly a PEDAGOGICAL decision, not purely a security one —\n * whether a rubric or a hint is learner-visible differs legitimately between\n * deployments — and the SDK must not freeze that choice. Use this to tighten\n * a field the SDK ships as `public`:\n *\n * ```ts\n * redact(essay, { policy: { rubric: 'author-only' } });\n * ```\n *\n * Overrides can only be applied to fields; they cannot re-open a field the\n * caller has not classified, because unclassified still means removed.\n * Note that tightening below what the type's `redactedSchema` requires is\n * allowed — the schema check only rejects payloads that reveal MORE than\n * the learner-safe shape.\n */\n policy?: FieldPolicy;\n}\n\n/** Merges per-call overrides over a registered policy, one level deep. */\nfunction mergePolicy(base: FieldPolicy, overrides: FieldPolicy | undefined): FieldPolicy {\n if (overrides === undefined) {\n return base;\n }\n const merged: Record<string, Sensitivity | FieldPolicy> = { ...base };\n for (const [key, override] of Object.entries(overrides)) {\n const current = merged[key];\n merged[key] =\n typeof override === 'object' && typeof current === 'object'\n ? { ...current, ...override }\n : override;\n }\n return merged;\n}\n\nfunction isSensitivity(value: Sensitivity | FieldPolicy): value is Sensitivity {\n return typeof value === 'string';\n}\n\nfunction keepField(sensitivity: Sensitivity, reveal: 'none' | 'after-submit'): boolean {\n if (sensitivity === 'public') {\n return true;\n }\n return sensitivity === 'answer-key' && reveal === 'after-submit';\n}\n\nfunction redactValue(\n value: unknown,\n policy: FieldPolicy,\n reveal: 'none' | 'after-submit',\n): unknown {\n if (Array.isArray(value)) {\n return value.map((element) => redactValue(element, policy, reveal));\n }\n if (value === null || typeof value !== 'object') {\n // A nested FieldPolicy cannot classify a primitive's sub-fields; the\n // policy author classified an object shape that is not there. Fail\n // closed: drop it (handled by the caller returning undefined).\n return undefined;\n }\n\n const source = value as Record<string, unknown>;\n const output: Record<string, unknown> = {};\n for (const [key, fieldValue] of Object.entries(source)) {\n if (fieldValue === undefined) {\n continue;\n }\n const classification = policy[key];\n if (classification === undefined) {\n // Fail closed: unclassified fields are never emitted, at any reveal\n // level. Adding a field without classifying it hides it — never leaks it.\n continue;\n }\n if (isSensitivity(classification)) {\n if (keepField(classification, reveal)) {\n output[key] = fieldValue;\n }\n continue;\n }\n const nested = redactValue(fieldValue, classification, reveal);\n if (nested !== undefined) {\n output[key] = nested;\n }\n }\n return output;\n}\n\n/**\n * Produces the learner-safe projection of activity data (R7), driven by the\n * `fieldPolicy` registered for `data.type`. Fail-closed and exhaustive by\n * construction: a field the policy does not classify is removed — including\n * unknown passthrough fields — so a NEW field added by a future SDK or a\n * consumer sidecar can never leak through an out-of-date redactor.\n *\n * With the default `reveal: 'none'`, the output validates against the type's\n * strict redacted schema (verified here; an invalid projection throws\n * {@link ActivitySchemaError} rather than shipping an unproven payload).\n *\n * @throws UnknownActivityTypeError when `data.type` is not registered.\n * @throws Error when the registered descriptor declares no `fieldPolicy`\n * (redaction cannot guess sensitivities).\n */\nexport function redact<T extends { type: string }>(\n data: T,\n options: RedactOptions = {},\n): RedactedActivityData {\n const reveal = options.reveal ?? 'none';\n const descriptor = getActivityTypeDescriptor(data.type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(data.type));\n }\n if (descriptor.fieldPolicy === undefined) {\n throw new Error(\n `Activity type \"${descriptor.type}\" has no fieldPolicy; redact() cannot run fail-closed redaction without one.`,\n );\n }\n\n const effectivePolicy = mergePolicy(descriptor.fieldPolicy, options.policy);\n const projected = redactValue(data, effectivePolicy, reveal) as Record<string, unknown>;\n const result = { ...projected, redacted: true as const } as RedactedActivityData;\n\n if (reveal === 'none' && descriptor.redactedSchema !== undefined) {\n const parsed = descriptor.redactedSchema.safeParse(result);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n descriptor.type,\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n }\n\n return result;\n}\n\n/**\n * Asserts that `data` is a learner-safe redacted projection: it carries the\n * `redacted: true` marker and, when its type registers a strict redacted\n * schema, validates against it (proving the absence of answer-key fields).\n * Use this at the server boundary before sending activity data to a client\n * that must not hold the key.\n */\nexport function assertRedacted(data: unknown): asserts data is RedactedActivityData {\n if (typeof data !== 'object' || data === null) {\n throw new ActivitySchemaError('unknown', [\n { path: [], message: 'Redacted activity data must be an object.', code: 'invalid_type' },\n ]);\n }\n const candidate = data as Record<string, unknown>;\n if (candidate.redacted !== true) {\n throw new ActivitySchemaError(String(candidate.type ?? 'unknown'), [\n {\n path: ['redacted'],\n message: 'Missing redacted marker — this payload is not a redact() projection.',\n code: 'custom',\n },\n ]);\n }\n const type = typeof candidate.type === 'string' ? candidate.type : '';\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(type);\n }\n if (descriptor.redactedSchema === undefined) {\n // Fail closed: without a registered redacted schema there is no way to\n // PROVE the absence of answer-key fields, and a marker alone proves\n // nothing (any object can carry `redacted: true`).\n throw new ActivitySchemaError(descriptor.type, [\n {\n path: [],\n message: `Activity type \"${descriptor.type}\" registers no redactedSchema; assertRedacted cannot prove this payload is learner-safe.`,\n code: 'custom',\n },\n ]);\n }\n const parsed = descriptor.redactedSchema.safeParse(candidate);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n descriptor.type,\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n}\n\n/**\n * Sensitivity of a stimulus. Everything is learner-visible — that is what a\n * stimulus IS — except the author transcript. Fail-closed like every other\n * policy: a field added to `Stimulus` without a classification here is\n * dropped, never leaked.\n */\nconst STIMULUS_FIELD_POLICY: FieldPolicy = {\n id: 'public',\n kind: 'public',\n title: 'public',\n body: 'public',\n bodyHtml: 'public',\n media: 'public',\n locale: 'public',\n attribution: 'public',\n transcript: 'author-only',\n};\n\n/** The group container's own fields. `items` is handled separately, per item type. */\nconst ITEM_GROUP_FIELD_POLICY: FieldPolicy = {\n schemaVersion: 'public',\n type: 'public',\n id: 'public',\n title: 'public',\n shuffle: 'public',\n stimulus: STIMULUS_FIELD_POLICY,\n};\n\n/** A learner-safe item group: the container with its marker, holding `redact()` projections. */\nexport type RedactedItemGroup = ItemGroup<RedactedActivityData> & { redacted: true };\n\n/**\n * Produces the learner-safe projection of an item group: the container and\n * stimulus under their own fail-closed policy (the author transcript goes;\n * the passage, media and attribution stay — the learner is meant to see\n * them), and every item through {@link redact} with the same `options`, so\n * a per-call `policy` tightens each item exactly as it would alone.\n *\n * With the default `reveal: 'none'` the container is verified against the\n * strict redacted schema; each item was already verified by `redact`.\n */\nexport function redactItemGroup<TItem extends { type: string }>(\n group: ItemGroup<TItem>,\n options: RedactOptions = {},\n): RedactedItemGroup {\n const reveal = options.reveal ?? 'none';\n const { items, ...container } = group;\n const projected = redactValue(container, ITEM_GROUP_FIELD_POLICY, reveal) as Record<\n string,\n unknown\n >;\n const result = {\n ...projected,\n items: items.map((item) => redact(item, options)),\n redacted: true as const,\n } as RedactedItemGroup;\n\n if (reveal === 'none') {\n const parsed = RedactedItemGroupSchema.safeParse(result);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n 'item-group',\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n }\n return result;\n}\n\n/**\n * Asserts that `data` is a learner-safe item group: it carries the marker,\n * its container and stimulus satisfy the strict redacted schema (so no\n * transcript, no unclassified field), and EVERY item passes\n * {@link assertRedacted} against its own type's redacted schema. Item\n * failures are reported at `items.<index>.…`. Use it at the server boundary\n * before sending a group to a client that must not hold the key.\n */\nexport function assertRedactedItemGroup(data: unknown): asserts data is RedactedItemGroup {\n if (typeof data !== 'object' || data === null) {\n throw new ActivitySchemaError('item-group', [\n { path: [], message: 'Redacted item group must be an object.', code: 'invalid_type' },\n ]);\n }\n const candidate = data as Record<string, unknown>;\n if (candidate.redacted !== true) {\n throw new ActivitySchemaError('item-group', [\n {\n path: ['redacted'],\n message: 'Missing redacted marker — this payload is not a redactItemGroup() projection.',\n code: 'custom',\n },\n ]);\n }\n const parsed = RedactedItemGroupSchema.safeParse(candidate);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n 'item-group',\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n parsed.data.items.forEach((item, index) => {\n try {\n assertRedacted(item);\n } catch (error) {\n if (error instanceof ActivitySchemaError) {\n throw new ActivitySchemaError(\n 'item-group',\n error.errors.map((issue) => ({\n ...issue,\n path: ['items', String(index), ...issue.path],\n })),\n );\n }\n throw error;\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,SAAS,SAAS,OAAuB;AAC9C,MAAI,IAAI,eAAe;AACvB,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,GAAG;AACxC,SAAK,MAAM,WAAW,CAAC;AACvB,QAAI,KAAK,KAAK,GAAG,QAAQ,MAAM;AAAA,EACjC;AACA,SAAO;AACT;AA0CA,SAAS,gBAAmB,OAAqB,MAAc,SAA8B;AAC3F,QAAM,MAAM,CAAC,GAAG,KAAK;AACrB,MAAI,IAAI,SAAS,KAAK;AACtB,WAAS,IAAI,IAAI,SAAS,GAAG,IAAI,GAAG,KAAK,GAAG;AAC1C,QAAK,KAAK,KAAK,GAAG,OAAO,IAAI,eAAgB;AAG7C,UAAM,IAAI,YAAY,IAAI,KAAK,MAAO,IAAI,cAAe,IAAI,EAAE,IAAI,KAAK,IAAI;AAC5E,KAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAQ,IAAI,CAAC,CAAM;AAAA,EAC9C;AACA,SAAO;AACT;AAWO,SAAS,cACd,OACA,MACA,UAAgC,CAAC,GAC5B;AACL,SAAO,gBAAgB,OAAO,SAAS,IAAI,GAAG,QAAQ,WAAW,CAAC;AACpE;;;ACxFO,SAAS,YACd,OAC2B;AAC3B,SAAO,MAAM,SAAS;AACxB;AAkCO,SAAS,gBACd,SACA,UAAkC,C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AAA,YAC3B,GAAG;AAAA,YACH,MAAM,CAAC,SAAS,OAAO,KAAK,GAAG,GAAG,MAAM,IAAI;AAAA,UAC9C,EAAE;AAAA,QACJ;AAAA,MACF;AACA,YAAM;AAAA,IACR;AAAA,EACF,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/content-hash.ts","../src/shuffle.ts","../src/item-group.ts","../src/attempt-plan.ts","../src/attempt-state.ts","../src/redact.ts"],"sourcesContent":["/**\n * Content fingerprinting — \"is this the same content the learner was served?\"\n *\n * A recorded attempt outlives the content it was taken against. Papers get\n * corrected, a typo is fixed, an option is reworded — and six months later a\n * remark, an appeal, or a per-item analysis is run against content that is no\n * longer what the learner saw. Nothing warns anybody, because the ids all still\n * match. A fingerprint stored with the attempt turns that silent drift into a\n * question somebody can answer.\n */\n\n/**\n * Deterministic JSON: object keys sorted, arrays left in order, `undefined`\n * omitted from objects (matching `JSON.stringify`) and rendered as `null`\n * inside arrays.\n *\n * Key order is the whole point. Two objects that differ only in the order\n * their keys happened to be written are the SAME content, and a fingerprint\n * that disagreed would raise a false alarm every time a payload made a\n * round-trip through a different serializer.\n */\nexport function canonicalJson(value: unknown, seen: Set<object> = new Set()): string {\n if (value === null) {\n return 'null';\n }\n if (typeof value === 'number') {\n // JSON.stringify renders every non-finite number as `null`, which would\n // fingerprint NaN, Infinity and -Infinity identically — and identically to\n // a real null. Content carrying one of those is already broken; it must at\n // least be distinguishable.\n return Number.isFinite(value) ? JSON.stringify(value === 0 ? 0 : value) : `\"#${String(value)}\"`;\n }\n if (typeof value === 'string' || typeof value === 'boolean') {\n return JSON.stringify(value);\n }\n if (typeof value === 'bigint') {\n return `\"#${value.toString()}n\"`;\n }\n if (typeof value === 'object') {\n // A cycle would recurse until the stack gave out, and a stack overflow\n // while fingerprinting an exam is a far worse failure than being told the\n // content is not serialisable. Content is JSON, so this should never fire —\n // but \"should never\" is not a guard.\n if (seen.has(value)) {\n throw new Error(\n 'canonicalJson: the value contains a circular reference and cannot be fingerprinted.',\n );\n }\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return `[${value.map((element) => (element === undefined ? 'null' : canonicalJson(element, seen))).join(',')}]`;\n }\n const source = value as Record<string, unknown>;\n const parts: string[] = [];\n for (const key of Object.keys(source).sort()) {\n const entry = source[key];\n if (entry === undefined) {\n continue;\n }\n parts.push(`${JSON.stringify(key)}:${canonicalJson(entry, seen)}`);\n }\n return `{${parts.join(',')}}`;\n } finally {\n // Released on the way out, so a value legitimately appearing twice in\n // SIBLING positions is not mistaken for a cycle.\n seen.delete(value);\n }\n }\n // Functions, symbols and undefined have no place in content.\n return 'null';\n}\n\nconst FNV_OFFSET = 14695981039346656037n;\nconst FNV_PRIME = 1099511628211n;\nconst MASK64 = (1n << 64n) - 1n;\n\n/**\n * FNV-1a over the UTF-8 bytes of `input`, as 16 lowercase hex digits.\n *\n * **This is a change-detection fingerprint, not a tamper-evident signature.**\n * It is deterministic across runtimes and dependency-free, which is what makes\n * it usable in a stored grade record — but an adversary who can edit content\n * can also, with effort, preserve the fingerprint. If you need the stronger\n * property, sign the plan with a key the content author does not hold; this\n * exists to catch honest edits, which is what actually happens.\n */\nexport function fingerprint(input: string): string {\n const bytes = new TextEncoder().encode(input);\n let hash = FNV_OFFSET;\n for (const byte of bytes) {\n hash = ((hash ^ BigInt(byte)) * FNV_PRIME) & MASK64;\n }\n return hash.toString(16).padStart(16, '0');\n}\n\n/**\n * Fingerprints any JSON-serialisable value through {@link canonicalJson}, so\n * the result depends on the content and not on how it was written.\n */\nexport function contentHash(value: unknown): string {\n return fingerprint(canonicalJson(value));\n}\n","/**\n * Seeded, deterministic shuffling — the ONE algorithm every presentation-order\n * decision in the SDK goes through: option order in a multiple-choice item,\n * item order inside an item group, entry order in a sequence. A server and a\n * client holding the same seed derive the same order, and an order recorded\n * against an attempt can be rebuilt later from nothing but its seed.\n *\n * STABILITY: the hash and the generator are part of the wire contract. A\n * stored attempt may hold only a seed and rely on this function to reproduce\n * the order it presented; changing either would silently re-order every\n * recorded attempt. Any change here is a package major, and the pinned\n * permutation test exists so an accidental one fails loudly.\n */\n\n/** FNV-1a hash of a string → unsigned 32-bit integer. */\nexport function hashSeed(input: string): number {\n let h = 2166136261 >>> 0;\n for (let i = 0; i < input.length; i += 1) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 16777619) >>> 0;\n }\n return h;\n}\n\n/**\n * Which draw the Fisher–Yates step uses.\n *\n * - `1` — the original. Takes the index from the LCG's LOW bits (`s % (i+1)`).\n * - `2` — takes it from the HIGH bits. Same LCG, same seed, different draw.\n *\n * The difference is not cosmetic. In a linear congruential generator with a\n * power-of-two modulus, the low bits have drastically short periods: bit 0\n * alternates, bit 1 has period 4, and so on. `% (i+1)` reads exactly those\n * bits, so consecutive draws are correlated and most permutations become\n * unreachable FOR EVERY SEED THAT WILL EVER EXIST:\n *\n * | items | permutations | reachable under v1 | under v2 |\n * | ----- | ------------ | ------------------ | -------- |\n * | 4 | 24 | 12 | 24 |\n * | 5 | 120 | 60 | 120 |\n * | 6 | 720 | 180 | 720 |\n *\n * It also biases WHERE an option lands. On a four-option item under v1 the\n * last authored option takes the first presented position 8.3% of the time\n * and the second position 41.7%, against 25% each — a systematic advantage to\n * anyone who notices. For a summative exam that is a fairness defect, not a\n * curiosity.\n *\n * v1 remains the DEFAULT regardless, because these permutations are a wire\n * contract: an attempt may be stored with nothing but its seed, and a review\n * render of that attempt has to reproduce the order the learner actually saw.\n * Switching the default would silently re-order every recorded attempt, so it\n * is a package major — scheduled, not smuggled in. Choose v2 for new content\n * where no attempt has been recorded yet.\n */\nexport type ShuffleVersion = 1 | 2;\n\n/** Options for {@link seededShuffle}. */\nexport interface SeededShuffleOptions {\n /** Draw algorithm. Defaults to `1` — see {@link ShuffleVersion}. */\n version?: ShuffleVersion;\n}\n\n/** LCG-driven Fisher–Yates over a 32-bit seed; returns a permutation (no loss, no duplicate). */\nfunction shuffleWithSeed<T>(items: readonly T[], seed: number, version: ShuffleVersion): T[] {\n const out = [...items];\n let s = seed >>> 0 || 1;\n for (let i = out.length - 1; i > 0; i -= 1) {\n s = (Math.imul(s, 1664525) + 1013904223) >>> 0;\n // v1 reads the low bits; v2 scales the whole 32-bit word, which uses the\n // high bits and reaches every permutation.\n const j = version === 2 ? Math.floor((s / 4294967296) * (i + 1)) : s % (i + 1);\n [out[i], out[j]] = [out[j] as T, out[i] as T];\n }\n return out;\n}\n\n/**\n * Returns a new array holding a permutation of `items` determined entirely by\n * `seed` (and the chosen {@link ShuffleVersion}): same inputs, same order —\n * across processes, runtimes and releases. The input is never mutated.\n *\n * Compose the seed from the attempt identity AND the thing being shuffled\n * (`${attemptId}:${itemId}`), so two shuffles in one attempt do not share an\n * order.\n */\nexport function seededShuffle<T>(\n items: readonly T[],\n seed: string,\n options: SeededShuffleOptions = {},\n): T[] {\n return shuffleWithSeed(items, hashSeed(seed), options.version ?? 1);\n}\n","import { seededShuffle } from './shuffle.js';\nimport type { ItemGroup, SequenceEntry, SequenceSlot } from './types/item-group.js';\n\n/** Narrows a sequence entry to an item group. */\nexport function isItemGroup<TItem extends { type: string }>(\n entry: SequenceEntry<TItem>,\n): entry is ItemGroup<TItem> {\n return entry.type === 'item-group';\n}\n\n/**\n * An entry's declared `slotKey`, if it has one. Read structurally rather than\n * from the type, because a plain activity may carry one too — `slotKey` is a\n * property of an item's PLACE in a paper, so any entry can declare it without\n * every activity schema having to know about assessment assembly.\n *\n * A key containing `.` is rejected: `.` separates a group from its item in a\n * slot id, so `\"a.b\"` as a group key would be indistinguishable from item `b`\n * of group `a`.\n */\nfunction keyOf(entry: unknown): string | undefined {\n const key = (entry as { slotKey?: unknown }).slotKey;\n if (key === undefined) {\n return undefined;\n }\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error(\n `flattenSequence: slotKey must be a non-empty string, received ${String(key)}.`,\n );\n }\n if (key.includes('.')) {\n throw new Error(\n `flattenSequence: slotKey \"${key}\" contains a \".\" , which separates a group from its item ` +\n 'in a slot id. Choose a key without it, or the two become indistinguishable.',\n );\n }\n return key;\n}\n\n/** Options for {@link flattenSequence}. */\nexport interface FlattenSequenceOptions {\n /**\n * Shuffle the top-level entries. A group moves as ONE block — its items are\n * never interleaved with other entries — which is the reason a group exists\n * as a container rather than as a flag on each item.\n */\n shuffleEntries?: boolean;\n /**\n * Seed for every shuffle in this call: the entries, and each group whose\n * `shuffle` is `within-group`. REQUIRED whenever anything shuffles. The SDK\n * never invents one, because the server that stores an attempt and the\n * client that renders it must derive the SAME order, and only a shared seed\n * makes that true. The attempt id is the natural choice.\n */\n seed?: string;\n}\n\n/**\n * Turns a sequence definition — loose activities and item groups, in authored\n * order — into the ordered list of slots to present. Pure and deterministic:\n * call it on the server to record an attempt's order, and on the client to\n * render it, and the two agree.\n *\n * Shuffling is opt-in and seeded. Groups are shuffle-atomic: with\n * `shuffleEntries` a group changes position but stays one contiguous block,\n * and only a group that declares `shuffle: 'within-group'` has its items\n * reordered. Every slot carries a `slotId` derived from the authored\n * position, so identities survive shuffling.\n *\n * @throws Error when a shuffle is requested without a `seed`.\n */\nexport function flattenSequence<TItem extends { id: string; type: string }>(\n entries: readonly SequenceEntry<TItem>[],\n options: FlattenSequenceOptions = {},\n): SequenceSlot<TItem>[] {\n const shuffleEntries = options.shuffleEntries === true;\n const needsSeed =\n shuffleEntries ||\n entries.some((entry) => isItemGroup(entry) && entry.shuffle === 'within-group');\n if (needsSeed && options.seed === undefined) {\n throw new Error(\n 'flattenSequence: a seed is required when shuffling (shuffleEntries, or a group with ' +\n 'shuffle: \"within-group\"). Pass the attempt id so the server and the client derive the same order.',\n );\n }\n const seed = options.seed ?? '';\n\n // Carry the AUTHORED index through the shuffle: slot identity comes from\n // where an entry was written, never from where it happens to be shown.\n const authored = entries.map((entry, entryIndex) => ({ entry, entryIndex }));\n const ordered = shuffleEntries ? seededShuffle(authored, `${seed}:entries`) : authored;\n\n const slots: SequenceSlot<TItem>[] = [];\n for (const { entry, entryIndex } of ordered) {\n // An authored `slotKey` wins over the positional path. A positional id is\n // only valid against ONE version of the entries array; a declared key\n // survives insertion, deletion and re-ordering, which is what makes a\n // stored slot id safe to re-grade against later.\n const entryKey = keyOf(entry) ?? String(entryIndex);\n if (!isItemGroup(entry)) {\n slots.push({ slotId: entryKey, index: slots.length, activity: entry });\n continue;\n }\n // An empty group contributes no slots, so it would DISAPPEAR — stimulus,\n // questions and all — from a sequence that still looks well-formed. A\n // listening section filtered to nothing upstream would leave an 18-slot\n // paper presented as 12 slots, and `composeAssessmentScore` would then\n // report a `final` grade over the survivors with nothing pending. The\n // type already declares `items` non-empty; this makes that enforceable at\n // the point where the omission would otherwise become invisible.\n if (entry.items.length === 0) {\n throw new Error(\n `flattenSequence: item group \"${entry.id}\" has no items. An empty group would silently ` +\n 'remove its stimulus and its questions from the presented sequence.',\n );\n }\n const items = entry.items.map((item, itemIndex) => ({ item, itemIndex }));\n const presented =\n entry.shuffle === 'within-group' ? seededShuffle(items, `${seed}:group:${entry.id}`) : items;\n const size = presented.length;\n presented.forEach(({ item, itemIndex }, position) => {\n slots.push({\n slotId: `${entryKey}.${keyOf(item) ?? String(itemIndex)}`,\n index: slots.length,\n activity: item,\n group: {\n id: entry.id,\n ...(entry.title !== undefined ? { title: entry.title } : {}),\n stimulus: entry.stimulus,\n position,\n size,\n },\n });\n });\n }\n\n // Positional ids are unique by construction; authored keys are not. Two\n // entries sharing a key would collapse into one identity, so every response\n // stored against it would overwrite the other's — and `composeAssessmentScore`\n // would score one question twice and the other never.\n const seenSlotIds = new Set<string>();\n // ENTRY keys are checked separately, because a loose entry keyed \"reading\"\n // and a group keyed \"reading\" produce slot ids \"reading\" and \"reading.0\"\n // that never collide — while everything reading the entry prefix (the\n // pager's stimulus grouping, for one) treats them as the same entry, and\n // shows the group's passage above the unrelated loose question. Positional\n // ids could not express this: an index is a loose item or a group, never\n // both.\n const seenEntryKeys = new Set<string>();\n for (const slot of slots) {\n if (seenSlotIds.has(slot.slotId)) {\n throw new Error(\n `flattenSequence: duplicate slot id \"${slot.slotId}\". Two entries declare the same ` +\n 'slotKey, so responses stored against them could not be told apart.',\n );\n }\n seenSlotIds.add(slot.slotId);\n }\n for (const { entry, entryIndex } of ordered) {\n const entryKey = keyOf(entry) ?? String(entryIndex);\n if (seenEntryKeys.has(entryKey)) {\n throw new Error(\n `flattenSequence: duplicate entry key \"${entryKey}\". A loose activity and an item group ` +\n 'cannot share a slotKey — their slot ids would not collide, but everything that reads ' +\n 'the entry they belong to would treat them as one entry.',\n );\n }\n seenEntryKeys.add(entryKey);\n }\n return slots;\n}\n","import { contentHash } from './content-hash.js';\nimport { flattenSequence } from './item-group.js';\nimport type { ScoredItem } from './scoring/compose.js';\nimport type { ActivityData, ItemOutcome } from './types/activity.js';\nimport type { AttemptPlan, AttemptPlanDrift, AttemptPlanSlot } from './types/attempt-plan.js';\nimport type { SequenceEntry, SequenceSlot } from './types/item-group.js';\n\nexport type { AttemptPlan, AttemptPlanDrift, AttemptPlanSlot } from './types/attempt-plan.js';\n\n/** Options for {@link planAttempt}. */\nexport interface PlanAttemptOptions<TItem> {\n /** Shuffle the top-level entries. A group moves as one block. */\n shuffleEntries?: boolean;\n /**\n * Seed for every shuffle in this attempt. Required whenever anything\n * shuffles — the attempt has to be reproducible, which is the entire point\n * of writing a plan down. Use the attempt id.\n */\n seed?: string;\n /**\n * What each slot is worth. Defaults to 1 for every slot.\n *\n * Points are resolved HERE, not read from content, because they belong to\n * the paper rather than the item: the same question is worth 1 in a practice\n * quiz and 3 in a final. Whatever this returns is frozen into the plan and\n * is what `composeAssessmentScore` will weight by.\n *\n * @throws Error when it returns a value that is not a finite, non-negative\n * number — a slot worth `NaN` points would poison the whole total.\n */\n points?: (slot: SequenceSlot<TItem>) => number;\n}\n\n/**\n * The activity as CONTENT, with its slot key removed.\n *\n * `slotKey` rides on the same object but is identity, not content — the whole\n * point of the design. Including it in the fingerprint meant that annotating\n * an existing entry with the key that pins its identity reported as\n * \"this question was edited\", which is precisely backwards.\n */\nfunction contentOf(activity: object): object {\n if (!Object.hasOwn(activity, 'slotKey')) {\n return activity;\n }\n const { slotKey: _slotKey, ...content } = activity as { slotKey?: unknown };\n return content;\n}\n\nfunction planSlot<TItem extends { id: string; type: string }>(\n slot: SequenceSlot<TItem>,\n points: number,\n): AttemptPlanSlot {\n if (!Number.isFinite(points) || points < 0) {\n throw new Error(\n `planAttempt: slot \"${slot.slotId}\" resolved to ${String(points)} points. Points must be a ` +\n 'finite, non-negative number, or the paper has no defensible total.',\n );\n }\n return {\n slotId: slot.slotId,\n index: slot.index,\n activityId: slot.activity.id,\n activityType: slot.activity.type,\n points,\n contentHash: contentHash(contentOf(slot.activity)),\n ...(slot.group !== undefined\n ? {\n group: {\n id: slot.group.id,\n ...(slot.group.title !== undefined ? { title: slot.group.title } : {}),\n stimulusHash: contentHash(slot.group.stimulus),\n },\n }\n : {}),\n };\n}\n\n/**\n * Freezes what an attempt is being served: the presented order, each slot's\n * identity and worth, and a fingerprint of the content behind it.\n *\n * Call this once, when the attempt starts, and store the result beside the\n * responses. Everything that decides the grade is then a historical fact\n * rather than a re-read of content that may since have changed — which is what\n * makes a re-grade, a remark or an appeal answerable.\n *\n * Ordering comes from `flattenSequence`, so a plan and a live render of the\n * same entries with the same seed agree slot for slot.\n *\n * @throws Error when a shuffle is requested without a seed, when a group is\n * empty, when two entries collide on a `slotKey`, or when `points`\n * returns a value that is not finite and non-negative.\n */\nexport function planAttempt<TItem extends { id: string; type: string }>(\n entries: readonly SequenceEntry<TItem>[],\n options: PlanAttemptOptions<TItem> = {},\n): AttemptPlan {\n const { seed, shuffleEntries, points } = options;\n const slots = flattenSequence(entries, {\n ...(shuffleEntries !== undefined ? { shuffleEntries } : {}),\n ...(seed !== undefined ? { seed } : {}),\n });\n\n const planned = slots.map((slot) => planSlot(slot, points?.(slot) ?? 1));\n const totalPoints = planned.reduce((sum, slot) => sum + slot.points, 0);\n\n return {\n planVersion: '1.0',\n ...(seed !== undefined ? { seed } : {}),\n ...(shuffleEntries !== undefined ? { shuffleEntries } : {}),\n // The plan's own fingerprint covers the slots verbatim — identity, order,\n // points and content hashes — so one stored value answers \"is this still\n // the paper that was sat?\" and the per-slot hashes then say what moved.\n planHash: contentHash(planned),\n slots: planned,\n totalPoints,\n };\n}\n\n/**\n * Compares a stored plan with the content as it stands now, and reports every\n * way they have drifted apart.\n *\n * This is the question a remark or an appeal actually asks: *is the paper I am\n * looking at the paper this learner sat?* Ids alone cannot answer it, because\n * they survive an edit unchanged.\n *\n * Rebuild the comparison plan with the SAME options the stored one recorded —\n * its `seed`, its `shuffleEntries`, and the same `points` function — or the\n * differences you see will be your own:\n *\n * ```ts\n * const now = planAttempt(currentEntries, {\n * seed: stored.seed,\n * shuffleEntries: stored.shuffleEntries,\n * points: pointsFor, // omit it and every slot reweights to 1\n * });\n * const drift = verifyAttemptPlan(stored, now);\n * ```\n *\n * A drift is not automatically a problem — a fixed typo changes a hash without\n * changing what was asked. It is a fact somebody has to be able to see.\n */\nexport function verifyAttemptPlan(plan: AttemptPlan, current: AttemptPlan): AttemptPlanDrift {\n const before = new Map(plan.slots.map((slot) => [slot.slotId, slot]));\n const after = new Map(current.slots.map((slot) => [slot.slotId, slot]));\n\n const missingSlotIds = plan.slots.filter((s) => !after.has(s.slotId)).map((s) => s.slotId);\n const addedSlotIds = current.slots.filter((s) => !before.has(s.slotId)).map((s) => s.slotId);\n\n const changedSlotIds: string[] = [];\n const changedStimulusSlotIds: string[] = [];\n const changedPointsSlotIds: string[] = [];\n const reorderedSlotIds: string[] = [];\n for (const slot of plan.slots) {\n const now = after.get(slot.slotId);\n if (now === undefined) {\n continue;\n }\n // A swapped activity changes the content behind the slot, so it lands in\n // `changedSlotIds` through the fingerprint rather than needing its own arm.\n if (now.contentHash !== slot.contentHash) {\n changedSlotIds.push(slot.slotId);\n }\n if (now.group?.stimulusHash !== slot.group?.stimulusHash) {\n changedStimulusSlotIds.push(slot.slotId);\n }\n // A reweight moves the grade without touching a single question. Left out,\n // `matches` said the paper was unchanged while its `planHash` disagreed.\n if (now.points !== slot.points) {\n changedPointsSlotIds.push(slot.slotId);\n }\n if (now.index !== slot.index) {\n reorderedSlotIds.push(slot.slotId);\n }\n }\n\n return {\n matches:\n missingSlotIds.length === 0 &&\n addedSlotIds.length === 0 &&\n changedSlotIds.length === 0 &&\n changedStimulusSlotIds.length === 0 &&\n changedPointsSlotIds.length === 0 &&\n reorderedSlotIds.length === 0,\n missingSlotIds,\n addedSlotIds,\n changedSlotIds,\n changedStimulusSlotIds,\n changedPointsSlotIds,\n reorderedSlotIds,\n };\n}\n\n/** How {@link scoredItemsFromPlan} fills a slot that has no recorded outcome. */\nexport type MissingOutcomePolicy =\n /**\n * Default. `{ status: 'deferred', reason: 'no_response_recorded' }` — a\n * non-terminal state, so the composed result stays `provisional` and cannot\n * be recorded as a final pass or fail.\n */\n | 'deferred'\n /**\n * `{ status: 'scored', score: 0 }` — the learner left it blank on a paper\n * that IS complete. Choose this only when you know the attempt was\n * submitted; it is a real zero and makes the result final.\n */\n | 'zero'\n /** Build the outcome yourself, per slot. */\n | ((slot: AttemptPlanSlot) => ItemOutcome);\n\nfunction missingOutcome(slot: AttemptPlanSlot, policy: MissingOutcomePolicy): ItemOutcome {\n if (typeof policy === 'function') {\n return policy(slot);\n }\n if (policy === 'zero') {\n return { status: 'scored', score: 0, maxScore: 1, passed: false, feedback: null, details: [] };\n }\n return { status: 'deferred', reason: 'no_response_recorded', maxScore: 1 };\n}\n\n/**\n * Turns a plan plus whatever outcomes exist into the `ScoredItem[]`\n * `composeAssessmentScore` consumes.\n *\n * The plan is the source of the denominator, not the outcomes. A slot the\n * learner never reached still has to appear — otherwise it silently leaves the\n * denominator and the remaining questions quietly become worth more than the\n * paper says.\n *\n * **A missing outcome defaults to `deferred`, never `unscorable`.** The\n * distinction decides a grade: `unscorable` means \"a grade is never coming\",\n * so `composeAssessmentScore` drops the slot from the denominator AND lets the\n * result go `final` — which turned a three-question paper with one answer into\n * a final, passing 100%. `deferred` means \"not yet\", which holds the result\n * `provisional` so nothing can be recorded. Pass `'zero'` once you know the\n * attempt was submitted and the blanks are genuinely blanks.\n *\n * Pass outcomes keyed by `slotId`. Keys the plan does not know are ignored:\n * a plan is the authority on what the attempt contained.\n */\nexport function scoredItemsFromPlan(\n plan: AttemptPlan,\n outcomes: Readonly<Record<string, ItemOutcome>>,\n options: { missing?: MissingOutcomePolicy } = {},\n): ScoredItem[] {\n const policy = options.missing ?? 'deferred';\n return plan.slots.map((slot) => ({\n slotId: slot.slotId,\n activityId: slot.activityId,\n points: slot.points,\n // `Object.hasOwn`, not a bare lookup: slot ids come from authored\n // `slotKey`s, and a key of `constructor` or `toString` would otherwise\n // resolve through the prototype chain and hand a FUNCTION to the scorer\n // in place of an outcome.\n outcome: Object.hasOwn(outcomes, slot.slotId)\n ? (outcomes[slot.slotId] as ItemOutcome)\n : missingOutcome(slot, policy),\n }));\n}\n\n/** Convenience alias: the entry type a plan is built from. */\nexport type PlannableEntry = SequenceEntry<ActivityData>;\n","import { canonicalJson } from './content-hash.js';\nimport type { LearnerResponse } from './types/activity.js';\nimport type { AttemptPlan } from './types/attempt-plan.js';\nimport type { AttemptState, ResponseDiffEntry } from './types/attempt-state.js';\n\nexport type { AttemptState, ResponseDiffEntry } from './types/attempt-state.js';\n\n/** What {@link serializeAttemptState} is given about an attempt in progress. */\nexport interface AttemptProgress {\n /** Answers so far, keyed by `slotId`. */\n responses: Readonly<Record<string, LearnerResponse>>;\n /** Slots already submitted. Defaults to none. */\n submittedSlotIds?: readonly string[];\n /** Presented position the learner is on. Defaults to 0. */\n index?: number;\n /** ISO 8601 timestamp to stamp the snapshot with. The SDK does not read a clock. */\n savedAt?: string;\n}\n\n/**\n * A DEEP copy of the responses.\n *\n * A one-level spread is not enough: every `LearnerResponse` shape is itself an\n * object (`selectedOptionIds`, `answers`, `text`), so a spread hands back a new\n * map of the caller's SAME response objects. A consumer whose reducer updates\n * an answer in place — an Immer draft, a push onto a multi-select, or\n * `answers[blankId] = text`, which is the natural update for that shape — then\n * mutates every snapshot ever taken. The stored snapshot retroactively becomes\n * the new answer, `diffResponses` sees no change, and a delta autosave writes\n * nothing for an edit the learner really made.\n */\nfunction cloneResponses(\n responses: Readonly<Record<string, LearnerResponse>>,\n): Record<string, LearnerResponse> {\n // Responses are JSON by contract, so the fallback is lossless for them.\n return typeof structuredClone === 'function'\n ? structuredClone(responses as Record<string, LearnerResponse>)\n : (JSON.parse(JSON.stringify(responses)) as Record<string, LearnerResponse>);\n}\n\n/** Slot ids present in the object but unknown to the plan. */\nfunction unknownKeys(plan: AttemptPlan, keys: readonly string[]): string[] {\n const known = new Set(plan.slots.map((slot) => slot.slotId));\n return keys.filter((key) => !known.has(key));\n}\n\n/**\n * Captures an in-progress attempt as a storable snapshot, bound to its plan.\n *\n * Validated against the plan on the way in, not on the way out: a response\n * stored under a slot the paper does not contain is a bug at the moment it is\n * written, and finding it months later — when a learner tries to resume — is\n * finding it far too late.\n *\n * The SDK reads no clock: pass `savedAt` if you want the snapshot stamped, so\n * the function stays pure and its output stays reproducible in a test.\n *\n * @throws Error when a response or submitted slot is not in the plan, or when\n * `index` is not a position the plan actually has.\n */\nexport function serializeAttemptState(plan: AttemptPlan, progress: AttemptProgress): AttemptState {\n const responseKeys = Object.keys(progress.responses);\n const submittedSlotIds = [...(progress.submittedSlotIds ?? [])];\n\n const strayResponses = unknownKeys(plan, responseKeys);\n if (strayResponses.length > 0) {\n throw new Error(\n `serializeAttemptState: response recorded for slot(s) the plan does not contain: ${strayResponses.join(', ')}. ` +\n 'A response that belongs to no question cannot be scored and would be lost silently.',\n );\n }\n const straySubmitted = unknownKeys(plan, submittedSlotIds);\n if (straySubmitted.length > 0) {\n throw new Error(\n `serializeAttemptState: submitted slot(s) the plan does not contain: ${straySubmitted.join(', ')}.`,\n );\n }\n\n const index = progress.index ?? 0;\n // An out-of-range position would reopen the attempt on a question that is\n // not there — which the pager renders as an empty shell with no way forward.\n // An empty plan admits only 0: guarding with `slots.length > 0` skipped the\n // range check altogether there, so a zero-slot paper accepted any index and\n // the error message contradicted itself.\n const lastIndex = Math.max(0, plan.slots.length - 1);\n if (!Number.isInteger(index) || index < 0 || index > lastIndex) {\n throw new Error(\n `serializeAttemptState: index ${String(index)} is not a position in a ${plan.slots.length}-slot plan.`,\n );\n }\n\n return {\n stateVersion: '1.0',\n planHash: plan.planHash,\n // Copied DEEPLY, not aliased: a snapshot that keeps mutating with the\n // live attempt is not a snapshot. See cloneResponses.\n responses: cloneResponses(progress.responses),\n submittedSlotIds,\n index,\n ...(progress.savedAt !== undefined ? { savedAt: progress.savedAt } : {}),\n };\n}\n\n/**\n * Reopens a stored snapshot against a plan, refusing anything that does not\n * belong to it.\n *\n * The `planHash` check is the point. Slot ids are short and stable by design,\n * so a snapshot from a DIFFERENT paper — last term's midterm, a sibling\n * version, a copy-pasted attempt row — will happily line its answers up\n * against the wrong questions and look entirely plausible doing it. Comparing\n * the paper's fingerprint is what makes that impossible rather than unlikely.\n *\n * @throws Error when the snapshot belongs to a different plan, or references\n * slots the plan does not contain.\n */\nexport function restoreAttemptState(plan: AttemptPlan, state: AttemptState): AttemptState {\n if (state === null || typeof state !== 'object') {\n throw new Error('restoreAttemptState: the snapshot is not an object.');\n }\n // The one field added so a stored snapshot survives an envelope change was\n // the one field never read: an unrecognised version was accepted,\n // reinterpreted under this version's rules, and re-stamped '1.0' — which\n // also destroyed the evidence that it had ever been anything else.\n if (state.stateVersion !== '1.0') {\n throw new Error(\n `restoreAttemptState: unsupported stateVersion ${JSON.stringify(state.stateVersion)}. ` +\n 'This build understands \"1.0\"; a newer snapshot must be migrated before it is restored.',\n );\n }\n if (state.responses === null || typeof state.responses !== 'object') {\n throw new Error(\n 'restoreAttemptState: the snapshot carries no responses object (a NULL column, or a ' +\n 'partially written row).',\n );\n }\n if (state.planHash !== plan.planHash) {\n throw new Error(\n 'restoreAttemptState: this snapshot belongs to a different paper ' +\n `(snapshot ${state.planHash}, plan ${plan.planHash}). Restoring it would attach the ` +\n \"learner's answers to questions they never saw.\",\n );\n }\n // Re-validated rather than trusted: a snapshot is storage, and storage is\n // edited, migrated and hand-fixed.\n return serializeAttemptState(plan, {\n responses: state.responses,\n submittedSlotIds: state.submittedSlotIds,\n index: state.index,\n ...(state.savedAt !== undefined ? { savedAt: state.savedAt } : {}),\n });\n}\n\n/**\n * Reports how two snapshots' responses differ, slot by slot.\n *\n * Useful for an autosave that should only write what moved, and for an audit\n * trail that has to show what a learner changed between two saves — including\n * an answer they cleared, which a naive comparison of the later snapshot\n * alone cannot see.\n *\n * Entries come back sorted by `slotId`, so the output is stable regardless of\n * the order the two objects happened to be written in.\n */\nexport function diffResponses(\n before: Pick<AttemptState, 'responses'>,\n after: Pick<AttemptState, 'responses'>,\n): ResponseDiffEntry[] {\n const slotIds = [...new Set([...Object.keys(before.responses), ...Object.keys(after.responses)])];\n slotIds.sort();\n\n const entries: ResponseDiffEntry[] = [];\n for (const slotId of slotIds) {\n const had = Object.hasOwn(before.responses, slotId);\n const has = Object.hasOwn(after.responses, slotId);\n const from = before.responses[slotId];\n const to = after.responses[slotId];\n\n if (had && !has) {\n entries.push({ slotId, change: 'removed', ...(from !== undefined ? { before: from } : {}) });\n continue;\n }\n if (!had && has) {\n entries.push({ slotId, change: 'added', ...(to !== undefined ? { after: to } : {}) });\n continue;\n }\n // Structural comparison through the canonical form, so a response that\n // survived a JSON round-trip with its keys reordered does not read as a\n // change the learner never made.\n if (canonicalJson(from) !== canonicalJson(to)) {\n entries.push({\n slotId,\n change: 'changed',\n ...(from !== undefined ? { before: from } : {}),\n ...(to !== undefined ? { after: to } : {}),\n });\n }\n }\n return entries;\n}\n","import { ActivitySchemaError, UnknownActivityTypeError } from './errors.js';\nimport { getActivityTypeDescriptor } from './registry/index.js';\nimport type { FieldPolicy, Sensitivity } from './registry/registry.js';\nimport { RedactedItemGroupSchema } from './schemas/item-group.js';\nimport type { ItemGroup } from './types/item-group.js';\n\n/**\n * A learner-safe projection of activity data produced by {@link redact}:\n * the activity's public fields plus the `redacted: true` marker. Renderable\n * and validatable (each built-in type registers a strict redacted schema),\n * but stripped of the answer key, scoring rules, authored feedback, and\n * author-only assets.\n */\nexport interface RedactedActivityData {\n redacted: true;\n schemaVersion: string;\n type: string;\n id: string;\n title: string;\n [key: string]: unknown;\n}\n\n/** Options for {@link redact}. */\nexport interface RedactOptions {\n /**\n * Which sensitivity tiers to keep beyond `public`:\n * - `'none'` (default) — public fields only; the output satisfies the\n * type's strict redacted schema and `assertRedacted`.\n * - `'after-submit'` — public + answer-key fields (for post-submission\n * review renders). `author-only` fields and unclassified fields are\n * STILL removed; the output will NOT pass `assertRedacted`.\n */\n reveal?: 'none' | 'after-submit';\n /**\n * Per-call sensitivity overrides, merged over the type's registered\n * `fieldPolicy` (top-level keys replace; nested objects merge one level).\n *\n * Sensitivity is partly a PEDAGOGICAL decision, not purely a security one —\n * whether a rubric or a hint is learner-visible differs legitimately between\n * deployments — and the SDK must not freeze that choice. Use this to tighten\n * a field the SDK ships as `public`:\n *\n * ```ts\n * redact(essay, { policy: { rubric: 'author-only' } });\n * ```\n *\n * Overrides can only be applied to fields; they cannot re-open a field the\n * caller has not classified, because unclassified still means removed.\n * Note that tightening below what the type's `redactedSchema` requires is\n * allowed — the schema check only rejects payloads that reveal MORE than\n * the learner-safe shape.\n */\n policy?: FieldPolicy;\n}\n\n/** Merges per-call overrides over a registered policy, one level deep. */\nfunction mergePolicy(base: FieldPolicy, overrides: FieldPolicy | undefined): FieldPolicy {\n if (overrides === undefined) {\n return base;\n }\n const merged: Record<string, Sensitivity | FieldPolicy> = { ...base };\n for (const [key, override] of Object.entries(overrides)) {\n const current = merged[key];\n merged[key] =\n typeof override === 'object' && typeof current === 'object'\n ? { ...current, ...override }\n : override;\n }\n return merged;\n}\n\nfunction isSensitivity(value: Sensitivity | FieldPolicy): value is Sensitivity {\n return typeof value === 'string';\n}\n\nfunction keepField(sensitivity: Sensitivity, reveal: 'none' | 'after-submit'): boolean {\n if (sensitivity === 'public') {\n return true;\n }\n return sensitivity === 'answer-key' && reveal === 'after-submit';\n}\n\nfunction redactValue(\n value: unknown,\n policy: FieldPolicy,\n reveal: 'none' | 'after-submit',\n): unknown {\n if (Array.isArray(value)) {\n return value.map((element) => redactValue(element, policy, reveal));\n }\n if (value === null || typeof value !== 'object') {\n // A nested FieldPolicy cannot classify a primitive's sub-fields; the\n // policy author classified an object shape that is not there. Fail\n // closed: drop it (handled by the caller returning undefined).\n return undefined;\n }\n\n const source = value as Record<string, unknown>;\n const output: Record<string, unknown> = {};\n for (const [key, fieldValue] of Object.entries(source)) {\n if (fieldValue === undefined) {\n continue;\n }\n const classification = policy[key];\n if (classification === undefined) {\n // Fail closed: unclassified fields are never emitted, at any reveal\n // level. Adding a field without classifying it hides it — never leaks it.\n continue;\n }\n if (isSensitivity(classification)) {\n if (keepField(classification, reveal)) {\n output[key] = fieldValue;\n }\n continue;\n }\n const nested = redactValue(fieldValue, classification, reveal);\n if (nested !== undefined) {\n output[key] = nested;\n }\n }\n return output;\n}\n\n/**\n * Produces the learner-safe projection of activity data (R7), driven by the\n * `fieldPolicy` registered for `data.type`. Fail-closed and exhaustive by\n * construction: a field the policy does not classify is removed — including\n * unknown passthrough fields — so a NEW field added by a future SDK or a\n * consumer sidecar can never leak through an out-of-date redactor.\n *\n * With the default `reveal: 'none'`, the output validates against the type's\n * strict redacted schema (verified here; an invalid projection throws\n * {@link ActivitySchemaError} rather than shipping an unproven payload).\n *\n * @throws UnknownActivityTypeError when `data.type` is not registered.\n * @throws Error when the registered descriptor declares no `fieldPolicy`\n * (redaction cannot guess sensitivities).\n */\nexport function redact<T extends { type: string }>(\n data: T,\n options: RedactOptions = {},\n): RedactedActivityData {\n const reveal = options.reveal ?? 'none';\n const descriptor = getActivityTypeDescriptor(data.type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(data.type));\n }\n if (descriptor.fieldPolicy === undefined) {\n throw new Error(\n `Activity type \"${descriptor.type}\" has no fieldPolicy; redact() cannot run fail-closed redaction without one.`,\n );\n }\n\n const effectivePolicy = mergePolicy(descriptor.fieldPolicy, options.policy);\n const projected = redactValue(data, effectivePolicy, reveal) as Record<string, unknown>;\n const result = { ...projected, redacted: true as const } as RedactedActivityData;\n\n if (reveal === 'none' && descriptor.redactedSchema !== undefined) {\n const parsed = descriptor.redactedSchema.safeParse(result);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n descriptor.type,\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n }\n\n return result;\n}\n\n/**\n * Asserts that `data` is a learner-safe redacted projection: it carries the\n * `redacted: true` marker and, when its type registers a strict redacted\n * schema, validates against it (proving the absence of answer-key fields).\n * Use this at the server boundary before sending activity data to a client\n * that must not hold the key.\n */\nexport function assertRedacted(data: unknown): asserts data is RedactedActivityData {\n if (typeof data !== 'object' || data === null) {\n throw new ActivitySchemaError('unknown', [\n { path: [], message: 'Redacted activity data must be an object.', code: 'invalid_type' },\n ]);\n }\n const candidate = data as Record<string, unknown>;\n if (candidate.redacted !== true) {\n throw new ActivitySchemaError(String(candidate.type ?? 'unknown'), [\n {\n path: ['redacted'],\n message: 'Missing redacted marker — this payload is not a redact() projection.',\n code: 'custom',\n },\n ]);\n }\n const type = typeof candidate.type === 'string' ? candidate.type : '';\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(type);\n }\n if (descriptor.redactedSchema === undefined) {\n // Fail closed: without a registered redacted schema there is no way to\n // PROVE the absence of answer-key fields, and a marker alone proves\n // nothing (any object can carry `redacted: true`).\n throw new ActivitySchemaError(descriptor.type, [\n {\n path: [],\n message: `Activity type \"${descriptor.type}\" registers no redactedSchema; assertRedacted cannot prove this payload is learner-safe.`,\n code: 'custom',\n },\n ]);\n }\n const parsed = descriptor.redactedSchema.safeParse(candidate);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n descriptor.type,\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n}\n\n/**\n * Sensitivity of a stimulus. Everything is learner-visible — that is what a\n * stimulus IS — except the author transcript. Fail-closed like every other\n * policy: a field added to `Stimulus` without a classification here is\n * dropped, never leaked.\n */\nconst STIMULUS_FIELD_POLICY: FieldPolicy = {\n id: 'public',\n kind: 'public',\n title: 'public',\n body: 'public',\n bodyHtml: 'public',\n media: 'public',\n locale: 'public',\n attribution: 'public',\n transcript: 'author-only',\n};\n\n/** The group container's own fields. `items` is handled separately, per item type. */\nconst ITEM_GROUP_FIELD_POLICY: FieldPolicy = {\n schemaVersion: 'public',\n type: 'public',\n id: 'public',\n title: 'public',\n // See the note on the built-in activity policies: a slot key is identity,\n // and identity has to cross the redaction boundary intact.\n slotKey: 'public',\n shuffle: 'public',\n stimulus: STIMULUS_FIELD_POLICY,\n};\n\n/** A learner-safe item group: the container with its marker, holding `redact()` projections. */\nexport type RedactedItemGroup = ItemGroup<RedactedActivityData> & { redacted: true };\n\n/**\n * Produces the learner-safe projection of an item group: the container and\n * stimulus under their own fail-closed policy (the author transcript goes;\n * the passage, media and attribution stay — the learner is meant to see\n * them), and every item through {@link redact} with the same `options`, so\n * a per-call `policy` tightens each item exactly as it would alone.\n *\n * With the default `reveal: 'none'` the container is verified against the\n * strict redacted schema; each item was already verified by `redact`.\n */\nexport function redactItemGroup<TItem extends { type: string }>(\n group: ItemGroup<TItem>,\n options: RedactOptions = {},\n): RedactedItemGroup {\n const reveal = options.reveal ?? 'none';\n const { items, ...container } = group;\n const projected = redactValue(container, ITEM_GROUP_FIELD_POLICY, reveal) as Record<\n string,\n unknown\n >;\n const result = {\n ...projected,\n items: items.map((item) => redact(item, options)),\n redacted: true as const,\n } as RedactedItemGroup;\n\n if (reveal === 'none') {\n const parsed = RedactedItemGroupSchema.safeParse(result);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n 'item-group',\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n }\n return result;\n}\n\n/**\n * Asserts that `data` is a learner-safe item group: it carries the marker,\n * its container and stimulus satisfy the strict redacted schema (so no\n * transcript, no unclassified field), and EVERY item passes\n * {@link assertRedacted} against its own type's redacted schema. Item\n * failures are reported at `items.<index>.…`. Use it at the server boundary\n * before sending a group to a client that must not hold the key.\n */\nexport function assertRedactedItemGroup(data: unknown): asserts data is RedactedItemGroup {\n if (typeof data !== 'object' || data === null) {\n throw new ActivitySchemaError('item-group', [\n { path: [], message: 'Redacted item group must be an object.', code: 'invalid_type' },\n ]);\n }\n const candidate = data as Record<string, unknown>;\n if (candidate.redacted !== true) {\n throw new ActivitySchemaError('item-group', [\n {\n path: ['redacted'],\n message: 'Missing redacted marker — this payload is not a redactItemGroup() projection.',\n code: 'custom',\n },\n ]);\n }\n const parsed = RedactedItemGroupSchema.safeParse(candidate);\n if (!parsed.success) {\n throw new ActivitySchemaError(\n 'item-group',\n parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n );\n }\n parsed.data.items.forEach((item, index) => {\n try {\n assertRedacted(item);\n } catch (error) {\n if (error instanceof ActivitySchemaError) {\n throw new ActivitySchemaError(\n 'item-group',\n error.errors.map((issue) => ({\n ...issue,\n path: ['items', String(index), ...issue.path],\n })),\n );\n }\n throw error;\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBO,SAAS,cAAc,OAAgB,OAAoB,oBAAI,IAAI,GAAW;AACnF,MAAI,UAAU,MAAM;AAClB,WAAO;AAAA,EACT;AACA,MAAI,OAAO,UAAU,UAAU;AAK7B,WAAO,OAAO,SAAS,KAAK,IAAI,KAAK,UAAU,UAAU,IAAI,IAAI,KAAK,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,EAC9F;AACA,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW;AAC3D,WAAO,KAAK,U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