@pie-qti/item-player 0.1.6 → 0.1.8

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 (54) hide show
  1. package/dist/catalog/applyGlossaryTriggers.d.ts +2 -1
  2. package/dist/catalog/applyGlossaryTriggers.d.ts.map +1 -1
  3. package/dist/catalog/applyGlossaryTriggers.js +145 -30
  4. package/dist/catalog/glossaryAction.d.ts.map +1 -1
  5. package/dist/catalog/glossaryAction.js +14 -4
  6. package/dist/components/utils/stimulusRender.d.ts +17 -0
  7. package/dist/components/utils/stimulusRender.d.ts.map +1 -0
  8. package/dist/components/utils/stimulusRender.js +70 -0
  9. package/dist/components/utils/stylesheetRender.d.ts +4 -0
  10. package/dist/components/utils/stylesheetRender.d.ts.map +1 -0
  11. package/dist/components/utils/stylesheetRender.js +57 -0
  12. package/dist/core/Player.d.ts +37 -2
  13. package/dist/core/Player.d.ts.map +1 -1
  14. package/dist/core/Player.js +320 -48
  15. package/dist/core/sanitizer.d.ts.map +1 -1
  16. package/dist/core/sanitizer.js +60 -0
  17. package/dist/document/AssessmentItemDocument.d.ts +4 -0
  18. package/dist/document/AssessmentItemDocument.d.ts.map +1 -1
  19. package/dist/document/AssessmentItemDocument.js +53 -4
  20. package/dist/element.js +2027 -1532
  21. package/dist/element.js.map +1 -1
  22. package/dist/index.d.ts +1 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/interactions/extended-text/extractor.d.ts +1 -0
  25. package/dist/interactions/extended-text/extractor.d.ts.map +1 -1
  26. package/dist/interactions/extended-text/extractor.js +2 -0
  27. package/dist/interactions/shared/types.d.ts +1 -0
  28. package/dist/interactions/shared/types.d.ts.map +1 -1
  29. package/dist/pnp/applyPnp.d.ts.map +1 -1
  30. package/dist/pnp/applyPnp.js +9 -2
  31. package/dist/pnp/parsePnpXml.d.ts.map +1 -1
  32. package/dist/pnp/parsePnpXml.js +91 -3
  33. package/dist/pnp/types.d.ts +24 -1
  34. package/dist/pnp/types.d.ts.map +1 -1
  35. package/dist/types/index.d.ts +47 -0
  36. package/dist/types/index.d.ts.map +1 -1
  37. package/package.json +6 -6
  38. package/src/catalog/applyGlossaryTriggers.ts +174 -34
  39. package/src/catalog/glossaryAction.ts +14 -4
  40. package/src/components/ItemBody.svelte +36 -27
  41. package/src/components/utils/stimulusRender.ts +93 -0
  42. package/src/components/utils/stylesheetRender.ts +58 -0
  43. package/src/core/Player.ts +355 -48
  44. package/src/core/sanitizer.ts +70 -0
  45. package/src/document/AssessmentItemDocument.ts +76 -7
  46. package/src/index.ts +1 -0
  47. package/src/interactions/extended-text/extractor.ts +3 -0
  48. package/src/interactions/shared/types.ts +1 -0
  49. package/src/pnp/applyPnp.ts +8 -2
  50. package/src/pnp/parsePnpXml.ts +102 -5
  51. package/src/pnp/types.ts +43 -1
  52. package/src/types/index.ts +53 -0
  53. package/src/__tests__/glossaryTriggers.test.ts +0 -411
  54. package/src/__tests__/pnp.test.ts +0 -250
@@ -8,8 +8,9 @@ import { createComponentRegistry } from './ComponentRegistry.js';
8
8
  import { createSeededRng } from './random.js';
9
9
  import { sanitizeHtml } from './sanitizer.js';
10
10
  import { toTrustedHtml } from './trustedTypes.js';
11
+ import { sanitizeResourceUrl } from './urlPolicy.js';
11
12
  import { applyPnpToRoot } from '../pnp/applyPnp.js';
12
- import { extractCatalogFromItemXml, mergeCatalogs } from '../catalog/catalogExtractor.js';
13
+ import { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from '../catalog/catalogExtractor.js';
13
14
  import { getCatalogEntry } from '../catalog/catalogLookup.js';
14
15
  import { PciHost } from '../pci/PciHost.js';
15
16
  export class Player {
@@ -18,10 +19,16 @@ export class Player {
18
19
  this.templateProcessingProgram = null;
19
20
  this.outcomeProcessingProgram = null;
20
21
  this._catalogIndex = new Map();
22
+ this._stimulusCatalogIndexes = new Map();
21
23
  this._pciHosts = new Map();
24
+ this._pnpChangeListeners = new Set();
25
+ this.lifecycleStatus = 'initial';
26
+ this.accumulatedDurationMs = 0;
22
27
  this.config = config;
23
28
  this.itemXml = config.itemXml ?? '';
24
29
  this.role = config.role ?? 'candidate';
30
+ this.sessionGuid = createSessionGuid();
31
+ this.sessionStartedAt = Date.now();
25
32
  this.rng = config.rng ?? (typeof config.seed === 'number' ? createSeededRng(config.seed) : Math.random);
26
33
  // Auto-detect QTI version and create appropriate mappers if not provided
27
34
  if (!config.elementNameMapper) {
@@ -129,16 +136,24 @@ export class Player {
129
136
  }
130
137
  // Store PNP profile for later use (applyPnpToRoot is called once a root element is available).
131
138
  this._pnp = config.pnp;
132
- // Build catalog index from item XML and optional shared catalog.
133
- const itemCatalog = extractCatalogFromItemXml(this.itemXml);
134
- if (config.catalogXml) {
135
- const sharedCatalog = extractCatalogFromItemXml(config.catalogXml);
136
- // Item-level wins on collision: merge shared first, then override with item entries.
137
- this._catalogIndex = mergeCatalogs(sharedCatalog, itemCatalog);
139
+ // Build catalog index from resolved delivery context, legacy shared catalog XML, and item XML.
140
+ // Item/global entries are merged first; item-level entries win on global collisions.
141
+ // Stimulus entries are kept separately so rendered stimulus terms can avoid ID collisions.
142
+ let mergedCatalog = new Map();
143
+ for (const source of config.deliveryContext?.catalogSources ?? []) {
144
+ const sourceCatalog = extractCatalog(source.xml);
145
+ if (source.scope === 'stimulus' && source.stimulusIdentifier) {
146
+ const existing = this._stimulusCatalogIndexes.get(source.stimulusIdentifier) ?? new Map();
147
+ this._stimulusCatalogIndexes.set(source.stimulusIdentifier, mergeCatalogs(existing, sourceCatalog));
148
+ }
149
+ else {
150
+ mergedCatalog = mergeCatalogs(mergedCatalog, sourceCatalog);
151
+ }
138
152
  }
139
- else {
140
- this._catalogIndex = itemCatalog;
153
+ if (config.catalogXml) {
154
+ mergedCatalog = mergeCatalogs(mergedCatalog, extractCatalogFromItemXml(config.catalogXml));
141
155
  }
156
+ this._catalogIndex = mergeCatalogs(mergedCatalog, extractCatalogFromItemXml(this.itemXml));
142
157
  // Check strict compliance if enabled
143
158
  if (this.config.strictQtiCompliance?.enabled) {
144
159
  this.validateStrictCompliance();
@@ -162,19 +177,43 @@ export class Player {
162
177
  if (this._rootEl) {
163
178
  applyPnpToRoot(this._rootEl, this._pnp);
164
179
  }
180
+ for (const listener of this._pnpChangeListeners) {
181
+ listener(this._pnp);
182
+ }
165
183
  }
166
184
  /** Return the current resolved PNP profile. */
167
185
  getPnp() {
168
186
  return this._pnp;
169
187
  }
188
+ onPnpChange(listener) {
189
+ this._pnpChangeListeners.add(listener);
190
+ return () => this._pnpChangeListeners.delete(listener);
191
+ }
192
+ /** Return the package/assessment-resolved delivery context, if one was supplied. */
193
+ getDeliveryContext() {
194
+ return this.config.deliveryContext;
195
+ }
170
196
  /**
171
197
  * Look up a catalog entry by card identifier, usage type, and optional language.
172
198
  * Returns the HTML string for the matched entry, or null if not found.
173
199
  *
174
200
  * Language fallback: exact match → prefix match → no-lang entry → null.
175
201
  */
176
- getCatalogEntry(idref, usage, lang) {
177
- return getCatalogEntry(this._catalogIndex, idref, usage, lang);
202
+ getCatalogEntry(idref, usage, lang, options) {
203
+ const stimulusHtml = options?.stimulusIdentifier
204
+ ? getCatalogEntry(this._stimulusCatalogIndexes.get(options.stimulusIdentifier) ?? new Map(), idref, usage, lang)
205
+ : null;
206
+ const html = stimulusHtml ?? getCatalogEntry(this._catalogIndex, idref, usage, lang);
207
+ if (html === null)
208
+ return null;
209
+ if (looksLikeCatalogUrl(html)) {
210
+ return sanitizeResourceUrl(html.trim(), this.config.security?.urlPolicy, 'img');
211
+ }
212
+ return this.sanitizeHtmlContent(html);
213
+ }
214
+ /** Sanitize externally resolved item-adjacent HTML before it reaches a rendering sink. */
215
+ sanitizeHtmlContent(html) {
216
+ return sanitizeHtml(html, { security: this.config.security });
178
217
  }
179
218
  /**
180
219
  * Create a PciHost for an extracted PCI and register it for response tracking.
@@ -245,45 +284,110 @@ export class Player {
245
284
  this.destroyPciHosts();
246
285
  }
247
286
  processResponses() {
248
- // Spec-aligned behavior: each processing run starts from outcome defaults.
249
- // This prevents stale outcomes when response/outcome processing doesn't set every variable.
250
- this.resetOutcomesToDefault();
251
- // Execute response processing if present
252
- const rpEl = this.itemDocument.getProcessingElement('response');
253
- if (rpEl) {
254
- // If responseProcessing has explicit statements, run the compiled program.
255
- // Otherwise, fall back to template-based processing (responseProcessing@template).
256
- const hasStatements = childElements(rpEl).length > 0;
257
- if (hasStatements) {
258
- this.execResponseProcessingProgram();
259
- }
260
- else {
261
- const templateUrl = getAttr(rpEl, 'template');
262
- if (templateUrl)
263
- this.execResponseProcessingTemplate(templateUrl);
264
- }
287
+ return this.runResponseProcessing({ finalizeNonAdaptiveAttempt: true });
288
+ }
289
+ saveItemSession() {
290
+ this.freezeDuration();
291
+ return this.serializeItemSession();
292
+ }
293
+ restoreItemSession(state) {
294
+ this.sessionGuid = state.sessionGuid;
295
+ this.lifecycleStatus = state.lifecycleStatus;
296
+ this.accumulatedDurationMs = Math.max(0, Number(state.duration) || 0);
297
+ this.sessionStartedAt = Date.now();
298
+ this.applySerializedVariables(state.responseVariables);
299
+ this.applySerializedVariables(state.outcomeVariables);
300
+ this.applySerializedVariables(state.templateVariables);
301
+ this.applySerializedVariables(state.contextVariables);
302
+ this.updateDuration();
303
+ }
304
+ suspendAttempt() {
305
+ const validation = this.validateResponses(this.getResponses());
306
+ this.lifecycleStatus = 'suspended';
307
+ const sessionState = this.saveItemSession();
308
+ return {
309
+ action: 'suspendAttempt',
310
+ lifecycleStatus: this.lifecycleStatus,
311
+ completionStatus: this.getCompletionStatus(),
312
+ numAttempts: this.getNumAttempts(),
313
+ duration: sessionState.duration,
314
+ completed: this.isCompleted(),
315
+ sessionState,
316
+ validation,
317
+ };
318
+ }
319
+ endAttempt(options = {}) {
320
+ const validate = options.validateResponses ?? false;
321
+ const validation = validate ? this.validateResponses(this.getResponses()) : undefined;
322
+ if (validation && !validation.valid) {
323
+ const sessionState = this.saveItemSession();
324
+ return {
325
+ action: 'endAttempt',
326
+ lifecycleStatus: this.lifecycleStatus,
327
+ completionStatus: this.getCompletionStatus(),
328
+ numAttempts: this.getNumAttempts(),
329
+ duration: sessionState.duration,
330
+ completed: this.isCompleted(),
331
+ sessionState,
332
+ validation,
333
+ };
265
334
  }
266
- // Execute outcome processing if present (runs after responseProcessing)
267
- this.execOutcomeProcessingProgram();
268
- // For non-adaptive items, update completionStatus and numAttempts after processing
269
- if (!this.isAdaptive()) {
270
- // Set completionStatus to 'completed' for non-adaptive items (single submission)
271
- this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'completed'));
272
- // Increment numAttempts for non-adaptive items (tracks total submissions, including retries)
273
- const currentAttempts = this.getNumAttempts();
274
- this.ctx.setValue('numAttempts', qtiValue('integer', 'single', currentAttempts + 1));
335
+ const scoring = this.isAdaptive()
336
+ ? this.submitAttempt(options.countAttempt ?? true)
337
+ : this.runResponseProcessing({
338
+ finalizeNonAdaptiveAttempt: true,
339
+ countAttempt: options.countAttempt ?? true,
340
+ });
341
+ this.lifecycleStatus = scoring.completed ? 'closed' : 'interacting';
342
+ const sessionState = this.saveItemSession();
343
+ return {
344
+ action: 'endAttempt',
345
+ lifecycleStatus: this.lifecycleStatus,
346
+ completionStatus: this.getCompletionStatus(),
347
+ numAttempts: this.getNumAttempts(),
348
+ duration: sessionState.duration,
349
+ completed: scoring.completed,
350
+ sessionState,
351
+ validation,
352
+ scoring,
353
+ };
354
+ }
355
+ scoreAttempt() {
356
+ const scoring = this.runResponseProcessing({ finalizeNonAdaptiveAttempt: false });
357
+ const sessionState = this.saveItemSession();
358
+ return {
359
+ action: 'scoreAttempt',
360
+ lifecycleStatus: this.lifecycleStatus,
361
+ completionStatus: this.getCompletionStatus(),
362
+ numAttempts: this.getNumAttempts(),
363
+ duration: sessionState.duration,
364
+ completed: scoring.completed,
365
+ sessionState,
366
+ scoring,
367
+ };
368
+ }
369
+ newTemplate(options = {}) {
370
+ this.resetOutcomesToDefault();
371
+ if (options.resetResponses ?? true) {
372
+ this.resetResponsesToDefault();
275
373
  }
276
- const outcomes = this.collectOutcomes();
277
- const score = Number(outcomes.SCORE ?? 0);
278
- const maxScore = Number(outcomes.MAXSCORE ?? 1);
279
- const completionStatus = outcomes.completionStatus ?? 'not_attempted';
280
- const completed = completionStatus === 'completed' || !this.isAdaptive();
374
+ this.resetTemplatesToDefault();
375
+ this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'not_attempted'));
376
+ this.ctx.setValue('numAttempts', qtiValue('integer', 'single', 0));
377
+ this.execTemplateProcessing();
378
+ this.lifecycleStatus = 'initial';
379
+ this.accumulatedDurationMs = 0;
380
+ this.sessionStartedAt = Date.now();
381
+ this.updateDuration();
382
+ const sessionState = this.serializeItemSession();
281
383
  return {
282
- score,
283
- maxScore,
284
- completed,
285
- outcomeValues: outcomes,
286
- modalFeedback: this.getModalFeedback(outcomes),
384
+ action: 'newTemplate',
385
+ lifecycleStatus: this.lifecycleStatus,
386
+ completionStatus: this.getCompletionStatus(),
387
+ numAttempts: this.getNumAttempts(),
388
+ duration: sessionState.duration,
389
+ completed: this.isCompleted(),
390
+ sessionState,
287
391
  };
288
392
  }
289
393
  getSecurityConfig() {
@@ -389,11 +493,70 @@ export class Player {
389
493
  continue;
390
494
  // Built-in stateful variables must survive across processing runs.
391
495
  // They are updated by the runtime (adaptive attempt tracking), not by outcome defaults.
392
- if (d.identifier === 'numAttempts' || d.identifier === 'completionStatus')
496
+ if (d.identifier === 'numAttempts' || d.identifier === 'completionStatus' || d.identifier === 'duration')
497
+ continue;
498
+ this.ctx.resetToDefault(d.identifier);
499
+ }
500
+ }
501
+ resetResponsesToDefault() {
502
+ for (const d of Object.values(this.decls)) {
503
+ if (d.__kind !== 'response')
504
+ continue;
505
+ this.ctx.resetToDefault(d.identifier);
506
+ this.setPciResponse(d.identifier, d.value.kind === 'value' ? d.value.value : null);
507
+ }
508
+ }
509
+ resetTemplatesToDefault() {
510
+ for (const d of Object.values(this.decls)) {
511
+ if (!d.isTemplate)
393
512
  continue;
394
513
  this.ctx.resetToDefault(d.identifier);
395
514
  }
396
515
  }
516
+ runResponseProcessing(options) {
517
+ this.updateDuration();
518
+ // Spec-aligned behavior: each processing run starts from outcome defaults.
519
+ // This prevents stale outcomes when response/outcome processing doesn't set every variable.
520
+ this.resetOutcomesToDefault();
521
+ // Execute response processing if present
522
+ const rpEl = this.itemDocument.getProcessingElement('response');
523
+ if (rpEl) {
524
+ // If responseProcessing has explicit statements, run the compiled program.
525
+ // Otherwise, fall back to template-based processing (responseProcessing@template).
526
+ const hasStatements = childElements(rpEl).length > 0;
527
+ if (hasStatements) {
528
+ this.execResponseProcessingProgram();
529
+ }
530
+ else {
531
+ const templateUrl = getAttr(rpEl, 'template');
532
+ if (templateUrl)
533
+ this.execResponseProcessingTemplate(templateUrl);
534
+ }
535
+ }
536
+ // Execute outcome processing if present (runs after responseProcessing)
537
+ this.execOutcomeProcessingProgram();
538
+ // Compatibility: processResponses() has historically finalized non-adaptive items.
539
+ // New scoreAttempt() uses this same engine with finalization disabled.
540
+ if (!this.isAdaptive() && options.finalizeNonAdaptiveAttempt) {
541
+ this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'completed'));
542
+ if (options.countAttempt ?? true) {
543
+ const currentAttempts = this.getNumAttempts();
544
+ this.ctx.setValue('numAttempts', qtiValue('integer', 'single', currentAttempts + 1));
545
+ }
546
+ }
547
+ const outcomes = this.collectOutcomes();
548
+ const score = Number(outcomes.SCORE ?? 0);
549
+ const maxScore = Number(outcomes.MAXSCORE ?? 1);
550
+ const completionStatus = outcomes.completionStatus ?? 'not_attempted';
551
+ const completed = completionStatus === 'completed' || (!this.isAdaptive() && options.finalizeNonAdaptiveAttempt);
552
+ return {
553
+ score,
554
+ maxScore,
555
+ completed,
556
+ outcomeValues: outcomes,
557
+ modalFeedback: this.getModalFeedback(outcomes),
558
+ };
559
+ }
397
560
  getItemBodyHtml() {
398
561
  const inner = this.itemDocument.serializeItemBodyChildren();
399
562
  if (!inner)
@@ -910,12 +1073,25 @@ export class Player {
910
1073
  identifier: 'numAttempts',
911
1074
  baseType: 'integer',
912
1075
  cardinality: 'single',
1076
+ defaultValue: qtiValue('integer', 'single', 0),
913
1077
  value: qtiValue('integer', 'single', 0),
914
1078
  isTemplate: false,
915
1079
  // @ts-expect-error internal marker
916
1080
  __kind: 'outcome',
917
1081
  };
918
1082
  }
1083
+ if (!decls.duration) {
1084
+ decls.duration = {
1085
+ identifier: 'duration',
1086
+ baseType: 'duration',
1087
+ cardinality: 'single',
1088
+ defaultValue: qtiValue('duration', 'single', 0),
1089
+ value: qtiValue('duration', 'single', 0),
1090
+ isTemplate: false,
1091
+ // @ts-expect-error internal marker
1092
+ __kind: 'outcome',
1093
+ };
1094
+ }
919
1095
  // Common scoring defaults
920
1096
  if (!decls.SCORE) {
921
1097
  decls.SCORE = {
@@ -947,6 +1123,91 @@ export class Player {
947
1123
  continue;
948
1124
  d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
949
1125
  }
1126
+ const restoredDuration = Number(state.duration);
1127
+ if (Number.isFinite(restoredDuration) && restoredDuration >= 0) {
1128
+ this.accumulatedDurationMs = restoredDuration;
1129
+ this.sessionStartedAt = Date.now();
1130
+ this.updateDuration();
1131
+ }
1132
+ }
1133
+ applySerializedVariables(vars) {
1134
+ for (const v of Object.values(vars)) {
1135
+ const d = this.decls[v.identifier];
1136
+ if (!d)
1137
+ continue;
1138
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, v.value);
1139
+ if (d.__kind === 'response') {
1140
+ this.setPciResponse(d.identifier, v.value);
1141
+ }
1142
+ }
1143
+ }
1144
+ serializeItemSession() {
1145
+ const responseVariables = {};
1146
+ const outcomeVariables = {};
1147
+ const templateVariables = {};
1148
+ const contextVariables = {};
1149
+ const contextIds = new Set(['completionStatus', 'numAttempts', 'duration']);
1150
+ for (const d of Object.values(this.decls)) {
1151
+ const variable = this.serializeVariable(d);
1152
+ if (d.isTemplate) {
1153
+ templateVariables[d.identifier] = { ...variable, kind: 'template' };
1154
+ }
1155
+ else if (contextIds.has(d.identifier)) {
1156
+ contextVariables[d.identifier] = { ...variable, kind: 'context' };
1157
+ }
1158
+ else if (d.__kind === 'response') {
1159
+ responseVariables[d.identifier] = { ...variable, kind: 'response' };
1160
+ }
1161
+ else if (d.__kind === 'outcome') {
1162
+ outcomeVariables[d.identifier] = { ...variable, kind: 'outcome' };
1163
+ }
1164
+ }
1165
+ const validation = this.validateResponses(this.getResponses());
1166
+ return {
1167
+ itemIdentifier: this.itemDocument.getAssessmentItemAttribute('identifier') ?? undefined,
1168
+ sessionGuid: this.sessionGuid,
1169
+ lifecycleStatus: this.lifecycleStatus,
1170
+ completionStatus: this.getCompletionStatus(),
1171
+ numAttempts: this.getNumAttempts(),
1172
+ duration: this.getDuration(),
1173
+ responseVariables,
1174
+ outcomeVariables,
1175
+ templateVariables,
1176
+ contextVariables,
1177
+ validationMessages: validation.issues,
1178
+ savedAt: new Date().toISOString(),
1179
+ };
1180
+ }
1181
+ serializeVariable(d) {
1182
+ return {
1183
+ identifier: d.identifier,
1184
+ kind: (d.__kind ?? (d.isTemplate ? 'template' : 'context')),
1185
+ baseType: d.baseType,
1186
+ cardinality: d.cardinality,
1187
+ value: this.qtiValueToSerializable(d.value),
1188
+ defaultValue: this.qtiValueToSerializable(d.defaultValue),
1189
+ };
1190
+ }
1191
+ qtiValueToSerializable(value) {
1192
+ if (!value || value.kind !== 'value')
1193
+ return null;
1194
+ return value.value;
1195
+ }
1196
+ updateDuration() {
1197
+ const elapsedMs = Math.max(0, Date.now() - this.sessionStartedAt);
1198
+ const durationMs = this.accumulatedDurationMs + elapsedMs;
1199
+ this.ctx.setValue('duration', qtiValue('duration', 'single', durationMs));
1200
+ }
1201
+ freezeDuration() {
1202
+ this.updateDuration();
1203
+ const duration = this.getDuration();
1204
+ this.accumulatedDurationMs = duration;
1205
+ this.sessionStartedAt = Date.now();
1206
+ return duration;
1207
+ }
1208
+ getDuration() {
1209
+ const value = this.ctx.getValue('duration');
1210
+ return Math.max(0, Math.floor(toNumber(value) || 0));
950
1211
  }
951
1212
  parseDefaultValue(declEl, baseType, cardinality) {
952
1213
  const defaultEl = findFirstDescendant(declEl, this.mapper.toNative('defaultvalue'));
@@ -1132,3 +1393,14 @@ function mergePnp(base, partial) {
1132
1393
  cognitive: { ...(base?.cognitive ?? {}), ...(partial.cognitive ?? {}) },
1133
1394
  };
1134
1395
  }
1396
+ function createSessionGuid() {
1397
+ if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
1398
+ return crypto.randomUUID();
1399
+ }
1400
+ return `item-session-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
1401
+ }
1402
+ function looksLikeCatalogUrl(value) {
1403
+ const trimmed = value.trim();
1404
+ return /^(https?:\/\/|\/\/|\/|\.{0,2}\/|data:|blob:)/i.test(trimmed) ||
1405
+ /\.(png|jpe?g|gif|webp|svg|mp3|wav|ogg|mp4|webm|pdf)(\?.*)?$/i.test(trimmed);
1406
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"sanitizer.d.ts","sourceRoot":"","sources":["../../src/core/sanitizer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,KAAK,EAAE,oBAAoB,EAAmB,MAAM,mBAAmB,CAAC;AAI/E,MAAM,WAAW,mBAAmB;IACnC;;;OAGG;IACH,QAAQ,CAAC,EAAE,oBAAoB,CAAC;CAChC;AA+ID;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,CA0ChF;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,CAYvF"}
1
+ {"version":3,"file":"sanitizer.d.ts","sourceRoot":"","sources":["../../src/core/sanitizer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,KAAK,EAAE,oBAAoB,EAAmB,MAAM,mBAAmB,CAAC;AAI/E,MAAM,WAAW,mBAAmB;IACnC;;;OAGG;IACH,QAAQ,CAAC,EAAE,oBAAoB,CAAC;CAChC;AAiKD;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,CA0ChF;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,CAYvF"}
@@ -25,6 +25,17 @@ function allowObjectEmbeds(options) {
25
25
  function allowIframes(options) {
26
26
  return options?.security?.allowIframes === true;
27
27
  }
28
+ function escapeAttr(value) {
29
+ return value
30
+ .replace(/&/g, '&')
31
+ .replace(/"/g, '"')
32
+ .replace(/</g, '&lt;')
33
+ .replace(/>/g, '&gt;');
34
+ }
35
+ function getOptionalAttr(element, attrName) {
36
+ const value = element.getAttribute(attrName);
37
+ return value ? ` ${attrName}="${escapeAttr(value)}"` : '';
38
+ }
28
39
  function sanitizeUrlAttr(value, policy, kind) {
29
40
  return sanitizeResourceUrl(value, policy, kind) ?? '#';
30
41
  }
@@ -74,6 +85,11 @@ function sanitizeElement(element, options, limitsState, depth) {
74
85
  return;
75
86
  }
76
87
  if ((tagName === 'object' || tagName === 'embed') && !allowObjectEmbeds(options)) {
88
+ const replacementHtml = getSafeObjectReplacementHtml(element, policyFromOptions(options));
89
+ if (replacementHtml) {
90
+ element.replaceWith(replacementHtml);
91
+ return;
92
+ }
77
93
  element.remove();
78
94
  return;
79
95
  }
@@ -196,3 +212,47 @@ export function sanitizeTextContent(text, options) {
196
212
  // Plain text - return as-is
197
213
  return text;
198
214
  }
215
+ function getSafeObjectReplacementHtml(element, policy) {
216
+ if (element.rawTagName?.toLowerCase() !== 'object') {
217
+ return null;
218
+ }
219
+ const rawType = element.getAttribute('type')?.trim().toLowerCase() ?? '';
220
+ const rawData = element.getAttribute('data')?.trim() ?? '';
221
+ if (!rawType || !rawData) {
222
+ return null;
223
+ }
224
+ const dimensions = `${getOptionalAttr(element, 'width')}${getOptionalAttr(element, 'height')}`;
225
+ const classes = getOptionalAttr(element, 'class');
226
+ const id = getOptionalAttr(element, 'id');
227
+ if (rawType.startsWith('image/')) {
228
+ const src = sanitizeResourceUrl(rawData, policy, 'img');
229
+ if (!src) {
230
+ return null;
231
+ }
232
+ const alt = element.getAttribute('aria-label') ??
233
+ element.getAttribute('title') ??
234
+ element.textContent?.trim() ??
235
+ '';
236
+ return `<img src="${escapeAttr(src)}" alt="${escapeAttr(alt)}"${dimensions}${classes}${id}>`;
237
+ }
238
+ if (rawType.startsWith('audio/')) {
239
+ const src = sanitizeResourceUrl(rawData, policy, 'media');
240
+ if (!src) {
241
+ return null;
242
+ }
243
+ return `<audio controls${classes}${id}><source src="${escapeAttr(src)}" type="${escapeAttr(rawType)}"></audio>`;
244
+ }
245
+ if (rawType.startsWith('video/')) {
246
+ const src = sanitizeResourceUrl(rawData, policy, 'media');
247
+ if (!src) {
248
+ return null;
249
+ }
250
+ const rawPoster = element.getAttribute('poster')?.trim() ?? '';
251
+ const poster = rawPoster
252
+ ? sanitizeResourceUrl(rawPoster, policy, 'img')
253
+ : null;
254
+ const posterAttr = poster ? ` poster="${escapeAttr(poster)}"` : '';
255
+ return `<video controls${dimensions}${classes}${id}${posterAttr}><source src="${escapeAttr(src)}" type="${escapeAttr(rawType)}"></video>`;
256
+ }
257
+ return null;
258
+ }
@@ -17,6 +17,7 @@ export interface AssessmentItemDocumentInput {
17
17
  export declare class AssessmentItemDocument {
18
18
  private readonly itemXml;
19
19
  private readonly security?;
20
+ private readonly mathMlPrefixes;
20
21
  readonly elementNameMapper: ElementNameMapper;
21
22
  readonly attributeNameMapper: AttributeNameMapper;
22
23
  private readonly xmlDocument;
@@ -35,6 +36,9 @@ export declare class AssessmentItemDocument {
35
36
  findExtractionElements(elementTypes: Iterable<string>): DiscoveredInteractionElement[];
36
37
  private getExtractionRoot;
37
38
  private getExtractionDocument;
39
+ private getItemBodyElement;
40
+ private serializeItemBodyForExtraction;
41
+ private serializeChildNodes;
38
42
  private walkExtractionChildren;
39
43
  private getExtractionResponseIdentifier;
40
44
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AssessmentItemDocument.d.ts","sourceRoot":"","sources":["../../src/document/AssessmentItemDocument.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAYlF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAE3D,MAAM,MAAM,cAAc,GAAG,UAAU,GAAG,UAAU,GAAG,SAAS,CAAC;AAEjE,MAAM,WAAW,4BAA4B;IAC5C,OAAO,EAAE,UAAU,CAAC;IACpB,WAAW,EAAE,UAAU,CAAC;IACxB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,cAAc,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,2BAA2B;IAC3C,OAAO,EAAE,MAAM,CAAC;IAChB,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,mBAAmB,EAAE,mBAAmB,CAAC;IACzC,QAAQ,CAAC,EAAE,oBAAoB,CAAC;CAChC;AAED,qBAAa,sBAAsB;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAuB;IACjD,QAAQ,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IAC9C,QAAQ,CAAC,mBAAmB,EAAE,mBAAmB,CAAC;IAClD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAW;IACvC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAU;IACzC,OAAO,CAAC,kBAAkB,CAA2B;IACrD,OAAO,CAAC,cAAc,CAA2B;gBAErC,EACX,OAAO,EACP,iBAAiB,EACjB,mBAAmB,EACn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C,sBAAsB;IAS9B,OAAO,CAAC,+BAA+B;CAUvC;AAED,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,2BAA2B,GAAG,sBAAsB,CAEtG"}
@@ -1,4 +1,4 @@
1
- import { childElements, findAssessmentItem, findDescendants, findFirstDescendant, parseXml, serializeXml, } from '@pie-qti/qti-processing';
1
+ import { findAssessmentItem, findDescendants, findFirstDescendant, parseXml, serializeXml, } from '@pie-qti/qti-processing';
2
2
  import { parse } from 'node-html-parser';
3
3
  import { enforceItemXmlLimits } from '../core/parsingLimits.js';
4
4
  import { normalizeInteractionTypeFromTagName } from '../interactions/modules.js';
@@ -8,6 +8,7 @@ export class AssessmentItemDocument {
8
8
  this.extractionRoot = null;
9
9
  this.itemXml = itemXml;
10
10
  this.security = security;
11
+ this.mathMlPrefixes = findMathMlPrefixes(itemXml);
11
12
  this.elementNameMapper = elementNameMapper;
12
13
  this.attributeNameMapper = attributeNameMapper;
13
14
  enforceItemXmlLimits(this.itemXml, this.security);
@@ -26,7 +27,7 @@ export class AssessmentItemDocument {
26
27
  return findFirstDescendant(this.assessmentItem, this.elementNameMapper.toNative(tagName));
27
28
  }
28
29
  serializeItemBodyChildren() {
29
- const itemBody = findFirstDescendant(this.assessmentItem, this.elementNameMapper.toNative('itembody'));
30
+ const itemBody = this.getItemBodyElement();
30
31
  if (!itemBody)
31
32
  return '';
32
33
  return this.serializeChildren(itemBody);
@@ -49,7 +50,7 @@ export class AssessmentItemDocument {
49
50
  return this.assessmentItem.getAttribute(this.attributeNameMapper.toNative(name));
50
51
  }
51
52
  serializeChildren(element) {
52
- return childElements(element).map((child) => serializeXml(child)).join('');
53
+ return normalizeMathMlPrefixes(unwrapCdataSections(this.serializeChildNodes(element)), this.mathMlPrefixes);
53
54
  }
54
55
  findExtractionElements(elementTypes) {
55
56
  const root = this.getExtractionRoot();
@@ -86,13 +87,35 @@ export class AssessmentItemDocument {
86
87
  getExtractionDocument() {
87
88
  if (!this.extractionDocument) {
88
89
  enforceItemXmlLimits(this.itemXml, this.security);
89
- this.extractionDocument = parse(this.itemXml, {
90
+ this.extractionDocument = parse(this.serializeItemBodyForExtraction(), {
90
91
  lowerCaseTagName: false,
91
92
  comment: false,
92
93
  });
93
94
  }
94
95
  return this.extractionDocument;
95
96
  }
97
+ getItemBodyElement() {
98
+ return findFirstDescendant(this.assessmentItem, this.elementNameMapper.toNative('itembody'));
99
+ }
100
+ serializeItemBodyForExtraction() {
101
+ const itemBodyTag = this.elementNameMapper.toNative('itembody');
102
+ const itemBody = this.getItemBodyElement();
103
+ const itemBodyChildren = itemBody ? this.serializeChildren(itemBody) : '';
104
+ return `<assessmentItem><${itemBodyTag}>${itemBodyChildren}</${itemBodyTag}></assessmentItem>`;
105
+ }
106
+ serializeChildNodes(element) {
107
+ const children = element.childNodes;
108
+ if (!children)
109
+ return '';
110
+ const serialized = [];
111
+ for (let index = 0; index < children.length; index++) {
112
+ const child = children[index];
113
+ if (child) {
114
+ serialized.push(serializeXml(child));
115
+ }
116
+ }
117
+ return serialized.join('');
118
+ }
96
119
  walkExtractionChildren(root, visit) {
97
120
  for (const child of root.childNodes ?? []) {
98
121
  const element = child;
@@ -114,3 +137,29 @@ export class AssessmentItemDocument {
114
137
  export function parseAssessmentItemDocument(input) {
115
138
  return new AssessmentItemDocument(input);
116
139
  }
140
+ function unwrapCdataSections(xml) {
141
+ return xml.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, (_match, content) => content);
142
+ }
143
+ function findMathMlPrefixes(xml) {
144
+ const prefixes = new Set();
145
+ for (const match of xml.matchAll(/\sxmlns:([A-Za-z_][\w.-]*)=(["'])http:\/\/www\.w3\.org\/1998\/Math\/MathML\2/g)) {
146
+ const prefix = match[1];
147
+ if (prefix) {
148
+ prefixes.add(prefix);
149
+ }
150
+ }
151
+ return prefixes;
152
+ }
153
+ function normalizeMathMlPrefixes(xml, prefixes) {
154
+ let normalized = xml;
155
+ for (const prefix of prefixes) {
156
+ const escapedPrefix = escapeRegExp(prefix);
157
+ normalized = normalized
158
+ .replace(new RegExp(`(<\\/?)${escapedPrefix}:([A-Za-z][\\w.-]*)(?=[\\s>/])`, 'g'), '$1$2')
159
+ .replace(new RegExp(`\\sxmlns:${escapedPrefix}=(["'])http:\\/\\/www\\.w3\\.org\\/1998\\/Math\\/MathML\\1`, 'g'), '');
160
+ }
161
+ return normalized;
162
+ }
163
+ function escapeRegExp(value) {
164
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
165
+ }