@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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schemas/item-group.ts","../src/schemas/json-schema.ts","../src/schemas/index.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport { getActivityTypeDescriptor } from '../registry/index.js';\nimport type { ActivityData, ValidationError, ValidationResult } from '../types/activity.js';\nimport type { ItemGroup, StimulusKind } from '../types/item-group.js';\nimport { MediaSchema } from './media.js';\n\nfunction hasBody(stimulus: { body?: string | undefined }): boolean {\n return typeof stimulus.body === 'string' && stimulus.body.trim().length > 0;\n}\n\n/** Which media types can carry a stimulus of each kind. `text`/`mixed` accept any. */\nfunction mediaFits(kind: StimulusKind, mediaType: string | undefined): boolean {\n switch (kind) {\n case 'audio':\n return mediaType === 'audio';\n case 'video':\n return mediaType === 'video' || mediaType === 'embed';\n case 'image':\n return mediaType === 'image';\n default:\n return true;\n }\n}\n\n/**\n * Zod schema for a {@link Stimulus}. Loose: unknown keys preserved.\n *\n * The semantic guards exist because a stimulus that does not carry what its\n * `kind` promises is an authoring error that must not reach an exam: an\n * \"audio\" stimulus with no recording renders as a blank panel above six\n * listening questions. Unrepresentable in JSON Schema; dropped from\n * `stimulusJsonSchema` by design.\n */\nexport const StimulusSchema = z\n .looseObject({\n id: z.string().min(1),\n kind: z.enum(['text', 'audio', 'video', 'image', 'mixed']),\n title: z.string().optional(),\n body: z.string().optional(),\n bodyHtml: z.string().optional(),\n media: MediaSchema.optional(),\n transcript: z.string().optional(),\n locale: z.string().optional(),\n attribution: z.string().optional(),\n })\n .refine((stimulus) => stimulus.bodyHtml === undefined || hasBody(stimulus), {\n error:\n 'bodyHtml requires a plain-text body: it is the accessible fallback rendered when no sanitiser is supplied.',\n path: ['body'],\n })\n .refine(\n (stimulus) => (stimulus.kind !== 'text' && stimulus.kind !== 'mixed') || hasBody(stimulus),\n {\n error: 'A text or mixed stimulus needs a non-empty body.',\n path: ['body'],\n },\n )\n .refine((stimulus) => stimulus.kind === 'text' || stimulus.media !== undefined, {\n error: 'An audio, video, image or mixed stimulus needs media.',\n path: ['media'],\n })\n .refine(\n (stimulus) => stimulus.media === undefined || mediaFits(stimulus.kind, stimulus.media.type),\n {\n error:\n 'media.type does not fit the stimulus kind: audio needs audio; video needs video or embed; image needs image.',\n path: ['media', 'type'],\n },\n );\n\n/**\n * The structural minimum of an item as seen by the CONTAINER schema. Each\n * item's own contract is checked against its registered schema by\n * {@link validateItemGroup} — a zod schema cannot dispatch on a registry\n * that consumers extend at runtime.\n */\nconst ItemShapeSchema = z.looseObject({\n type: z.string().min(1),\n id: z.string().min(1),\n slotKey: z.string().min(1).optional(),\n});\n\n/**\n * Zod schema for an {@link ItemGroup} CONTAINER. Loose: unknown keys\n * preserved. Validates the group's own fields and the stimulus in full, and\n * each item only structurally (`type` and `id`); use {@link validateItemGroup}\n * to validate the items against their registered schemas as well.\n */\nexport const ItemGroupSchema = z\n .looseObject({\n schemaVersion: z.literal('1.0'),\n type: z.literal('item-group'),\n id: z.string().min(1),\n title: z.string().optional(),\n slotKey: z.string().min(1).optional(),\n stimulus: StimulusSchema,\n items: z.array(ItemShapeSchema).min(1),\n shuffle: z.enum(['none', 'within-group']).optional(),\n })\n .refine((group) => group.items.every((item) => item.type !== 'item-group'), {\n error: 'Item groups do not nest: every item must be an activity.',\n path: ['items'],\n })\n .refine((group) => new Set(group.items.map((item) => item.id)).size === group.items.length, {\n error: 'Item ids must be unique within a group.',\n path: ['items'],\n });\n\n/** The learner-safe shape of a stimulus, derived from the strict schema below. */\nexport type RedactedStimulus = z.infer<typeof RedactedStimulusSchema>;\n\n/** Strict learner-safe stimulus: everything but the author-only `transcript`. */\nexport const RedactedStimulusSchema = z.strictObject({\n id: z.string().min(1),\n kind: z.enum(['text', 'audio', 'video', 'image', 'mixed']),\n title: z.string().optional(),\n body: z.string().optional(),\n bodyHtml: z.string().optional(),\n media: MediaSchema.optional(),\n locale: z.string().optional(),\n attribution: z.string().optional(),\n});\n\n/**\n * Strict learner-safe item group. Items are left opaque here — each is proven\n * learner-safe by `assertRedacted` against its OWN type's redacted schema,\n * which is the only place that knowledge lives.\n */\nexport const RedactedItemGroupSchema = z.strictObject({\n redacted: z.literal(true),\n schemaVersion: z.literal('1.0'),\n type: z.literal('item-group'),\n id: z.string().min(1),\n title: z.string().optional(),\n slotKey: z.string().min(1).optional(),\n stimulus: RedactedStimulusSchema,\n items: z.array(z.unknown()).min(1),\n shuffle: z.enum(['none', 'within-group']).optional(),\n});\n\nfunction toValidationErrors(\n issues: readonly { path: PropertyKey[]; message: string; code: string }[],\n prefix: string[],\n): ValidationError[] {\n return issues.map((issue) => ({\n path: [...prefix, ...issue.path.map(String)],\n message: issue.message,\n code: issue.code,\n }));\n}\n\n/**\n * Validates an item group in full: the container and stimulus against\n * {@link ItemGroupSchema}, then every item against the schema registered for\n * its `type`. Errors from items are reported at `items.<index>.…`.\n *\n * Unlike `validateActivity`, an item whose type is not registered is REPORTED\n * (code `unknown_activity_type`) rather than thrown: a group is validated as\n * a whole, and an author fixing a six-item group wants every problem listed,\n * not the first one that happened to throw.\n */\nexport function validateItemGroup(data: unknown): ValidationResult<ItemGroup> {\n const container = ItemGroupSchema.safeParse(data);\n if (!container.success) {\n return { success: false, errors: toValidationErrors(container.error.issues, []) };\n }\n\n const errors: ValidationError[] = [];\n const items: ActivityData[] = [];\n container.data.items.forEach((item, index) => {\n const descriptor = getActivityTypeDescriptor(item.type);\n if (descriptor === undefined) {\n errors.push({\n path: ['items', String(index), 'type'],\n message: `Activity type \"${item.type}\" is not registered`,\n code: 'unknown_activity_type',\n });\n return;\n }\n const parsed = descriptor.schema.safeParse(item);\n if (!parsed.success) {\n errors.push(...toValidationErrors(parsed.error.issues, ['items', String(index)]));\n return;\n }\n items.push(parsed.data as ActivityData);\n });\n\n if (errors.length > 0) {\n return { success: false, errors };\n }\n // zod4 optional outputs are `T | undefined`; the wire type uses exact\n // optionals. Structurally identical at runtime — the cast is type-level.\n return { success: true, data: { ...container.data, items } as unknown as ItemGroup };\n}\n","import { z } from 'zod/v4';\nimport { UnknownActivityTypeError } from '../errors.js';\nimport { getActivityTypeDescriptor } from '../registry/index.js';\nimport { FillInTheBlanksDataSchema } from './fill-in-the-blanks.js';\nimport { ItemGroupSchema, StimulusSchema } from './item-group.js';\nimport { MultipleChoiceDataSchema } from './multiple-choice.js';\nimport { WrittenResponseDataSchema } from './written-response.js';\n\n/**\n * JSON Schema (Draft 7) for a `Stimulus`. Structural contract only — the\n * kind/media/body consistency guards are Zod-only.\n */\nexport const stimulusJsonSchema = z.toJSONSchema(StimulusSchema, { target: 'draft-7' });\n\n/**\n * JSON Schema (Draft 7) for an `ItemGroup` CONTAINER. Items appear as objects\n * with `type` and `id` only; each item's own contract is `jsonSchemaFor(type)`.\n * For an AI generation pipeline, ask for the group and each item separately\n * rather than a single nested schema — that keeps the per-type schema the\n * registry's, not a copy.\n */\nexport const itemGroupJsonSchema = z.toJSONSchema(ItemGroupSchema, { target: 'draft-7' });\n\n/**\n * JSON Schema (Draft 7) representation of the Multiple Choice activity data\n * contract, generated natively by Zod 4. Draft 7 is mandated by Requirement\n * 2.2 for the widest AI-prompt / OpenAPI tooling compatibility. The semantic\n * `.refine()` guards are not representable in JSON Schema and are\n * intentionally omitted — the export captures the *structural* contract only.\n * Since v0.3 the source schemas are loose, so these no longer emit\n * `additionalProperties: false` — the JSON Schema and `validateActivity` now\n * agree on unknown-key handling.\n */\nexport const multipleChoiceJsonSchema = z.toJSONSchema(MultipleChoiceDataSchema, {\n target: 'draft-7',\n});\n\n/**\n * JSON Schema (Draft 7) representation of the Fill-in-the-Blanks activity data\n * contract, generated natively by Zod 4. Structural contract only (semantic\n * `.refine()` guards are Zod-only and not representable in JSON Schema).\n */\nexport const fillInTheBlanksJsonSchema = z.toJSONSchema(FillInTheBlanksDataSchema, {\n target: 'draft-7',\n});\n\n/**\n * JSON Schema (Draft 7) representation of the Written Response activity data\n * contract. Structural contract only.\n */\nexport const writtenResponseJsonSchema = z.toJSONSchema(WrittenResponseDataSchema, {\n target: 'draft-7',\n});\n\n/**\n * Derives the JSON Schema (Draft 7) for any REGISTERED activity type — the\n * live, registry-backed replacement for the static per-type exports above,\n * and the building block for AI generation pipelines (R6.1): pass the result\n * as a structured-output schema so a model can only emit valid items.\n *\n * @throws UnknownActivityTypeError when `type` has no registered descriptor.\n */\nexport function jsonSchemaFor(type: string): Record<string, unknown> {\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(type);\n }\n return z.toJSONSchema(descriptor.schema as never, { target: 'draft-7' }) as Record<\n string,\n unknown\n >;\n}\n","import { UnknownActivityTypeError } from '../errors.js';\nimport { getActivityTypeDescriptor } from '../registry/index.js';\nimport type { ActivityDataMap, ActivityType, ValidationResult } from '../types/activity.js';\n\nexport { FeedbackSchema } from './feedback.js';\nexport {\n BlankConfigSchema,\n FillInTheBlanksDataSchema,\n TextMatchPolicySchema,\n} from './fill-in-the-blanks.js';\nexport type { RedactedStimulus } from './item-group.js';\nexport {\n ItemGroupSchema,\n RedactedItemGroupSchema,\n RedactedStimulusSchema,\n StimulusSchema,\n validateItemGroup,\n} from './item-group.js';\nexport {\n fillInTheBlanksJsonSchema,\n itemGroupJsonSchema,\n jsonSchemaFor,\n multipleChoiceJsonSchema,\n stimulusJsonSchema,\n writtenResponseJsonSchema,\n} from './json-schema.js';\nexport { MediaSchema, MediaUrlSchema } from './media.js';\nexport { MultipleChoiceDataSchema, MultipleChoiceOptionSchema } from './multiple-choice.js';\nexport type {\n RedactedActivity,\n RedactedBlankConfig,\n RedactedFillInTheBlanksData,\n RedactedMultipleChoiceData,\n RedactedMultipleChoiceOption,\n RedactedWrittenResponseData,\n} from './redacted.js';\nexport {\n RedactedBlankConfigSchema,\n RedactedFillInTheBlanksDataSchema,\n RedactedMultipleChoiceDataSchema,\n RedactedMultipleChoiceOptionSchema,\n RedactedWrittenResponseDataSchema,\n} from './redacted.js';\nexport {\n WrittenResponseDataSchema,\n WrittenResponseRubricCriterionSchema,\n WrittenResponseRubricSchema,\n} from './written-response.js';\n\n/**\n * Validates raw activity data against the schema registered for the given\n * activity type (built-in or consumer-registered via `registerActivityType`).\n *\n * Unknown keys are PRESERVED, not stripped: every built-in schema is loose,\n * so consumer sidecar fields and forward-version fields survive validation\n * verbatim in the returned `data`.\n *\n * @returns `{ success: true, data }` with the typed, validated data, or\n * `{ success: false, errors }` with one entry per failed constraint.\n * @throws UnknownActivityTypeError when `type` has no registered descriptor.\n */\nexport function validateActivity<T extends ActivityType>(\n type: T,\n data: unknown,\n): ValidationResult<ActivityDataMap[T]> {\n const descriptor = getActivityTypeDescriptor(type);\n if (descriptor === undefined) {\n throw new UnknownActivityTypeError(String(type));\n }\n\n const result = descriptor.schema.safeParse(data);\n\n if (result.success) {\n return { success: true, data: result.data as ActivityDataMap[T] };\n }\n\n return {\n success: false,\n errors: result.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n code: issue.code,\n })),\n };\n}\n"],"mappings":";;;;;;;;;;AAA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,IAAI,yBAAyB,OAAO,IAAI,CAAC;AAAA,EACjD;AAEA,QAAM,SAAS,WAAW,OAAO,UAAU,IAAI;AAE/C,MAAI,OAAO,SAAS;AAClB,WAAO,EAAE,SAAS,MAAM,MAAM,OAAO,KAA2B;AAAA,EAClE;AAEA,SAAO;AAAA,IACL,SAAS;AAAA,IACT,QAAQ,OAAO,MAAM,OAAO,IAAI,CAAC,WAAW;AAAA,MAC1C,MAAM,MAAM,KAAK,IAAI,MAAM;AAAA,MAC3B,SAAS,MAAM;AAAA,MACf,MAAM,MAAM;AAAA,IACd,EAAE;AAAA,EACJ;AACF;","names":["z","z"]}
@@ -223,6 +223,8 @@ import { z as z6 } from "zod/v4";
223
223
  var redactedBase = {
224
224
  /** Marker distinguishing a redacted projection from full activity data. */
225
225
  redacted: z6.literal(true),
226
+ /** Slot identity, carried through redaction so the client and the plan agree. */
227
+ slotKey: z6.string().min(1).optional(),
226
228
  schemaVersion: z6.literal("1.0"),
227
229
  id: z6.string().min(1),
228
230
  title: z6.string().min(1),
@@ -472,6 +474,11 @@ var SHARED_PUBLIC_FIELDS = {
472
474
  schemaVersion: "public",
473
475
  type: "public",
474
476
  id: "public",
477
+ // Assembly metadata, not content: it names the slot this item occupies in a
478
+ // paper. It has to survive redaction, or the exam client derives positional
479
+ // slot ids while the server's stored plan holds keyed ones, and the
480
+ // responses cannot be matched back to the attempt.
481
+ slotKey: "public",
475
482
  title: "public",
476
483
  media: "public",
477
484
  passThreshold: "public",
@@ -622,4 +629,4 @@ export {
622
629
  fillInTheBlanksType,
623
630
  writtenResponseType
624
631
  };
625
- //# sourceMappingURL=chunk-NUCEUU4P.js.map
632
+ //# sourceMappingURL=chunk-YCXIHFLG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/count-words.ts","../src/errors.ts","../src/schemas/feedback.ts","../src/schemas/media.ts","../src/schemas/fill-in-the-blanks.ts","../src/schemas/multiple-choice.ts","../src/schemas/written-response.ts","../src/schemas/redacted.ts","../src/scoring/text-match.ts","../src/registry/registry.ts","../src/scoring/strategies/all-or-nothing.ts","../src/scoring/strategies/partial.ts","../src/scoring/activity-scorers/fill-in-the-blanks.ts","../src/scoring/activity-scorers/multiple-choice.ts","../src/registry/builtins.ts"],"sourcesContent":["/**\n * Canonical word counter for written-response bounds (Req 22.9): tokens are\n * maximal runs of non-whitespace (split on `\\s+`), so hyphenated forms\n * (`well-known`) count as one word. The empty / whitespace-only string counts\n * 0. Consumers must use this helper rather than re-implementing the split so\n * client previews, SDK scoring, and stored `wordCount` values always agree.\n */\nexport function countWords(text: string): number {\n // Tolerate non-strings: this runs on client-supplied submission payloads,\n // where a malformed value must score 0 rather than throw mid-grading.\n if (typeof text !== 'string') {\n return 0;\n }\n const trimmed = text.trim();\n if (trimmed === '') {\n return 0;\n }\n return trimmed.split(/\\s+/).length;\n}\n","import type { ValidationError } from './types/activity.js';\n\n/** Thrown when activity data fails schema validation at a component boundary. */\nexport class ActivitySchemaError extends Error {\n constructor(\n public readonly activityType: string,\n public readonly errors: ValidationError[],\n ) {\n super(`Invalid activity data for type \"${activityType}\"`);\n this.name = 'ActivitySchemaError';\n }\n}\n\n/** Thrown when an unrecognised activity type is passed to the scoring engine. */\nexport class UnknownActivityTypeError extends Error {\n constructor(public readonly activityType: string) {\n super(`Activity type \"${activityType}\" is not registered`);\n this.name = 'UnknownActivityTypeError';\n }\n}\n\n/**\n * Thrown when `score()` is asked to grade a `redact()` projection (or any\n * activity data whose answer key is missing, yielding a non-finite score).\n * Redacted data is learner-safe precisely because the key was removed, so a\n * score derived from it is meaningless — previously this produced a silent\n * `NaN` that serialized to `null` in a grade column. `evaluate()` returns\n * `{ status: 'unscorable' }` for the same input instead of throwing.\n */\nexport class RedactedScoringError extends Error {\n constructor(public readonly activityType: string) {\n super(\n `Activity data for \"${activityType}\" carries no answer key (it looks redacted), so it cannot be scored. ` +\n 'Score against the full activity data server-side, or use evaluate() which returns { status: \"unscorable\" }.',\n );\n this.name = 'RedactedScoringError';\n }\n}\n\n/**\n * Thrown when `score()` is called for an activity type whose grading is\n * deferred (asynchronous AI/human grading, e.g. `written-response`). A\n * deferred submission has no synchronous score — treating it as 0 would show\n * a learner a failing grade for work that simply has not been graded yet.\n * Call `evaluate()` instead, which returns `{ status: 'deferred', ... }`.\n */\nexport class DeferredScoringError extends Error {\n constructor(public readonly activityType: string) {\n super(\n `Activity type \"${activityType}\" is graded asynchronously and has no synchronous score. ` +\n `Use evaluate() — it returns { status: 'deferred' } for this type.`,\n );\n this.name = 'DeferredScoringError';\n }\n}\n","import { z } from 'zod/v4';\n\n/**\n * Optional authored \"overall feedback\" shown after submission, selected by\n * whether the learner passed (h5p-style overall feedback). Both fields are\n * optional; non-empty when present.\n */\nexport const FeedbackSchema = z.looseObject({\n correct: z.string().min(1).optional(),\n incorrect: z.string().min(1).optional(),\n});\n","import { z } from 'zod/v4';\n\n/**\n * Optional media attached to an activity, rendered above the question or\n * passage — e.g. a recording to listen to, or an embedded video to watch\n * before answering. URL-only by design: hosting/delivery (S3/CDN, or the\n * provider's own embed for `embed`) is the consuming app's responsibility\n * (see requirements \"Non-Goals and Shared Responsibility\").\n *\n * - `image`: rendered as `<img>` — `alt` is REQUIRED (WCAG 1.1.1 / Req 14.5).\n * - `audio` / `video`: rendered with native controls; `alt` is an optional\n * accessible label; `captionsUrl` points at a WebVTT `<track>`. `url` must\n * be a direct media file (NOT a YouTube/Vimeo page — use `embed` for those).\n * - `embed`: rendered as a sandboxed `<iframe>` for provider players\n * (YouTube/Vimeo/etc.). `url` MUST be the provider's *embeddable* URL\n * (e.g. `https://www.youtube.com/embed/<id>`). `alt` is REQUIRED and used\n * as the iframe's accessible `title` (WCAG 4.1.2 / 2.4.1).\n */\n/**\n * Media URL policy (security-reviewed): absolute URLs must use `https:`,\n * `http:`, `data:`, or `blob:`; root-relative paths (`/media/x.mp3`) are\n * allowed for same-origin hosting. Everything else — notably `javascript:`,\n * `file:`, `ftp:` — is rejected: these URLs land in `src` attributes\n * (including an iframe for `embed`), so an unvetted scheme is a stored-XSS\n * vector in every consuming app.\n */\nexport const MediaUrlSchema = z.union([\n z.url().refine((value) => /^(https?|data|blob):/i.test(value), {\n error: 'Absolute media URLs must use the https:, http:, data:, or blob: scheme.',\n }),\n z.string().regex(/^\\/(?!\\/)\\S*$/, {\n error: 'Relative media URLs must be root-relative (a single leading \"/\").',\n }),\n]);\n\nexport const MediaSchema = z\n .looseObject({\n type: z.enum(['image', 'audio', 'video', 'embed']),\n url: MediaUrlSchema,\n alt: z.string().min(1).optional(),\n captionsUrl: MediaUrlSchema.optional(),\n })\n .refine(\n (m) =>\n (m.type !== 'image' && m.type !== 'embed') || (typeof m.alt === 'string' && m.alt.length > 0),\n {\n error: 'image and embed media require non-empty alt text (WCAG 1.1.1 / 4.1.2).',\n path: ['alt'],\n },\n )\n .refine((m) => m.type !== 'embed' || /^https?:\\/\\//i.test(m.url), {\n error:\n 'embed media requires an absolute http(s) provider URL. data:, blob:, and relative URLs are not allowed for embeds — the embed iframe runs with allow-scripts, and a data:/same-origin document there is an XSS vector.',\n path: ['url'],\n });\n","import { z } from 'zod/v4';\nimport { FeedbackSchema } from './feedback.js';\nimport { MediaSchema } from './media.js';\n\n/** Matches `{{ blank_id }}` placeholders in a passage, capturing the trimmed id. */\nconst PLACEHOLDER_RE = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g;\n\n/**\n * Zod schema for a `TextMatchPolicy` — the opt-in matching tolerances a blank\n * may declare. Every default reproduces the v1 trim + case-fold semantics.\n */\nexport const TextMatchPolicySchema = z.looseObject({\n caseSensitive: z.boolean().optional(),\n trim: z.boolean().optional(),\n normalize: z.enum(['none', 'NFC', 'NFKC']).optional(),\n foldDiacritics: z.boolean().optional(),\n collapseInnerWhitespace: z.boolean().optional(),\n ignorePunctuation: z.boolean().optional(),\n levenshtein: z.number().int().min(0).optional(),\n locale: z.string().optional(),\n});\n\n/**\n * Zod schema for a single fill-in-the-blank slot configuration. Loose:\n * unknown keys are preserved through validation. Accepted answers must\n * contain non-whitespace characters — a whitespace-only accepted answer\n * normalizes to the empty string and would mark an empty response correct.\n */\nexport const BlankConfigSchema = z.looseObject({\n id: z.string().min(1),\n acceptedAnswers: z\n .array(\n z\n .string()\n .min(1)\n .refine((answer) => answer.trim().length > 0, {\n error: 'Accepted answers must contain non-whitespace characters.',\n }),\n )\n .min(1),\n caseSensitive: z.boolean().optional(),\n trimWhitespace: z.boolean().optional(),\n match: TextMatchPolicySchema.optional(),\n hint: z.string().optional(),\n feedback: z.string().optional(),\n});\n\n/**\n * Zod schema validating the full Fill-in-the-Blanks activity data contract.\n * Loose at every level: unknown keys are preserved, never stripped (B7).\n *\n * The refinement enforces a true one-to-one correspondence between `{{id}}`\n * placeholders and `blanks[].id`: every blank id appears EXACTLY ONCE in the\n * passage and exactly once in `blanks[]`. (The previous set-based check let\n * duplicate placeholders and duplicate blank configs through, corrupting the\n * partial-score denominator and per-item details.)\n */\nexport const FillInTheBlanksDataSchema = z\n .looseObject({\n schemaVersion: z.literal('1.0'),\n type: z.literal('fill-in-the-blanks'),\n id: z.string().min(1),\n title: z.string().min(1),\n passage: z.string().min(1),\n passageHtml: z.string().optional(),\n blanks: z.array(BlankConfigSchema).min(1),\n scoringStrategy: z.enum(['all-or-nothing', 'partial']),\n media: MediaSchema.optional(),\n feedback: FeedbackSchema.optional(),\n passThreshold: z.number().min(0).max(1).optional(),\n locale: z.string().optional(),\n learningObjectives: z.array(z.string()).optional(),\n difficultyLevel: z.literal([1, 2, 3, 4, 5]).optional(),\n })\n .refine(\n (data) => {\n const placeholderCounts = new Map<string, number>();\n for (const match of data.passage.matchAll(PLACEHOLDER_RE)) {\n const id = match[1] as string;\n placeholderCounts.set(id, (placeholderCounts.get(id) ?? 0) + 1);\n }\n const blankIds = data.blanks.map((blank) => blank.id);\n if (new Set(blankIds).size !== blankIds.length) {\n return false;\n }\n if (placeholderCounts.size !== blankIds.length) {\n return false;\n }\n return blankIds.every((id) => placeholderCounts.get(id) === 1);\n },\n {\n error:\n 'Each blank id must appear exactly once in blanks[] and have exactly one matching {{id}} placeholder in the passage, and vice versa.',\n path: ['passage'],\n },\n );\n","import { z } from 'zod/v4';\nimport { FeedbackSchema } from './feedback.js';\nimport { MediaSchema } from './media.js';\n\n/**\n * Zod schema for a single Multiple Choice option. Loose: unknown keys are\n * preserved through validation (forward-compat / consumer sidecars — B7).\n */\nexport const MultipleChoiceOptionSchema = z.looseObject({\n id: z.string().min(1),\n text: z.string().min(1),\n isCorrect: z.boolean(),\n feedback: z.string().optional(),\n});\n\n/**\n * Zod schema validating the full Multiple Choice activity data contract.\n * Loose at every level: unknown keys are preserved, never stripped, so a\n * v0.3 runtime reading a future payload (or a consumer sidecar field) does\n * not silently delete data.\n *\n * Semantic guards: (1) at least one option must be correct, otherwise the\n * activity can never be answered correctly; (2) `mode: 'single'` must have\n * exactly one correct option — multiple correct options under single-select\n * make `showCorrectAnswers` and the xAPI correct-response ambiguous and mask\n * authoring errors; (3) option ids must be unique — the scorer looks options\n * up by id, so a duplicate id makes one option unscoreable. All are\n * unrepresentable in JSON Schema and are dropped from `toJSONSchema` output\n * by design.\n */\nexport const MultipleChoiceDataSchema = z\n .looseObject({\n schemaVersion: z.literal('1.0'),\n type: z.literal('multiple-choice'),\n id: z.string().min(1),\n title: z.string().min(1),\n question: z.string().min(1),\n questionHtml: z.string().optional(),\n mode: z.enum(['single', 'multi']),\n options: z.array(MultipleChoiceOptionSchema).min(2).max(26),\n scoringStrategy: z.enum(['all-or-nothing', 'partial']),\n media: MediaSchema.optional(),\n feedback: FeedbackSchema.optional(),\n passThreshold: z.number().min(0).max(1).optional(),\n shuffle: z.boolean().optional(),\n locale: z.string().optional(),\n learningObjectives: z.array(z.string()).optional(),\n difficultyLevel: z.literal([1, 2, 3, 4, 5]).optional(),\n })\n .refine((data) => data.options.some((option) => option.isCorrect), {\n error: 'At least one option must be marked correct.',\n path: ['options'],\n })\n .refine(\n (data) =>\n data.mode !== 'single' || data.options.filter((option) => option.isCorrect).length === 1,\n {\n error: 'Single-select activities (mode: \"single\") must have exactly one correct option.',\n path: ['options'],\n },\n )\n .refine((data) => new Set(data.options.map((option) => option.id)).size === data.options.length, {\n error: 'Option ids must be unique within the activity.',\n path: ['options'],\n });\n","import { z } from 'zod/v4';\nimport { FeedbackSchema } from './feedback.js';\nimport { MediaSchema } from './media.js';\n\n/** Zod schema for a single rubric criterion. Loose: unknown keys preserved. */\nexport const WrittenResponseRubricCriterionSchema = z.looseObject({\n name: z.string().min(1),\n description: z.string().optional(),\n weight: z.number().min(0),\n});\n\n/** Zod schema for a written-response grading rubric. Loose: unknown keys preserved. */\nexport const WrittenResponseRubricSchema = z.looseObject({\n label: z.string().optional(),\n criteria: z.array(WrittenResponseRubricCriterionSchema).min(1),\n});\n\n/**\n * Zod schema validating the Written Response activity data contract (Req 22).\n *\n * Wire-format constraints (Req 22.9): field names are locked for\n * byte-compatibility with consumer-stored rows, and the schema is loose at\n * EVERY level (Req 22.5) — unknown top-level keys, `promptHtml`, `rubric`\n * sidecars and any future fields survive `validateActivity` verbatim.\n */\nexport const WrittenResponseDataSchema = z\n .looseObject({\n schemaVersion: z.literal('1.0'),\n type: z.literal('written-response'),\n id: z.string().min(1),\n title: z.string().min(1),\n prompt: z.string(),\n promptHtml: z.string().optional(),\n minWords: z.number().int().min(0),\n maxWords: z.number().int().min(1),\n rubric: WrittenResponseRubricSchema.optional(),\n languageTarget: z.string().optional(),\n media: MediaSchema.optional(),\n feedback: FeedbackSchema.optional(),\n passThreshold: z.number().min(0).max(1).optional(),\n locale: z.string().optional(),\n learningObjectives: z.array(z.string()).optional(),\n difficultyLevel: z.literal([1, 2, 3, 4, 5]).optional(),\n })\n .refine((data) => data.maxWords >= data.minWords, {\n error: 'maxWords must be greater than or equal to minWords.',\n path: ['maxWords'],\n });\n","import { z } from 'zod/v4';\nimport { MediaSchema } from './media.js';\nimport { WrittenResponseRubricSchema } from './written-response.js';\n\n/**\n * Schemas for REDACTED activity data — the learner-safe projection `redact()`\n * produces (R7). Deliberately STRICT (`z.strictObject`), the opposite of the\n * loose content schemas: a redacted payload must prove the ABSENCE of every\n * answer-key and author-only field, so any unknown key is a validation\n * failure, not a passthrough. `assertRedacted` validates against these.\n */\n\n/** Shared fields every redacted activity carries. */\nconst redactedBase = {\n /** Marker distinguishing a redacted projection from full activity data. */\n redacted: z.literal(true),\n /** Slot identity, carried through redaction so the client and the plan agree. */\n slotKey: z.string().min(1).optional(),\n schemaVersion: z.literal('1.0'),\n id: z.string().min(1),\n title: z.string().min(1),\n media: MediaSchema.optional(),\n passThreshold: z.number().min(0).max(1).optional(),\n locale: z.string().optional(),\n learningObjectives: z.array(z.string()).optional(),\n difficultyLevel: z.literal([1, 2, 3, 4, 5]).optional(),\n};\n\n/** A redacted Multiple Choice option: id and display text only — no `isCorrect`, no feedback. */\nexport const RedactedMultipleChoiceOptionSchema = z.strictObject({\n id: z.string().min(1),\n text: z.string().min(1),\n});\n\n/**\n * Redacted Multiple Choice data: renderable (question, mode, options to pick\n * from) with the answer key, per-option feedback, overall feedback, and the\n * scoring strategy removed. `scoringStrategy` is answer-key by design: MC\n * `partial` carries a wrong-selection penalty `all-or-nothing` does not, so\n * knowing the strategy tells a learner whether guessing is free.\n */\nexport const RedactedMultipleChoiceDataSchema = z.strictObject({\n ...redactedBase,\n type: z.literal('multiple-choice'),\n question: z.string().min(1),\n questionHtml: z.string().optional(),\n mode: z.enum(['single', 'multi']),\n options: z.array(RedactedMultipleChoiceOptionSchema).min(2).max(26),\n shuffle: z.boolean().optional(),\n});\n\n/** A redacted blank: id and hint only — no accepted answers, no matching rules, no feedback. */\nexport const RedactedBlankConfigSchema = z.strictObject({\n id: z.string().min(1),\n hint: z.string().optional(),\n});\n\n/** Redacted Fill-in-the-Blanks data: passage and blank slots, key removed. */\nexport const RedactedFillInTheBlanksDataSchema = z.strictObject({\n ...redactedBase,\n type: z.literal('fill-in-the-blanks'),\n passage: z.string().min(1),\n passageHtml: z.string().optional(),\n blanks: z.array(RedactedBlankConfigSchema).min(1),\n});\n\n/**\n * Redacted Written Response data: the prompt, word bounds and rubric are\n * learner-visible (a rubric tells the learner what they are graded on);\n * authored pass/fail feedback is removed until the grade exists.\n */\nexport const RedactedWrittenResponseDataSchema = z.strictObject({\n ...redactedBase,\n type: z.literal('written-response'),\n prompt: z.string(),\n promptHtml: z.string().optional(),\n minWords: z.number().int().min(0),\n maxWords: z.number().int().min(1),\n rubric: WrittenResponseRubricSchema.optional(),\n languageTarget: z.string().optional(),\n});\n\n/**\n * The learner-safe SHAPE of each built-in type, derived from the strict schema\n * above rather than hand-written beside it.\n *\n * `redact()` returns {@link RedactedActivityData}, which proves a payload is\n * learner-safe but is index-signature typed — it deliberately says nothing\n * about what the payload still CONTAINS. That is right for the assertion and\n * useless for anything that has to render or transport the result, so every\n * integrator ends up re-declaring these interfaces by hand and they drift the\n * moment a schema changes. Deriving them with `z.infer` means the type and the\n * validator can never disagree.\n *\n * Use them for the payload a server sends an exam client, and for the props of\n * a renderer that must never see an answer key.\n */\nexport type RedactedMultipleChoiceOption = z.infer<typeof RedactedMultipleChoiceOptionSchema>;\n/** A Multiple Choice item with the answer key, feedback and strategy removed. */\nexport type RedactedMultipleChoiceData = z.infer<typeof RedactedMultipleChoiceDataSchema>;\n/** A blank with its accepted answers and matching rules removed; the hint survives. */\nexport type RedactedBlankConfig = z.infer<typeof RedactedBlankConfigSchema>;\n/** A Fill-in-the-Blanks item with every accepted answer removed. */\nexport type RedactedFillInTheBlanksData = z.infer<typeof RedactedFillInTheBlanksDataSchema>;\n/** A Written Response item; the rubric survives, because it tells the learner what is assessed. */\nexport type RedactedWrittenResponseData = z.infer<typeof RedactedWrittenResponseDataSchema>;\n\n/**\n * Discriminated union of every built-in redacted activity. Narrow it on\n * `type`, exactly as you would {@link ActivityData}:\n *\n * ```ts\n * function render(item: RedactedActivity) {\n * if (item.type === 'multiple-choice') {\n * return item.options.map((option) => option.text); // no `isCorrect` to leak\n * }\n * }\n * ```\n */\nexport type RedactedActivity =\n | RedactedMultipleChoiceData\n | RedactedFillInTheBlanksData\n | RedactedWrittenResponseData;\n","/**\n * Configurable free-text answer matching (R3.3).\n *\n * Grade-stability contract: the DEFAULTS reproduce the v1 fill-in-the-blanks\n * semantics exactly (trim, then locale-insensitive lowercase, strict `===`).\n * Every tolerance below is opt-in, because changing a default here changes\n * historical grades — and this SDK powers real summative exams.\n */\nexport interface TextMatchPolicy {\n /** Compare case-sensitively. Default `false` (v1 behaviour). */\n caseSensitive?: boolean;\n /** Strip leading/trailing whitespace before comparing. Default `true` (v1 behaviour). */\n trim?: boolean;\n /**\n * Unicode normalization applied to both sides before comparing. Default\n * `'none'` (v1 behaviour). `'NFC'` makes a decomposed `está` (combining\n * U+0301) equal its composed form — the fix for accent-input mismatches in\n * EN/ES/PT content.\n */\n normalize?: 'none' | 'NFC' | 'NFKC';\n /** Treat diacritics as equal to their base letters (`está` ≡ `esta`). Default `false`. */\n foldDiacritics?: boolean;\n /** Collapse runs of inner whitespace to a single space. Default `false`. */\n collapseInnerWhitespace?: boolean;\n /** Ignore Unicode punctuation on both sides. Default `false`. */\n ignorePunctuation?: boolean;\n /** Maximum Levenshtein edit distance still accepted as a match. Default `0`. */\n levenshtein?: number;\n /**\n * BCP 47 tag for locale-aware case folding (e.g. `'tr'` for Turkish dotted /\n * dotless I). Default: locale-insensitive `toLowerCase()` (v1 behaviour).\n */\n locale?: string;\n}\n\n/**\n * How a match was achieved. Lets a consumer award full credit for an `exact`\n * match and partial credit for a `folded` or `fuzzy` one (e.g. diacritic\n * tolerance in a listening gap-fill vs. a spelling test).\n * - `exact` — equal under the baseline trim/case rules alone.\n * - `normalized` — required Unicode normalization, whitespace collapse, or punctuation tolerance.\n * - `folded` — required diacritic folding.\n * - `fuzzy` — required Levenshtein tolerance.\n * - `none` — no accepted answer matched.\n */\nexport interface TextMatchResult {\n matched: boolean;\n via: 'exact' | 'normalized' | 'folded' | 'fuzzy' | 'none';\n}\n\n/** Combining marks (any script) removed for diacritic folding after NFD decomposition. */\nconst COMBINING_MARKS_RE = /\\p{M}/gu;\n/**\n * Unicode punctuation (`\\p{P}`) removed by `ignorePunctuation`. Deliberately\n * NOT `\\p{S}`: symbols like `$`, `+`, `%` can be the substance of an answer\n * (`$100` vs `100`), so a \"punctuation\" toggle must not erase them.\n */\nconst PUNCTUATION_RE = /\\p{P}/gu;\n\nfunction applyBaseline(value: string, policy: TextMatchPolicy): string {\n let result = value;\n if (policy.trim !== false) {\n result = result.trim();\n }\n if (policy.caseSensitive !== true) {\n result = policy.locale ? result.toLocaleLowerCase(policy.locale) : result.toLowerCase();\n }\n return result;\n}\n\nfunction applyNormalization(value: string, policy: TextMatchPolicy): string {\n let result = value;\n if (policy.normalize === 'NFC' || policy.normalize === 'NFKC') {\n result = result.normalize(policy.normalize);\n }\n if (policy.ignorePunctuation === true) {\n result = result.replace(PUNCTUATION_RE, '');\n }\n if (policy.collapseInnerWhitespace === true) {\n // \"Inner\" means between non-space runs. Only trim the ends when the\n // policy's trim is on (its default) — an explicit `trim: false` must not\n // be silently overridden by the collapse.\n result = result.replace(/(?<=\\S)\\s+(?=\\S)/g, ' ');\n if (policy.trim !== false) {\n result = result.trim();\n }\n }\n return result;\n}\n\nfunction applyDiacriticFold(value: string): string {\n return value.normalize('NFD').replace(COMBINING_MARKS_RE, '').normalize('NFC');\n}\n\n/**\n * Levenshtein distance with an early-exit bound: returns `max + 1` as soon as\n * the distance provably exceeds `max`.\n */\nexport function levenshteinDistance(a: string, b: string, max: number): number {\n if (a === b) return 0;\n if (Math.abs(a.length - b.length) > max) return max + 1;\n if (a.length === 0) return b.length;\n if (b.length === 0) return a.length;\n\n let previous = Array.from({ length: b.length + 1 }, (_, i) => i);\n for (let i = 1; i <= a.length; i += 1) {\n const current = [i];\n let rowMin = i;\n for (let j = 1; j <= b.length; j += 1) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n const value = Math.min(\n (previous[j] as number) + 1,\n (current[j - 1] as number) + 1,\n (previous[j - 1] as number) + cost,\n );\n current.push(value);\n if (value < rowMin) rowMin = value;\n }\n if (rowMin > max) return max + 1;\n previous = current;\n }\n return previous[b.length] as number;\n}\n\n/**\n * Matches a learner's input against one or more accepted answers under a\n * {@link TextMatchPolicy}. Tolerances are evaluated in stages — baseline\n * (trim/case), then normalization, then diacritic folding, then Levenshtein —\n * and {@link TextMatchResult.via} reports the first stage that produced the\n * match, so graders can award credit by match quality.\n *\n * With no policy (or an empty one) this is byte-for-byte the v1 matching\n * semantics: `trim` + locale-insensitive `toLowerCase` + strict equality.\n */\nexport function matchText(\n input: string,\n accepted: string | readonly string[],\n policy: TextMatchPolicy = {},\n): TextMatchResult {\n const acceptedList = typeof accepted === 'string' ? [accepted] : accepted;\n const baselineInput = applyBaseline(input, policy);\n const baselineAccepted = acceptedList.map((answer) => applyBaseline(answer, policy));\n\n if (baselineAccepted.some((answer) => answer === baselineInput)) {\n return { matched: true, via: 'exact' };\n }\n\n const usesNormalization =\n policy.normalize === 'NFC' ||\n policy.normalize === 'NFKC' ||\n policy.ignorePunctuation === true ||\n policy.collapseInnerWhitespace === true;\n const normalizedInput = usesNormalization\n ? applyNormalization(baselineInput, policy)\n : baselineInput;\n const normalizedAccepted = usesNormalization\n ? baselineAccepted.map((answer) => applyNormalization(answer, policy))\n : baselineAccepted;\n\n if (usesNormalization && normalizedAccepted.some((answer) => answer === normalizedInput)) {\n return { matched: true, via: 'normalized' };\n }\n\n const foldedInput =\n policy.foldDiacritics === true ? applyDiacriticFold(normalizedInput) : normalizedInput;\n const foldedAccepted =\n policy.foldDiacritics === true\n ? normalizedAccepted.map((answer) => applyDiacriticFold(answer))\n : normalizedAccepted;\n\n if (policy.foldDiacritics === true && foldedAccepted.some((answer) => answer === foldedInput)) {\n return { matched: true, via: 'folded' };\n }\n\n const maxDistance = policy.levenshtein ?? 0;\n if (\n maxDistance > 0 &&\n foldedAccepted.some(\n (answer) => levenshteinDistance(foldedInput, answer, maxDistance) <= maxDistance,\n )\n ) {\n return { matched: true, via: 'fuzzy' };\n }\n\n return { matched: false, via: 'none' };\n}\n","import type { z } from 'zod/v4';\nimport type { DeferredScoringPartial, ScoringResult } from '../types/activity.js';\n\n/** ScoringResult without `passed` — the public `score()` / `evaluate()` fill that in. */\nexport type PartialScoringResult = Omit<ScoringResult, 'passed'>;\n\n/**\n * Sensitivity classification of a single activity-data field, driving\n * `redact()`:\n * - `public` — safe to send to a learner before they answer.\n * - `answer-key` — reveals (or helps infer) the correct answer or the scoring\n * rules; removed unless `reveal: 'after-submit'` is requested.\n * - `author-only` — never leaves the authoring/grading context (e.g. rubrics).\n */\nexport type Sensitivity = 'public' | 'answer-key' | 'author-only';\n\n/**\n * Per-field sensitivity map for an activity type. A `Sensitivity` value\n * classifies the whole field (objects and arrays included); a nested\n * `FieldPolicy` recurses into an object field — and, for an array field,\n * applies to every element. Fail-closed: any field a policy does not mention\n * is treated as `author-only` and removed by `redact()` — adding a field\n * without classifying it hides it, never leaks it.\n */\nexport interface FieldPolicy {\n readonly [field: string]: Sensitivity | FieldPolicy;\n}\n\n/** xAPI interaction types defined by xAPI 1.0.3 (cmi.interaction vocabulary). */\nexport type XAPIInteractionType =\n | 'choice'\n | 'fill-in'\n | 'long-fill-in'\n | 'matching'\n | 'sequencing'\n | 'performance'\n | 'true-false'\n | 'other';\n\n/** Interop facts a generic statement builder cannot infer from data alone. */\nexport interface ActivityTypeInterop<TData> {\n /** IRI for the xAPI Activity `definition.type`. */\n readonly xapiActivityTypeIri?: string;\n /** xAPI `definition.interactionType` for this activity type. */\n readonly xapiInteractionType?: XAPIInteractionType;\n /** Builds the xAPI `correctResponsesPattern` strings for an item. */\n readonly correctResponsesPattern?: (data: TData) => string[];\n}\n\n/**\n * How responses to an activity type are graded:\n * - `sync` — a pure function produces the grade at submit time.\n * - `deferred` — grading happens asynchronously (AI or human) after\n * submission; `partial` reports the facts computable synchronously\n * (e.g. word counts), surfaced in `ItemOutcome.partial`.\n */\nexport type ActivityTypeScoring<TData, TResponse> =\n | {\n readonly kind: 'sync';\n readonly score: (data: TData, response: TResponse) => PartialScoringResult;\n }\n | {\n readonly kind: 'deferred';\n readonly reason: 'requires_async_grading';\n readonly partial?: (data: TData, response: TResponse | undefined) => DeferredScoringPartial;\n };\n\n/**\n * A value-level description of an activity type: its contract (schema), its\n * grading, its redaction policy, and its interop facts. Registering a\n * descriptor makes `validateActivity`, `score`, `evaluate`, `redact`, and\n * `jsonSchemaFor` work for the type — an activity type is a value, not a\n * hardcoded union member (R1).\n */\nexport interface ActivityTypeDescriptor<TData extends { type: string }, TResponse> {\n /** The `type` discriminator string (kebab-case by convention). */\n readonly type: TData['type'];\n /** Zod schema validating the activity's data contract. */\n readonly schema: z.ZodType<TData>;\n /** How responses are graded. */\n readonly scoring: ActivityTypeScoring<TData, TResponse>;\n /** Whether a response counts as an answer (vs. blank/untouched). */\n readonly isAnswered?: (response: TResponse | undefined) => boolean;\n /** Per-field sensitivity map driving `redact()`. Fail-closed. */\n readonly fieldPolicy?: FieldPolicy;\n /**\n * Schema the output of `redact(data)` (with default `reveal: 'none'`) must\n * satisfy. Strict by design: it proves the ABSENCE of answer-key fields,\n * so `assertRedacted` can guarantee a payload is safe to send to a learner.\n */\n readonly redactedSchema?: z.ZodType<unknown>;\n /** Interop facts for xAPI (and later QTI) statement building. */\n readonly interop?: ActivityTypeInterop<TData>;\n /** The interaction-event kinds components for this type emit. */\n readonly interactions?: readonly string[];\n}\n\n/**\n * Internal type-erased descriptor shape stored in the registry. Dispatch call\n * sites cast payloads back; the public generic API preserves inference.\n */\nexport interface RegisteredActivityTypeDescriptor {\n readonly type: string;\n readonly schema: z.ZodType<unknown>;\n readonly scoring:\n | {\n readonly kind: 'sync';\n readonly score: (data: unknown, response: unknown) => PartialScoringResult;\n }\n | {\n readonly kind: 'deferred';\n readonly reason: 'requires_async_grading';\n readonly partial?: (data: unknown, response: unknown) => DeferredScoringPartial;\n };\n readonly isAnswered?: (response: unknown) => boolean;\n readonly fieldPolicy?: FieldPolicy;\n readonly redactedSchema?: z.ZodType<unknown>;\n readonly interop?: ActivityTypeInterop<unknown>;\n readonly interactions?: readonly string[];\n}\n\n/**\n * Module-scoped default registry (deliberate — no registry instances until a\n * second consumer exists; see roadmap §3.2 / audit §15.3).\n */\nconst registry = new Map<string, RegisteredActivityTypeDescriptor>();\n\n/**\n * Identity helper that gives full type inference when authoring a descriptor:\n *\n * ```ts\n * const myType = defineActivityType<MyTypeData, MyTypeLearnerResponse>({ ... });\n * registerActivityType(myType);\n * ```\n */\nexport function defineActivityType<TData extends { type: string }, TResponse>(\n descriptor: ActivityTypeDescriptor<TData, TResponse>,\n): ActivityTypeDescriptor<TData, TResponse> {\n return descriptor;\n}\n\n/**\n * Registers an activity type on the default registry, making it live for\n * `validateActivity`, `score`, `evaluate`, `redact`, and `jsonSchemaFor`.\n * Re-registering the same descriptor object is a no-op; registering a\n * DIFFERENT descriptor under an existing type throws — silently replacing a\n * type's contract or scoring is exactly the class of accident a summative\n * SDK must not allow.\n */\nexport function registerActivityType<TData extends { type: string }, TResponse>(\n descriptor: ActivityTypeDescriptor<TData, TResponse>,\n): void {\n if (descriptor.type === 'item-group') {\n // The container that holds several items around one stimulus. It has no\n // learner response and no score of its own, so it can never satisfy this\n // contract — and letting a consumer register one would make `isItemGroup`\n // and `flattenSequence` misread their own container.\n throw new Error(\n '\"item-group\" is reserved for the SDK\\'s item-group container (see ItemGroup) and cannot be registered as an activity type.',\n );\n }\n const existing = registry.get(descriptor.type);\n if (existing !== undefined) {\n if ((existing as unknown) === (descriptor as unknown)) {\n return;\n }\n throw new Error(\n `Activity type \"${descriptor.type}\" is already registered. ` +\n 'Registering a different descriptor for an existing type is not allowed.',\n );\n }\n registry.set(descriptor.type, descriptor as unknown as RegisteredActivityTypeDescriptor);\n}\n\n/** Returns the registered descriptor for `type`, or `undefined`. */\nexport function getActivityTypeDescriptor(\n type: string,\n): RegisteredActivityTypeDescriptor | undefined {\n return registry.get(type);\n}\n\n/** The type strings currently registered (built-ins plus consumer-registered). */\nexport function registeredActivityTypes(): string[] {\n return [...registry.keys()];\n}\n","/**\n * All-or-nothing scoring: full credit only when every item is correct.\n *\n * @param correctItems - per-item correctness flags for the relevant items\n * @returns `1` if every item is correct (or the list is empty), otherwise `0`\n */\nexport function allOrNothingStrategy(correctItems: boolean[]): number {\n return correctItems.every((isCorrect) => isCorrect) ? 1 : 0;\n}\n","/**\n * Partial-credit scoring for Multiple Choice — balanced/symmetric scheme.\n *\n * Reward and penalty are each normalised by their own pool: the fraction of\n * correct options found, minus the fraction of distractors wrongly chosen.\n * This is fairer than normalising the penalty by the correct-option count —\n * under that older form a single wrong pick could zero an otherwise-correct\n * response when there was only one correct answer.\n *\n * Result is always in [0, 1]: `reward ∈ [0,1]` and `penalty ∈ [0,1]`, so\n * `reward - penalty ∈ [-1,1]` and `max(0, …)` floors it at 0. Selecting every\n * option yields `1 - 1 = 0`; selecting exactly the correct set yields `1`.\n *\n * @param correctSelected - number of selected options that are correct\n * @param incorrectSelected - number of selected options that are incorrect\n * @param totalCorrect - total correct options; the `MultipleChoiceDataSchema`\n * \"≥1 correct\" guard guarantees this is ≥ 1, so the reward term cannot\n * divide by zero for schema-validated data\n * @param totalIncorrect - total incorrect options (distractors); when `0`\n * (every option is correct) the penalty term is defined as `0`\n */\nexport function partialStrategy(\n correctSelected: number,\n incorrectSelected: number,\n totalCorrect: number,\n totalIncorrect: number,\n): number {\n const reward = correctSelected / totalCorrect;\n const penalty = totalIncorrect === 0 ? 0 : incorrectSelected / totalIncorrect;\n return Math.max(0, reward - penalty);\n}\n\n/**\n * Partial-credit scoring for Fill-in-the-Blanks: fraction of blanks answered\n * correctly. Each blank is independently right or wrong, so a plain proportion\n * is already fair — no penalty term applies.\n *\n * @param correctBlanks - number of blanks answered correctly\n * @param totalBlanks - total number of blanks; the `FillInTheBlanksDataSchema`\n * `blanks.min(1)` constraint guarantees this is ≥ 1, so division by zero\n * cannot occur for schema-validated data\n */\nexport function partialBlankStrategy(correctBlanks: number, totalBlanks: number): number {\n return correctBlanks / totalBlanks;\n}\n","import type {\n BlankConfig,\n FillInTheBlanksData,\n FillInTheBlanksLearnerResponse,\n ScoringDetail,\n} from '../../types/activity.js';\nimport { allOrNothingStrategy } from '../strategies/all-or-nothing.js';\nimport { partialBlankStrategy } from '../strategies/partial.js';\nimport { matchText, type TextMatchPolicy } from '../text-match.js';\nimport type { PartialScoringResult } from './multiple-choice.js';\n\n/**\n * Resolves the effective match policy for a blank. The legacy\n * `caseSensitive` / `trimWhitespace` flags map onto the baseline policy\n * fields; an explicit `blank.match` policy takes precedence field-by-field.\n * With neither present, the result is the v1 semantics exactly.\n */\nfunction policyFor(blank: BlankConfig): TextMatchPolicy {\n return {\n ...(blank.caseSensitive !== undefined ? { caseSensitive: blank.caseSensitive } : {}),\n ...(blank.trimWhitespace !== undefined ? { trim: blank.trimWhitespace } : {}),\n ...blank.match,\n };\n}\n\n/**\n * Scores a Fill-in-the-Blanks response. Each blank is evaluated independently\n * via {@link matchText} under the blank's resolved policy; a missing answer\n * key is treated as empty input and scored incorrect.\n */\nexport function scoreFillInTheBlanks(\n data: FillInTheBlanksData,\n response: FillInTheBlanksLearnerResponse,\n): PartialScoringResult {\n const details: ScoringDetail[] = [];\n const perBlankCorrect: boolean[] = [];\n\n for (const blank of data.blanks) {\n const rawInput = response.answers[blank.id];\n const input = typeof rawInput === 'string' ? rawInput : '';\n const matched = matchText(input, blank.acceptedAnswers, policyFor(blank)).matched;\n\n perBlankCorrect.push(matched);\n details.push({\n itemId: blank.id,\n correct: matched,\n outcome: matched ? 'correct' : 'incorrect',\n learnerResponse: [input],\n correctResponse: [...blank.acceptedAnswers],\n weight: 1,\n });\n }\n\n const correctBlanks = perBlankCorrect.filter(Boolean).length;\n const scoreValue =\n data.scoringStrategy === 'all-or-nothing'\n ? allOrNothingStrategy(perBlankCorrect)\n : partialBlankStrategy(correctBlanks, data.blanks.length);\n\n return { score: scoreValue, maxScore: 1, feedback: null, details };\n}\n","import type { PartialScoringResult } from '../../registry/registry.js';\nimport type {\n MultipleChoiceData,\n MultipleChoiceLearnerResponse,\n ScoringDetail,\n} from '../../types/activity.js';\nimport { partialStrategy } from '../strategies/partial.js';\n\nexport type { PartialScoringResult } from '../../registry/registry.js';\n\n/**\n * Scores a Multiple Choice response. Pure; trusts its typed inputs (validation\n * is the component boundary's job). Options are looked up by id; an unknown\n * selected id is treated as an incorrect selection.\n */\nexport function scoreMultipleChoice(\n data: MultipleChoiceData,\n response: MultipleChoiceLearnerResponse,\n): PartialScoringResult {\n const optionById = new Map(data.options.map((option) => [option.id, option]));\n const selected = new Set(response.selectedOptionIds);\n\n const totalCorrect = data.options.filter((option) => option.isCorrect).length;\n const totalIncorrect = data.options.length - totalCorrect;\n\n let scoreValue: number;\n\n if (data.scoringStrategy === 'all-or-nothing') {\n if (data.mode === 'single') {\n scoreValue =\n response.selectedOptionIds.length === 1 &&\n optionById.get(response.selectedOptionIds[0])?.isCorrect === true\n ? 1\n : 0;\n } else {\n const correctIds = data.options.filter((o) => o.isCorrect).map((o) => o.id);\n const allCorrectSelected = correctIds.every((id) => selected.has(id));\n scoreValue = selected.size === correctIds.length && allCorrectSelected ? 1 : 0;\n }\n } else {\n let correctSelected = 0;\n let incorrectSelected = 0;\n for (const id of selected) {\n const option = optionById.get(id);\n if (option?.isCorrect) {\n correctSelected += 1;\n } else {\n incorrectSelected += 1;\n }\n }\n scoreValue = partialStrategy(correctSelected, incorrectSelected, totalCorrect, totalIncorrect);\n }\n\n const details: ScoringDetail[] = data.options.map((option) => {\n const wasSelected = selected.has(option.id);\n const outcome = wasSelected\n ? option.isCorrect\n ? 'correct'\n : 'incorrect'\n : option.isCorrect\n ? 'incorrect-omission'\n : 'correct-omission';\n return {\n itemId: option.id,\n correct: wasSelected === option.isCorrect,\n outcome,\n learnerResponse: [wasSelected ? 'selected' : 'not-selected'],\n correctResponse: [option.isCorrect ? 'selected' : 'not-selected'],\n weight: 1,\n };\n });\n\n return { score: scoreValue, maxScore: 1, feedback: null, details };\n}\n","import type { z } from 'zod/v4';\nimport { countWords } from '../count-words.js';\nimport { FillInTheBlanksDataSchema } from '../schemas/fill-in-the-blanks.js';\nimport { MultipleChoiceDataSchema } from '../schemas/multiple-choice.js';\nimport {\n RedactedFillInTheBlanksDataSchema,\n RedactedMultipleChoiceDataSchema,\n RedactedWrittenResponseDataSchema,\n} from '../schemas/redacted.js';\nimport { WrittenResponseDataSchema } from '../schemas/written-response.js';\nimport { scoreFillInTheBlanks } from '../scoring/activity-scorers/fill-in-the-blanks.js';\nimport { scoreMultipleChoice } from '../scoring/activity-scorers/multiple-choice.js';\nimport type {\n FillInTheBlanksData,\n FillInTheBlanksLearnerResponse,\n MultipleChoiceData,\n MultipleChoiceLearnerResponse,\n WrittenResponseData,\n WrittenResponseLearnerResponse,\n} from '../types/activity.js';\nimport { defineActivityType, type FieldPolicy, registerActivityType } from './registry.js';\n\n/**\n * Field-sensitivity policies for the built-in types (R7). Fail-closed:\n * anything not listed here is dropped by `redact()`. `scoringStrategy` is\n * answer-key everywhere — MC `partial` penalises wrong selections while\n * `all-or-nothing` does not, so the strategy reveals whether guessing is\n * free. Authored feedback is answer-key (it may quote or hint the answer).\n * Rubrics are PUBLIC: a rubric tells the learner what they are assessed on,\n * and a deployment that wants it hidden tightens it per call — see the\n * `rubric` entry in the written-response policy below.\n */\nconst SHARED_PUBLIC_FIELDS: FieldPolicy = {\n schemaVersion: 'public',\n type: 'public',\n id: 'public',\n // Assembly metadata, not content: it names the slot this item occupies in a\n // paper. It has to survive redaction, or the exam client derives positional\n // slot ids while the server's stored plan holds keyed ones, and the\n // responses cannot be matched back to the attempt.\n slotKey: 'public',\n title: 'public',\n media: 'public',\n passThreshold: 'public',\n locale: 'public',\n learningObjectives: 'public',\n difficultyLevel: 'public',\n};\n\nconst MULTIPLE_CHOICE_FIELD_POLICY: FieldPolicy = {\n ...SHARED_PUBLIC_FIELDS,\n question: 'public',\n questionHtml: 'public',\n mode: 'public',\n shuffle: 'public',\n scoringStrategy: 'answer-key',\n feedback: 'answer-key',\n options: {\n id: 'public',\n text: 'public',\n isCorrect: 'answer-key',\n feedback: 'answer-key',\n },\n};\n\nconst FILL_IN_THE_BLANKS_FIELD_POLICY: FieldPolicy = {\n ...SHARED_PUBLIC_FIELDS,\n passage: 'public',\n passageHtml: 'public',\n scoringStrategy: 'answer-key',\n feedback: 'answer-key',\n blanks: {\n id: 'public',\n hint: 'public',\n acceptedAnswers: 'answer-key',\n caseSensitive: 'answer-key',\n trimWhitespace: 'answer-key',\n match: 'answer-key',\n feedback: 'answer-key',\n },\n};\n\nconst WRITTEN_RESPONSE_FIELD_POLICY: FieldPolicy = {\n ...SHARED_PUBLIC_FIELDS,\n prompt: 'public',\n promptHtml: 'public',\n minWords: 'public',\n maxWords: 'public',\n languageTarget: 'public',\n feedback: 'answer-key',\n // A rubric is a LEARNER affordance, not a grader secret: it tells the\n // learner what they are being graded on, which is pedagogically the point\n // of publishing one. (Classifying it author-only broke real deployments\n // that render a rubric panel during the attempt.) A deployment that wants\n // it hidden can tighten this per call via `redact(data, { policy })`.\n rubric: 'public',\n};\n\n/** Built-in Multiple Choice descriptor. */\nexport const multipleChoiceType = defineActivityType<\n MultipleChoiceData,\n MultipleChoiceLearnerResponse\n>({\n type: 'multiple-choice',\n // zod4 optional outputs are `T | undefined`; the hand-written wire types use\n // exact optionals. Structurally identical at runtime — cast is type-level only.\n schema: MultipleChoiceDataSchema as unknown as z.ZodType<MultipleChoiceData>,\n scoring: { kind: 'sync', score: scoreMultipleChoice },\n isAnswered: (response) => (response?.selectedOptionIds.length ?? 0) > 0,\n fieldPolicy: MULTIPLE_CHOICE_FIELD_POLICY,\n redactedSchema: RedactedMultipleChoiceDataSchema,\n interop: {\n xapiActivityTypeIri: 'http://adlnet.gov/expapi/activities/cmi.interaction',\n xapiInteractionType: 'choice',\n correctResponsesPattern: (data) => [\n data.options\n .filter((option) => option.isCorrect)\n .map((option) => option.id)\n .join('[,]'),\n ],\n },\n interactions: ['option-selected', 'option-deselected', 'submitted'],\n});\n\n/** Built-in Fill-in-the-Blanks descriptor. */\nexport const fillInTheBlanksType = defineActivityType<\n FillInTheBlanksData,\n FillInTheBlanksLearnerResponse\n>({\n type: 'fill-in-the-blanks',\n schema: FillInTheBlanksDataSchema as unknown as z.ZodType<FillInTheBlanksData>,\n scoring: { kind: 'sync', score: scoreFillInTheBlanks },\n isAnswered: (response) =>\n Object.values(response?.answers ?? {}).some((answer) => answer.trim().length > 0),\n fieldPolicy: FILL_IN_THE_BLANKS_FIELD_POLICY,\n redactedSchema: RedactedFillInTheBlanksDataSchema,\n interop: {\n xapiActivityTypeIri: 'http://adlnet.gov/expapi/activities/cmi.interaction',\n xapiInteractionType: 'fill-in',\n // xAPI fill-in pattern: blank answers joined with \"[,]\". Only the first\n // accepted answer per blank is emitted (full alternates would explode\n // combinatorially); the complete key lives in the activity data.\n correctResponsesPattern: (data) => [\n data.blanks.map((blank) => blank.acceptedAnswers[0] ?? '').join('[,]'),\n ],\n },\n interactions: ['blank-filled', 'hint-requested', 'submitted'],\n});\n\n/**\n * Built-in Written Response descriptor. Grading is DEFERRED: submissions are\n * graded asynchronously (AI or human) by the consumer; the synchronous\n * outcome reports only word-count facts. `wordCount` is recomputed from the\n * submitted text with the canonical `countWords()` — the client-supplied\n * count is informational, never trusted.\n */\nexport const writtenResponseType = defineActivityType<\n WrittenResponseData,\n WrittenResponseLearnerResponse\n>({\n type: 'written-response',\n schema: WrittenResponseDataSchema as unknown as z.ZodType<WrittenResponseData>,\n scoring: {\n kind: 'deferred',\n reason: 'requires_async_grading',\n partial: (data, response) => {\n const wordCount = countWords(response?.text ?? '');\n return {\n withinWordBounds:\n response !== undefined && wordCount >= data.minWords && wordCount <= data.maxWords,\n wordCount,\n };\n },\n },\n isAnswered: (response) => (response?.text.trim().length ?? 0) > 0,\n fieldPolicy: WRITTEN_RESPONSE_FIELD_POLICY,\n redactedSchema: RedactedWrittenResponseDataSchema,\n interop: {\n xapiActivityTypeIri: 'http://adlnet.gov/expapi/activities/cmi.interaction',\n xapiInteractionType: 'long-fill-in',\n correctResponsesPattern: () => [],\n },\n interactions: ['text-changed', 'submitted'],\n});\n\nregisterActivityType(multipleChoiceType);\nregisterActivityType(fillInTheBlanksType);\nregisterActivityType(writtenResponseType);\n"],"mappings":";AAOO,SAAS,WAAW,MAAsB;AAG/C,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO;AAAA,EACT;AACA,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,YAAY,IAAI;AAClB,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,MAAM,KAAK,EAAE;AAC9B;;;ACfO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YACkB,cACA,QAChB;AACA,UAAM,mCAAmC,YAAY,GAAG;AAHxC;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EALkB;AAAA,EACA;AAKpB;AAGO,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAClD,YAA4B,cAAsB;AAChD,UAAM,kBAAkB,YAAY,qBAAqB;AAD/B;AAE1B,SAAK,OAAO;AAAA,EACd;AAAA,EAH4B;AAI9B;AAUO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAA4B,cAAsB;AAChD;AAAA,MACE,sBAAsB,YAAY;AAAA,IAEpC;AAJ0B;AAK1B,SAAK,OAAO;AAAA,EACd;AAAA,EAN4B;AAO9B;AASO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAA4B,cAAsB;AAChD;AAAA,MACE,kBAAkB,YAAY;AAAA,IAEhC;AAJ0B;AAK1B,SAAK,OAAO;AAAA,EACd;AAAA,EAN4B;AAO9B;;;ACtDA,SAAS,SAAS;AAOX,IAAM,iBAAiB,EAAE,YAAY;AAAA,EAC1C,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACpC,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AACxC,CAAC;;;ACVD,S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AAA,EACF;AAAA,EACA,cAAc,CAAC,gBAAgB,kBAAkB,WAAW;AAC9D,CAAC;AASM,IAAM,sBAAsB,mBAGjC;AAAA,EACA,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,SAAS;AAAA,IACP,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS,CAAC,MAAM,aAAa;AAC3B,YAAM,YAAY,WAAW,UAAU,QAAQ,EAAE;AACjD,aAAO;AAAA,QACL,kBACE,aAAa,UAAa,aAAa,KAAK,YAAY,aAAa,KAAK;AAAA,QAC5E;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EACA,YAAY,CAAC,cAAc,UAAU,KAAK,KAAK,EAAE,UAAU,KAAK;AAAA,EAChE,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB,SAAS;AAAA,IACP,qBAAqB;AAAA,IACrB,qBAAqB;AAAA,IACrB,yBAAyB,MAAM,CAAC;AAAA,EAClC;AAAA,EACA,cAAc,CAAC,gBAAgB,WAAW;AAC5C,CAAC;AAED,qBAAqB,kBAAkB;AACvC,qBAAqB,mBAAmB;AACxC,qBAAqB,mBAAmB;","names":["z","z","z","z","z","z","z","z","z"]}
@@ -1,4 +1,4 @@
1
- import { A as ActivityData, c as ActivityMedia, t as ValidationResult, e as ActivityType, a as ActivityDataMap } from './activity-wkzRemHx.cjs';
1
+ import { A as ActivityData, c as ActivityMedia, t as ValidationResult, e as ActivityType, a as ActivityDataMap } from './activity-gelWNZ6V.js';
2
2
  import { z } from 'zod/v4';
3
3
 
4
4
  /** What a stimulus primarily is. Drives validation and layout, never scoring. */
@@ -56,9 +56,26 @@ interface ItemGroup<TItem = ActivityData> {
56
56
  type: 'item-group';
57
57
  id: string;
58
58
  title?: string;
59
+ /**
60
+ * Stable identity for this entry's slots, independent of where it sits in
61
+ * the array. See {@link SequenceSlot.slotId}: without one, inserting a
62
+ * question above this group re-maps every slot id beneath it, and stored
63
+ * grades quietly start naming different questions.
64
+ */
65
+ slotKey?: string;
59
66
  stimulus: Stimulus;
60
- /** The items, in authored order. Non-empty; ids unique within the group; no nested groups. */
61
- items: TItem[];
67
+ /**
68
+ * The items, in authored order. Non-empty; ids unique within the group; no
69
+ * nested groups.
70
+ *
71
+ * An item may declare its own `slotKey`, for the same reason an entry can:
72
+ * it pins the item's identity within the group (`"reading.q1"` rather than
73
+ * `"reading.0"`), so inserting a question into a published group does not
74
+ * re-map the ones after it.
75
+ */
76
+ items: (TItem & {
77
+ slotKey?: string;
78
+ })[];
62
79
  /**
63
80
  * `none` (default) keeps authored order; `within-group` shuffles the items
64
81
  * among themselves under the sequence seed. Either way the group stays one
@@ -66,8 +83,20 @@ interface ItemGroup<TItem = ActivityData> {
66
83
  */
67
84
  shuffle?: 'none' | 'within-group';
68
85
  }
69
- /** What a sequence is made of: loose activities and item groups, in authored order. */
70
- type SequenceEntry<TItem = ActivityData> = TItem | ItemGroup<TItem>;
86
+ /**
87
+ * What a sequence is made of: loose activities and item groups, in authored
88
+ * order.
89
+ *
90
+ * A plain activity may carry `slotKey` here even though no activity SCHEMA
91
+ * declares one, because a slot key describes an item's PLACE in a paper, not
92
+ * its content — the same question keeps its own id in every paper it appears
93
+ * in. Putting it on the entry rather than on the activity is what lets it be
94
+ * authored without every activity type having to know about assessment
95
+ * assembly. See {@link SequenceSlot.slotId}.
96
+ */
97
+ type SequenceEntry<TItem = ActivityData> = (TItem & {
98
+ slotKey?: string;
99
+ }) | ItemGroup<TItem>;
71
100
  /** The group a presented slot belongs to. */
72
101
  interface SequenceSlotGroup {
73
102
  id: string;
@@ -82,10 +111,20 @@ interface SequenceSlotGroup {
82
111
  interface SequenceSlot<TItem = ActivityData> {
83
112
  /**
84
113
  * Identity of the slot within the sequence definition — unique, and stable
85
- * under shuffling. Derived from the AUTHORED position (`"2"` for the third
114
+ * under shuffling. Feed it to `composeAssessmentScore` as `slotId`.
115
+ *
116
+ * By default it is derived from the AUTHORED position (`"2"` for the third
86
117
  * top-level entry; `"2.1"` for the second item of that entry when it is a
87
118
  * group), so the same activity can appear in two entries and still be two
88
- * slots. Feed it to `composeAssessmentScore` as `slotId`.
119
+ * slots.
120
+ *
121
+ * **A positional id is only valid against one version of the entries
122
+ * array.** Insert a question at the top of a published paper and every id
123
+ * below it shifts: rows stored as `"3"` now name what used to be entry 2,
124
+ * and a re-grade or a review render pairs each response with the wrong
125
+ * question — silently, because the ids still look valid. For any content
126
+ * whose slot ids you persist, give the entries an explicit `slotKey`; it is
127
+ * used verbatim here and survives insertion, deletion and re-ordering.
89
128
  */
90
129
  slotId: string;
91
130
  /** 0-based PRESENTED position, after shuffling. */
@@ -212,7 +251,7 @@ declare const FillInTheBlanksDataSchema: z.ZodObject<{
212
251
  passThreshold: z.ZodOptional<z.ZodNumber>;
213
252
  locale: z.ZodOptional<z.ZodString>;
214
253
  learningObjectives: z.ZodOptional<z.ZodArray<z.ZodString>>;
215
- difficultyLevel: z.ZodOptional<z.ZodLiteral<1 | 2 | 3 | 4 | 5>>;
254
+ difficultyLevel: z.ZodOptional<z.ZodLiteral<2 | 1 | 3 | 4 | 5>>;
216
255
  }, z.core.$loose>;
217
256
 
218
257
  /**
@@ -262,6 +301,7 @@ declare const ItemGroupSchema: z.ZodObject<{
262
301
  type: z.ZodLiteral<"item-group">;
263
302
  id: z.ZodString;
264
303
  title: z.ZodOptional<z.ZodString>;
304
+ slotKey: z.ZodOptional<z.ZodString>;
265
305
  stimulus: z.ZodObject<{
266
306
  id: z.ZodString;
267
307
  kind: z.ZodEnum<{
@@ -292,12 +332,15 @@ declare const ItemGroupSchema: z.ZodObject<{
292
332
  items: z.ZodArray<z.ZodObject<{
293
333
  type: z.ZodString;
294
334
  id: z.ZodString;
335
+ slotKey: z.ZodOptional<z.ZodString>;
295
336
  }, z.core.$loose>>;
296
337
  shuffle: z.ZodOptional<z.ZodEnum<{
297
338
  none: "none";
298
339
  "within-group": "within-group";
299
340
  }>>;
300
341
  }, z.core.$loose>;
342
+ /** The learner-safe shape of a stimulus, derived from the strict schema below. */
343
+ type RedactedStimulus = z.infer<typeof RedactedStimulusSchema>;
301
344
  /** Strict learner-safe stimulus: everything but the author-only `transcript`. */
302
345
  declare const RedactedStimulusSchema: z.ZodObject<{
303
346
  id: z.ZodString;
@@ -336,6 +379,7 @@ declare const RedactedItemGroupSchema: z.ZodObject<{
336
379
  type: z.ZodLiteral<"item-group">;
337
380
  id: z.ZodString;
338
381
  title: z.ZodOptional<z.ZodString>;
382
+ slotKey: z.ZodOptional<z.ZodString>;
339
383
  stimulus: z.ZodObject<{
340
384
  id: z.ZodString;
341
385
  kind: z.ZodEnum<{
@@ -527,7 +571,7 @@ declare const MultipleChoiceDataSchema: z.ZodObject<{
527
571
  shuffle: z.ZodOptional<z.ZodBoolean>;
528
572
  locale: z.ZodOptional<z.ZodString>;
529
573
  learningObjectives: z.ZodOptional<z.ZodArray<z.ZodString>>;
530
- difficultyLevel: z.ZodOptional<z.ZodLiteral<1 | 2 | 3 | 4 | 5>>;
574
+ difficultyLevel: z.ZodOptional<z.ZodLiteral<2 | 1 | 3 | 4 | 5>>;
531
575
  }, z.core.$loose>;
532
576
 
533
577
  /** A redacted Multiple Choice option: id and display text only — no `isCorrect`, no feedback. */
@@ -557,6 +601,8 @@ declare const RedactedMultipleChoiceDataSchema: z.ZodObject<{
557
601
  shuffle: z.ZodOptional<z.ZodBoolean>;
558
602
  /** Marker distinguishing a redacted projection from full activity data. */
559
603
  redacted: z.ZodLiteral<true>;
604
+ /** Slot identity, carried through redaction so the client and the plan agree. */
605
+ slotKey: z.ZodOptional<z.ZodString>;
560
606
  schemaVersion: z.ZodLiteral<"1.0">;
561
607
  id: z.ZodString;
562
608
  title: z.ZodString;
@@ -574,7 +620,7 @@ declare const RedactedMultipleChoiceDataSchema: z.ZodObject<{
574
620
  passThreshold: z.ZodOptional<z.ZodNumber>;
575
621
  locale: z.ZodOptional<z.ZodString>;
576
622
  learningObjectives: z.ZodOptional<z.ZodArray<z.ZodString>>;
577
- difficultyLevel: z.ZodOptional<z.ZodLiteral<1 | 2 | 3 | 4 | 5>>;
623
+ difficultyLevel: z.ZodOptional<z.ZodLiteral<2 | 1 | 3 | 4 | 5>>;
578
624
  }, z.core.$strict>;
579
625
  /** A redacted blank: id and hint only — no accepted answers, no matching rules, no feedback. */
580
626
  declare const RedactedBlankConfigSchema: z.ZodObject<{
@@ -592,6 +638,8 @@ declare const RedactedFillInTheBlanksDataSchema: z.ZodObject<{
592
638
  }, z.core.$strict>>;
593
639
  /** Marker distinguishing a redacted projection from full activity data. */
594
640
  redacted: z.ZodLiteral<true>;
641
+ /** Slot identity, carried through redaction so the client and the plan agree. */
642
+ slotKey: z.ZodOptional<z.ZodString>;
595
643
  schemaVersion: z.ZodLiteral<"1.0">;
596
644
  id: z.ZodString;
597
645
  title: z.ZodString;
@@ -609,7 +657,7 @@ declare const RedactedFillInTheBlanksDataSchema: z.ZodObject<{
609
657
  passThreshold: z.ZodOptional<z.ZodNumber>;
610
658
  locale: z.ZodOptional<z.ZodString>;
611
659
  learningObjectives: z.ZodOptional<z.ZodArray<z.ZodString>>;
612
- difficultyLevel: z.ZodOptional<z.ZodLiteral<1 | 2 | 3 | 4 | 5>>;
660
+ difficultyLevel: z.ZodOptional<z.ZodLiteral<2 | 1 | 3 | 4 | 5>>;
613
661
  }, z.core.$strict>;
614
662
  /**
615
663
  * Redacted Written Response data: the prompt, word bounds and rubric are
@@ -633,6 +681,8 @@ declare const RedactedWrittenResponseDataSchema: z.ZodObject<{
633
681
  languageTarget: z.ZodOptional<z.ZodString>;
634
682
  /** Marker distinguishing a redacted projection from full activity data. */
635
683
  redacted: z.ZodLiteral<true>;
684
+ /** Slot identity, carried through redaction so the client and the plan agree. */
685
+ slotKey: z.ZodOptional<z.ZodString>;
636
686
  schemaVersion: z.ZodLiteral<"1.0">;
637
687
  id: z.ZodString;
638
688
  title: z.ZodString;
@@ -650,8 +700,45 @@ declare const RedactedWrittenResponseDataSchema: z.ZodObject<{
650
700
  passThreshold: z.ZodOptional<z.ZodNumber>;
651
701
  locale: z.ZodOptional<z.ZodString>;
652
702
  learningObjectives: z.ZodOptional<z.ZodArray<z.ZodString>>;
653
- difficultyLevel: z.ZodOptional<z.ZodLiteral<1 | 2 | 3 | 4 | 5>>;
703
+ difficultyLevel: z.ZodOptional<z.ZodLiteral<2 | 1 | 3 | 4 | 5>>;
654
704
  }, z.core.$strict>;
705
+ /**
706
+ * The learner-safe SHAPE of each built-in type, derived from the strict schema
707
+ * above rather than hand-written beside it.
708
+ *
709
+ * `redact()` returns {@link RedactedActivityData}, which proves a payload is
710
+ * learner-safe but is index-signature typed — it deliberately says nothing
711
+ * about what the payload still CONTAINS. That is right for the assertion and
712
+ * useless for anything that has to render or transport the result, so every
713
+ * integrator ends up re-declaring these interfaces by hand and they drift the
714
+ * moment a schema changes. Deriving them with `z.infer` means the type and the
715
+ * validator can never disagree.
716
+ *
717
+ * Use them for the payload a server sends an exam client, and for the props of
718
+ * a renderer that must never see an answer key.
719
+ */
720
+ type RedactedMultipleChoiceOption = z.infer<typeof RedactedMultipleChoiceOptionSchema>;
721
+ /** A Multiple Choice item with the answer key, feedback and strategy removed. */
722
+ type RedactedMultipleChoiceData = z.infer<typeof RedactedMultipleChoiceDataSchema>;
723
+ /** A blank with its accepted answers and matching rules removed; the hint survives. */
724
+ type RedactedBlankConfig = z.infer<typeof RedactedBlankConfigSchema>;
725
+ /** A Fill-in-the-Blanks item with every accepted answer removed. */
726
+ type RedactedFillInTheBlanksData = z.infer<typeof RedactedFillInTheBlanksDataSchema>;
727
+ /** A Written Response item; the rubric survives, because it tells the learner what is assessed. */
728
+ type RedactedWrittenResponseData = z.infer<typeof RedactedWrittenResponseDataSchema>;
729
+ /**
730
+ * Discriminated union of every built-in redacted activity. Narrow it on
731
+ * `type`, exactly as you would {@link ActivityData}:
732
+ *
733
+ * ```ts
734
+ * function render(item: RedactedActivity) {
735
+ * if (item.type === 'multiple-choice') {
736
+ * return item.options.map((option) => option.text); // no `isCorrect` to leak
737
+ * }
738
+ * }
739
+ * ```
740
+ */
741
+ type RedactedActivity = RedactedMultipleChoiceData | RedactedFillInTheBlanksData | RedactedWrittenResponseData;
655
742
 
656
743
  /** Zod schema for a single rubric criterion. Loose: unknown keys preserved. */
657
744
  declare const WrittenResponseRubricCriterionSchema: z.ZodObject<{
@@ -712,7 +799,7 @@ declare const WrittenResponseDataSchema: z.ZodObject<{
712
799
  passThreshold: z.ZodOptional<z.ZodNumber>;
713
800
  locale: z.ZodOptional<z.ZodString>;
714
801
  learningObjectives: z.ZodOptional<z.ZodArray<z.ZodString>>;
715
- difficultyLevel: z.ZodOptional<z.ZodLiteral<1 | 2 | 3 | 4 | 5>>;
802
+ difficultyLevel: z.ZodOptional<z.ZodLiteral<2 | 1 | 3 | 4 | 5>>;
716
803
  }, z.core.$loose>;
717
804
 
718
805
  /**
@@ -729,4 +816,4 @@ declare const WrittenResponseDataSchema: z.ZodObject<{
729
816
  */
730
817
  declare function validateActivity<T extends ActivityType>(type: T, data: unknown): ValidationResult<ActivityDataMap[T]>;
731
818
 
732
- export { BlankConfigSchema as B, FeedbackSchema as F, type ItemGroup as I, MediaSchema as M, RedactedBlankConfigSchema as R, type SequenceEntry as S, TextMatchPolicySchema as T, WrittenResponseDataSchema as W, FillInTheBlanksDataSchema as a, ItemGroupSchema as b, MediaUrlSchema as c, MultipleChoiceDataSchema as d, MultipleChoiceOptionSchema as e, RedactedFillInTheBlanksDataSchema as f, RedactedItemGroupSchema as g, RedactedMultipleChoiceDataSchema as h, RedactedMultipleChoiceOptionSchema as i, RedactedStimulusSchema as j, RedactedWrittenResponseDataSchema as k, type SequenceSlot as l, type SequenceSlotGroup as m, type Stimulus as n, type StimulusKind as o, StimulusSchema as p, WrittenResponseRubricCriterionSchema as q, WrittenResponseRubricSchema as r, fillInTheBlanksJsonSchema as s, itemGroupJsonSchema as t, jsonSchemaFor as u, multipleChoiceJsonSchema as v, stimulusJsonSchema as w, validateActivity as x, validateItemGroup as y, writtenResponseJsonSchema as z };
819
+ export { itemGroupJsonSchema as A, BlankConfigSchema as B, jsonSchemaFor as C, multipleChoiceJsonSchema as D, stimulusJsonSchema as E, FeedbackSchema as F, validateActivity as G, validateItemGroup as H, type ItemGroup as I, writtenResponseJsonSchema as J, MediaSchema as M, type RedactedActivity as R, type SequenceEntry as S, TextMatchPolicySchema as T, WrittenResponseDataSchema as W, FillInTheBlanksDataSchema as a, ItemGroupSchema as b, MediaUrlSchema as c, MultipleChoiceDataSchema as d, MultipleChoiceOptionSchema as e, type RedactedBlankConfig as f, RedactedBlankConfigSchema as g, type RedactedFillInTheBlanksData as h, RedactedFillInTheBlanksDataSchema as i, RedactedItemGroupSchema as j, type RedactedMultipleChoiceData as k, RedactedMultipleChoiceDataSchema as l, type RedactedMultipleChoiceOption as m, RedactedMultipleChoiceOptionSchema as n, type RedactedStimulus as o, RedactedStimulusSchema as p, type RedactedWrittenResponseData as q, RedactedWrittenResponseDataSchema as r, type SequenceSlot as s, type SequenceSlotGroup as t, type Stimulus as u, type StimulusKind as v, StimulusSchema as w, WrittenResponseRubricCriterionSchema as x, WrittenResponseRubricSchema as y, fillInTheBlanksJsonSchema as z };