@pie-qti/item-player 0.1.14 → 0.1.16

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 (90) hide show
  1. package/README.md +18 -6
  2. package/dist/components/utils/feedbackUtils.js +19 -8
  3. package/dist/components/utils/feedbackUtils.js.map +1 -1
  4. package/dist/core/ComponentRegistry.js +1 -0
  5. package/dist/core/ComponentRegistry.js.map +1 -1
  6. package/dist/core/Player.d.ts +4 -0
  7. package/dist/core/Player.js +296 -89
  8. package/dist/core/Player.js.map +1 -1
  9. package/dist/core/declarations.js +11 -4
  10. package/dist/core/declarations.js.map +1 -1
  11. package/dist/core/sanitizer.js +119 -1
  12. package/dist/core/sanitizer.js.map +1 -1
  13. package/dist/core/shuffle.d.ts +42 -0
  14. package/dist/core/shuffle.js +83 -0
  15. package/dist/core/shuffle.js.map +1 -0
  16. package/dist/core/urlPolicy.js +34 -23
  17. package/dist/core/urlPolicy.js.map +1 -1
  18. package/dist/element-class-hT-bDysz.js +6808 -0
  19. package/dist/element-class-hT-bDysz.js.map +1 -0
  20. package/dist/element-class.d.ts +73 -0
  21. package/dist/element-class.js +2 -0
  22. package/dist/element.d.ts +6 -40
  23. package/dist/element.js +4 -6296
  24. package/dist/element.js.map +1 -1
  25. package/dist/extraction/ExtractionRegistry.js +1 -1
  26. package/dist/extraction/ExtractionRegistry.js.map +1 -1
  27. package/dist/extraction/createContext.d.ts +1 -1
  28. package/dist/extraction/createContext.js +5 -1
  29. package/dist/extraction/createContext.js.map +1 -1
  30. package/dist/extraction/interactionExtractionPipeline.d.ts +6 -1
  31. package/dist/extraction/interactionExtractionPipeline.js +6 -3
  32. package/dist/extraction/interactionExtractionPipeline.js.map +1 -1
  33. package/dist/extraction/types.d.ts +10 -0
  34. package/dist/extraction/types.js.map +1 -1
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.js +1 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/interactions/associate/extractor.js +2 -1
  39. package/dist/interactions/associate/extractor.js.map +1 -1
  40. package/dist/interactions/choice/extractor.js +2 -1
  41. package/dist/interactions/choice/extractor.js.map +1 -1
  42. package/dist/interactions/custom/extractor.js +22 -2
  43. package/dist/interactions/custom/extractor.js.map +1 -1
  44. package/dist/interactions/extended-text/extractor.d.ts +6 -0
  45. package/dist/interactions/extended-text/extractor.js +40 -6
  46. package/dist/interactions/extended-text/extractor.js.map +1 -1
  47. package/dist/interactions/extended-text/index.d.ts +1 -0
  48. package/dist/interactions/extended-text/index.js +1 -0
  49. package/dist/interactions/extended-text/index.js.map +1 -1
  50. package/dist/interactions/extended-text/response.d.ts +31 -0
  51. package/dist/interactions/extended-text/response.js +193 -0
  52. package/dist/interactions/extended-text/response.js.map +1 -0
  53. package/dist/interactions/gap-match/extractor.js +8 -7
  54. package/dist/interactions/gap-match/extractor.js.map +1 -1
  55. package/dist/interactions/inline-choice/extractor.js +2 -1
  56. package/dist/interactions/inline-choice/extractor.js.map +1 -1
  57. package/dist/interactions/match/extractor.js +3 -2
  58. package/dist/interactions/match/extractor.js.map +1 -1
  59. package/dist/interactions/modules.d.ts +4 -0
  60. package/dist/interactions/modules.js +2 -0
  61. package/dist/interactions/modules.js.map +1 -1
  62. package/dist/interactions/order/extractor.js +2 -1
  63. package/dist/interactions/order/extractor.js.map +1 -1
  64. package/dist/interactions/portable-custom/extractor.d.ts +3 -2
  65. package/dist/interactions/portable-custom/extractor.js +66 -25
  66. package/dist/interactions/portable-custom/extractor.js.map +1 -1
  67. package/dist/interactions/portable-custom/index.d.ts +1 -1
  68. package/dist/interactions/portable-custom/index.js.map +1 -1
  69. package/dist/interactions/portable-custom/types.d.ts +1 -1
  70. package/dist/interactions/portable-custom/types.js.map +1 -1
  71. package/dist/interactions/position-object/extractor.d.ts +5 -35
  72. package/dist/interactions/position-object/extractor.js +58 -153
  73. package/dist/interactions/position-object/extractor.js.map +1 -1
  74. package/dist/interactions/shared/types.d.ts +15 -1
  75. package/dist/interactions/shared/types.js.map +1 -1
  76. package/dist/pci/PciHost.d.ts +14 -9
  77. package/dist/pci/PciHost.js +89 -22
  78. package/dist/pci/PciHost.js.map +1 -1
  79. package/dist/pci/index.d.ts +3 -0
  80. package/dist/pci/index.js +3 -0
  81. package/dist/pci/index.js.map +1 -0
  82. package/dist/pci/types.d.ts +72 -0
  83. package/dist/pci/types.js +12 -0
  84. package/dist/pci/types.js.map +1 -1
  85. package/dist/presentation/itemPresentationPlan.d.ts +2 -0
  86. package/dist/presentation/itemPresentationPlan.js +6 -0
  87. package/dist/presentation/itemPresentationPlan.js.map +1 -1
  88. package/dist/types/index.d.ts +26 -5
  89. package/dist/types/index.js.map +1 -1
  90. package/package.json +15 -7
@@ -13,6 +13,7 @@ import { applyPnpToRoot } from '../pnp/applyPnp.js';
13
13
  import { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from '../catalog/catalogExtractor.js';
14
14
  import { getCatalogEntry } from '../catalog/catalogLookup.js';
15
15
  import { PciHost } from '../pci/PciHost.js';
16
+ import { createExtendedTextNumericRecord, EXTENDED_TEXT_RECORD_FIELD_TYPES, } from '../interactions/extended-text/response.js';
16
17
  export class Player {
17
18
  constructor(config) {
18
19
  this.responseProcessingProgram = null;
@@ -100,24 +101,24 @@ export class Player {
100
101
  }
101
102
  }
102
103
  // Build ASTs once.
104
+ const processingBuildOptions = {
105
+ elementNameMapper: this.mapper,
106
+ resolveProcessingFragment: config.resolveProcessingFragment,
107
+ maxProcessingFragmentDepth: config.processingFragmentLimits?.maxDepth,
108
+ maxProcessingFragmentCharacters: config.processingFragmentLimits?.maxCharacters,
109
+ };
103
110
  const templateProcessing = this.itemDocument.getProcessingElement('template');
104
111
  if (templateProcessing) {
105
- this.templateProcessingProgram = buildTemplateProcessingAst(templateProcessing, {
106
- elementNameMapper: this.mapper,
107
- });
112
+ this.templateProcessingProgram = buildTemplateProcessingAst(templateProcessing, processingBuildOptions);
108
113
  this.execTemplateProcessing();
109
114
  }
110
115
  const responseProcessing = this.itemDocument.getProcessingElement('response');
111
116
  if (responseProcessing) {
112
- this.responseProcessingProgram = buildResponseProcessingAst(responseProcessing, {
113
- elementNameMapper: this.mapper,
114
- });
117
+ this.responseProcessingProgram = buildResponseProcessingAst(responseProcessing, processingBuildOptions);
115
118
  }
116
119
  const outcomeProcessing = this.itemDocument.getProcessingElement('outcome');
117
120
  if (outcomeProcessing) {
118
- this.outcomeProcessingProgram = buildOutcomeProcessingAst(outcomeProcessing, {
119
- elementNameMapper: this.mapper,
120
- });
121
+ this.outcomeProcessingProgram = buildOutcomeProcessingAst(outcomeProcessing, processingBuildOptions);
121
122
  }
122
123
  // Apply initial responses after templateProcessing (so template vars are ready).
123
124
  if (config.responses) {
@@ -223,13 +224,15 @@ export class Player {
223
224
  * host.initialize(domNode) once the DOM element is available.
224
225
  */
225
226
  createPciHost(data) {
226
- const baseUrl = this.config.pciBaseUrl ?? (typeof document !== 'undefined' ? document.baseURI : '');
227
- const host = new PciHost(data, baseUrl);
227
+ const host = new PciHost(data, {
228
+ baseUrl: this.config.pci?.baseUrl ?? this.config.pciBaseUrl,
229
+ moduleResolver: this.config.pci?.moduleResolver,
230
+ });
228
231
  // Wire response changes back into the player's declaration context
229
232
  host.onResponseChange((responseId, value) => {
230
233
  const d = this.decls[responseId];
231
234
  if (d) {
232
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, value);
235
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, value, d.identifier);
233
236
  }
234
237
  });
235
238
  this._pciHosts.set(data.responseIdentifier, host);
@@ -273,7 +276,7 @@ export class Player {
273
276
  const d = this.decls[id];
274
277
  if (!d)
275
278
  continue;
276
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
279
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);
277
280
  // Push restored responses into any mounted PCI modules
278
281
  this.setPciResponse(id, raw);
279
282
  }
@@ -616,6 +619,10 @@ export class Player {
616
619
  extractionRegistry: this.extractionRegistry,
617
620
  declarations: this.decls,
618
621
  config: this.config,
622
+ // Seeds `shuffle`. The GUID is persisted in saved state and restored, so a
623
+ // resumed session reproduces the order the candidate already saw, while a
624
+ // different candidate or a new attempt gets a different one.
625
+ sessionGuid: this.sessionGuid,
619
626
  });
620
627
  }
621
628
  /**
@@ -689,7 +696,12 @@ export class Player {
689
696
  for (const d of Object.values(this.decls)) {
690
697
  if (d.__kind !== 'response')
691
698
  continue;
692
- out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
699
+ const pciHost = this._pciHosts.get(d.identifier);
700
+ if (pciHost) {
701
+ const currentResponse = pciHost.getResponse();
702
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, currentResponse, d.identifier);
703
+ }
704
+ out[d.identifier] = this.qtiValueToPublic(d.value);
693
705
  }
694
706
  return out;
695
707
  }
@@ -707,7 +719,7 @@ export class Player {
707
719
  return undefined;
708
720
  if (respDecl.correctResponse.kind !== 'value')
709
721
  return undefined;
710
- return respDecl.correctResponse.value;
722
+ return this.qtiValueToPublic(respDecl.correctResponse);
711
723
  }
712
724
  /**
713
725
  * Get all correct responses as a map
@@ -721,7 +733,7 @@ export class Player {
721
733
  const respDecl = d;
722
734
  if (!respDecl.correctResponse || respDecl.correctResponse.kind !== 'value')
723
735
  continue;
724
- out[d.identifier] = respDecl.correctResponse.value;
736
+ out[d.identifier] = this.qtiValueToPublic(respDecl.correctResponse);
725
737
  }
726
738
  return out;
727
739
  }
@@ -730,7 +742,7 @@ export class Player {
730
742
  for (const d of Object.values(this.decls)) {
731
743
  if (!d.isTemplate)
732
744
  continue;
733
- out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
745
+ out[d.identifier] = this.qtiValueToPublic(d.value);
734
746
  }
735
747
  return out;
736
748
  }
@@ -739,13 +751,13 @@ export class Player {
739
751
  const d = this.decls[id];
740
752
  if (!d?.isTemplate)
741
753
  continue;
742
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
754
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);
743
755
  }
744
756
  }
745
757
  getSessionState() {
746
758
  const out = {};
747
759
  for (const d of Object.values(this.decls)) {
748
- out[d.identifier] = d.value.kind === 'value' ? d.value.value : null;
760
+ out[d.identifier] = this.qtiValueToPublic(d.value);
749
761
  }
750
762
  return out;
751
763
  }
@@ -757,8 +769,27 @@ export class Player {
757
769
  const responseId = i.responseIdentifier;
758
770
  const decl = this.decls[responseId];
759
771
  const value = responses[responseId];
772
+ const isMeaningfulEntry = (entry) => {
773
+ if (entry === null || entry === undefined)
774
+ return false;
775
+ if (typeof entry !== 'string')
776
+ return true;
777
+ const comparable = i.type === 'extendedTextInteraction' && i.format === 'xhtml'
778
+ ? entry.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;/gi, ' ')
779
+ : entry;
780
+ return comparable.trim().length > 0;
781
+ };
782
+ const constrainedChoices = [
783
+ ...(i.choices ?? []),
784
+ ...(i.gapTexts ?? []),
785
+ ...(i.gapImages ?? []),
786
+ ...(i.sourceSet ?? []),
787
+ ...(i.targetSet ?? []),
788
+ ...(i.associableHotspots ?? []),
789
+ ];
790
+ const minimum = Math.max(0, Number(i.minChoices ?? 0), Number(i.minAssociations ?? 0), Number(i.minStrings ?? 0), Number(i.minPlays ?? 0));
760
791
  const required = i.type !== 'endAttemptInteraction' &&
761
- (i.type !== 'mediaInteraction' || (typeof i.minPlays === 'number' && i.minPlays > 0));
792
+ (minimum > 0 || constrainedChoices.some((choice) => Number(choice.matchMin ?? 0) > 0));
762
793
  let complete = !required;
763
794
  if (i.type === 'mediaInteraction' && required) {
764
795
  const minPlays = Number(i.minPlays || 0);
@@ -766,24 +797,17 @@ export class Player {
766
797
  }
767
798
  else if (required) {
768
799
  if (Array.isArray(value)) {
769
- complete = value.length > 0;
800
+ const nonEmptyValues = value.filter(isMeaningfulEntry);
801
+ complete = nonEmptyValues.length > 0;
770
802
  // Enforce minChoices / minAssociations where applicable
771
- const minChoices = Number(i.minChoices || i.minAssociations || 0);
803
+ const minChoices = Math.max(Number(i.minChoices ?? 0), Number(i.minAssociations ?? 0), Number(i.minStrings ?? 0));
772
804
  if (complete && minChoices > 0) {
773
- complete = value.length >= minChoices;
805
+ complete = nonEmptyValues.length >= minChoices;
774
806
  }
775
807
  // Enforce matchMin per-choice: each pairing entry "id1 id2" in value must
776
808
  // appear at least matchMin times for the relevant choice.
777
809
  // Collect all choice arrays that can carry matchMin across all pairing interaction types.
778
- const choices = [
779
- ...(i.choices ?? []),
780
- ...(i.gapTexts ?? []),
781
- ...(i.gapImages ?? []),
782
- ...(i.sourceSet ?? []),
783
- ...(i.targetSet ?? []),
784
- ...(i.associableHotspots ?? []),
785
- ];
786
- for (const choice of choices) {
810
+ for (const choice of constrainedChoices) {
787
811
  const min = Number(choice.matchMin || 0);
788
812
  if (min > 0) {
789
813
  const count = value.filter((p) => {
@@ -797,8 +821,14 @@ export class Player {
797
821
  }
798
822
  }
799
823
  }
824
+ else if (decl?.cardinality === 'record') {
825
+ const stringValue = value && typeof value === 'object'
826
+ ? value.stringValue
827
+ : undefined;
828
+ complete = isMeaningfulEntry(stringValue);
829
+ }
800
830
  else {
801
- complete = value !== null && value !== undefined && value !== '';
831
+ complete = isMeaningfulEntry(value);
802
832
  }
803
833
  }
804
834
  const errors = [];
@@ -809,12 +839,23 @@ export class Player {
809
839
  errors.push(`Expected an array for ${decl.cardinality} response '${responseId}'`);
810
840
  }
811
841
  }
842
+ else if (decl.cardinality === 'record') {
843
+ if (!(value === null || value === undefined || (typeof value === 'object' && !Array.isArray(value)))) {
844
+ errors.push(`Expected an object for record response '${responseId}'`);
845
+ }
846
+ }
812
847
  else {
813
848
  if (Array.isArray(value)) {
814
849
  errors.push(`Expected a single value for response '${responseId}'`);
815
850
  }
816
851
  }
817
852
  }
853
+ if (i.type === 'extendedTextInteraction' &&
854
+ Array.isArray(value) &&
855
+ Number(i.maxStrings ?? 0) > 0 &&
856
+ value.filter(isMeaningfulEntry).length > Number(i.maxStrings)) {
857
+ errors.push(`Response '${responseId}' exceeds maxStrings=${i.maxStrings}`);
858
+ }
818
859
  const valid = errors.length === 0;
819
860
  entries[responseId] = {
820
861
  responseId,
@@ -857,17 +898,33 @@ export class Player {
857
898
  for (const i of this.getResponseInteractions()) {
858
899
  const id = i.responseIdentifier;
859
900
  const v = responses[id];
901
+ const isMeaningful = (entry) => {
902
+ if (entry === null || entry === undefined)
903
+ return false;
904
+ if (typeof entry !== 'string')
905
+ return true;
906
+ const comparable = i.type === 'extendedTextInteraction' && i.format === 'xhtml'
907
+ ? entry.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;/gi, ' ')
908
+ : entry;
909
+ return comparable.trim().length > 0;
910
+ };
860
911
  if (i.type === 'mediaInteraction') {
861
912
  if (Number(v || 0) > 0)
862
913
  return true;
863
914
  continue;
864
915
  }
865
916
  if (Array.isArray(v)) {
866
- if (v.length > 0)
917
+ if (v.some(isMeaningful))
918
+ return true;
919
+ continue;
920
+ }
921
+ if (v && typeof v === 'object') {
922
+ const record = v;
923
+ if (Object.values(record).some(isMeaningful))
867
924
  return true;
868
925
  continue;
869
926
  }
870
- if (v !== null && v !== undefined && v !== '')
927
+ if (isMeaningful(v))
871
928
  return true;
872
929
  }
873
930
  return false;
@@ -911,19 +968,48 @@ export class Player {
911
968
  console.warn(`[QTI Player] Could not extract template name from URL: ${templateUrl}`);
912
969
  return;
913
970
  }
914
- const responseDeclIds = Object.values(this.decls)
915
- .filter((d) => d.__kind === 'response')
916
- .map((d) => d.identifier);
971
+ const responseMatchesCorrect = () => {
972
+ const expression = {
973
+ kind: 'expr.match',
974
+ id: 'fixed-template-match',
975
+ a: { kind: 'expr.variable', id: 'fixed-template-response', identifier: 'RESPONSE' },
976
+ b: { kind: 'expr.correct', id: 'fixed-template-correct', identifier: 'RESPONSE' },
977
+ };
978
+ return toBoolean(evalExpr({ ctx: this.ctx, ops: this.ops, rng: this.rng, customOperators: this.config.customOperators }, expression));
979
+ };
980
+ const setScore = (value) => {
981
+ this.ctx.setValue('SCORE', qtiValue('float', 'single', value));
982
+ };
983
+ const setIdentifierOutcome = (identifier, value) => {
984
+ this.ctx.setValue(identifier, qtiValue('identifier', 'single', value));
985
+ };
986
+ const mapResponse = (point) => {
987
+ const response = this.ctx.getValue('RESPONSE');
988
+ if (response.kind === 'null')
989
+ return 0;
990
+ const mapped = evalExpr({ ctx: this.ctx, ops: this.ops, rng: this.rng, customOperators: this.config.customOperators }, {
991
+ kind: point ? 'expr.mapResponsePoint' : 'expr.mapResponse',
992
+ id: point ? 'fixed-template-map-response-point' : 'fixed-template-map-response',
993
+ identifier: 'RESPONSE',
994
+ });
995
+ const value = toNumber(mapped);
996
+ return Number.isFinite(value) ? value : 0;
997
+ };
917
998
  switch (name) {
918
999
  case 'match_correct':
919
- case 'cc2_match': { // CC2_match is an alias for match_correct (QTI 2.1 compatibility)
920
- const allCorrect = responseDeclIds.every((id) => {
921
- const expr = { kind: 'expr.match', id: 'tmp', a: { kind: 'expr.variable', id: 'tmp', identifier: id }, b: { kind: 'expr.correct', id: 'tmp', identifier: id } };
922
- // Use evaluator match semantics by evaluating a constructed MatchExpr
923
- return toBoolean(evalExpr({ ctx: this.ctx, ops: this.ops, rng: this.rng, customOperators: this.config.customOperators }, expr));
924
- });
925
- const max = toNumber(this.ctx.getValue('MAXSCORE'));
926
- this.ctx.setValue('SCORE', qtiValue('float', 'single', allCorrect ? (Number.isFinite(max) ? max : 1) : 0));
1000
+ case 'cc2_match': {
1001
+ setScore(responseMatchesCorrect() ? 1 : 0);
1002
+ return;
1003
+ }
1004
+ case 'cc2_match_basic': {
1005
+ if (responseMatchesCorrect()) {
1006
+ const maxScore = toNumber(this.ctx.getValue('MAXSCORE'));
1007
+ this.ctx.setValue('SCORE', Number.isFinite(maxScore) ? qtiValue('float', 'single', maxScore) : qtiNull('float', 'single'));
1008
+ setIdentifierOutcome('FEEDBACKBASIC', 'correct');
1009
+ }
1010
+ else {
1011
+ setIdentifierOutcome('FEEDBACKBASIC', 'incorrect');
1012
+ }
927
1013
  return;
928
1014
  }
929
1015
  case 'match_nothing':
@@ -943,35 +1029,25 @@ export class Player {
943
1029
  return v.value.trim().length === 0;
944
1030
  return false;
945
1031
  };
946
- const allEmpty = responseDeclIds.every((id) => isEmptyResponse(this.ctx.getValue(id)));
1032
+ const allEmpty = isEmptyResponse(this.ctx.getValue('RESPONSE'));
947
1033
  const max = toNumber(this.ctx.getValue('MAXSCORE'));
948
1034
  this.ctx.setValue('SCORE', qtiValue('float', 'single', allEmpty ? (Number.isFinite(max) ? max : 1) : 0));
949
1035
  return;
950
1036
  }
951
- case 'map_response':
952
- case 'cc2_map_response': { // QTI 2.1 compatibility
953
- let total = 0;
954
- for (const id of responseDeclIds) {
955
- const d = this.decls[id];
956
- if (!d.mapping)
957
- continue;
958
- const v = evalExpr({ ctx: this.ctx, ops: this.ops, rng: this.rng }, { kind: 'expr.mapResponse', id: 'tmp', identifier: id });
959
- total += toNumber(v) || 0;
960
- }
961
- this.ctx.setValue('SCORE', qtiValue('float', 'single', total));
1037
+ case 'map_response': {
1038
+ setScore(mapResponse(false));
1039
+ return;
1040
+ }
1041
+ case 'cc2_map_response': {
1042
+ const score = mapResponse(false);
1043
+ setScore(score);
1044
+ const maxScore = toNumber(this.ctx.getValue('MAXSCORE'));
1045
+ setIdentifierOutcome('FEEDBACK', Number.isFinite(maxScore) && score === maxScore ? 'correct' : 'incorrect');
962
1046
  return;
963
1047
  }
964
1048
  case 'map_response_point':
965
1049
  case 'cc2_map_response_point': { // QTI 2.1 compatibility
966
- let total = 0;
967
- for (const id of responseDeclIds) {
968
- const d = this.decls[id];
969
- if (!d.areaMapping)
970
- continue;
971
- const v = evalExpr({ ctx: this.ctx, ops: this.ops, rng: this.rng }, { kind: 'expr.mapResponsePoint', id: 'tmp', identifier: id });
972
- total += toNumber(v) || 0;
973
- }
974
- this.ctx.setValue('SCORE', qtiValue('float', 'single', total));
1050
+ setScore(mapResponse(true));
975
1051
  return;
976
1052
  }
977
1053
  default:
@@ -987,13 +1063,15 @@ export class Player {
987
1063
  const addDecl = (kind, el) => {
988
1064
  const identifier = this.getAttrMapped(el, 'identifier');
989
1065
  const cardinality = (this.getAttrMapped(el, 'cardinality') || 'single');
990
- const baseType = (this.getAttrMapped(el, 'baseType') || 'string');
1066
+ const baseType = cardinality === 'record'
1067
+ ? undefined
1068
+ : (this.getAttrMapped(el, 'baseType') || 'string');
991
1069
  if (!identifier)
992
1070
  return;
993
1071
  const defaultValue = this.parseDefaultValue(el, baseType, cardinality);
994
1072
  decls[identifier] = {
995
1073
  identifier,
996
- baseType,
1074
+ ...(baseType ? { baseType } : {}),
997
1075
  cardinality,
998
1076
  defaultValue,
999
1077
  value: defaultValue,
@@ -1005,7 +1083,7 @@ export class Player {
1005
1083
  // (Templates do not participate in mapping.)
1006
1084
  if (kind === 'response' || kind === 'outcome') {
1007
1085
  const mappingEl = findFirstDescendant(el, this.mapper.toNative('mapping'));
1008
- if (mappingEl) {
1086
+ if (mappingEl && baseType) {
1009
1087
  decls[identifier].mapping = this.parseMapping(mappingEl, baseType);
1010
1088
  }
1011
1089
  }
@@ -1135,7 +1213,7 @@ export class Player {
1135
1213
  const d = this.decls[id];
1136
1214
  if (!d)
1137
1215
  continue;
1138
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw);
1216
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);
1139
1217
  }
1140
1218
  const restoredDuration = Number(state.duration);
1141
1219
  if (Number.isFinite(restoredDuration) && restoredDuration >= 0) {
@@ -1149,7 +1227,7 @@ export class Player {
1149
1227
  const d = this.decls[v.identifier];
1150
1228
  if (!d)
1151
1229
  continue;
1152
- d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, v.value);
1230
+ d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, v.value, d.identifier);
1153
1231
  if (d.__kind === 'response') {
1154
1232
  this.setPciResponse(d.identifier, v.value);
1155
1233
  }
@@ -1196,7 +1274,7 @@ export class Player {
1196
1274
  return {
1197
1275
  identifier: d.identifier,
1198
1276
  kind: (d.__kind ?? (d.isTemplate ? 'template' : 'context')),
1199
- baseType: d.baseType,
1277
+ ...(d.baseType ? { baseType: d.baseType } : {}),
1200
1278
  cardinality: d.cardinality,
1201
1279
  value: this.qtiValueToSerializable(d.value),
1202
1280
  defaultValue: this.qtiValueToSerializable(d.defaultValue),
@@ -1205,7 +1283,28 @@ export class Player {
1205
1283
  qtiValueToSerializable(value) {
1206
1284
  if (!value || value.kind !== 'value')
1207
1285
  return null;
1208
- return value.value;
1286
+ if (value.cardinality !== 'record')
1287
+ return value.value;
1288
+ const serialized = {};
1289
+ for (const [fieldIdentifier, fieldValue] of Object.entries(value.value)) {
1290
+ serialized[fieldIdentifier] = {
1291
+ ...(fieldValue.baseType ? { baseType: fieldValue.baseType } : {}),
1292
+ cardinality: fieldValue.cardinality ?? 'single',
1293
+ value: this.qtiValueToSerializable(fieldValue),
1294
+ };
1295
+ }
1296
+ return serialized;
1297
+ }
1298
+ qtiValueToPublic(value) {
1299
+ if (!value || value.kind !== 'value')
1300
+ return null;
1301
+ if (value.cardinality !== 'record')
1302
+ return value.value;
1303
+ const record = {};
1304
+ for (const [fieldIdentifier, fieldValue] of Object.entries(value.value)) {
1305
+ record[fieldIdentifier] = this.qtiValueToPublic(fieldValue);
1306
+ }
1307
+ return record;
1209
1308
  }
1210
1309
  updateDuration() {
1211
1310
  const elapsedMs = Math.max(0, Date.now() - this.sessionStartedAt);
@@ -1227,17 +1326,29 @@ export class Player {
1227
1326
  const defaultEl = findFirstDescendant(declEl, this.mapper.toNative('defaultvalue'));
1228
1327
  if (!defaultEl)
1229
1328
  return qtiNull(baseType, cardinality);
1230
- const values = findDescendants(defaultEl, this.mapper.toNative('value')).map((v) => (v.textContent || '').trim());
1231
- if (cardinality === 'multiple' || cardinality === 'ordered') {
1232
- return qtiValue(baseType, cardinality, values.map((t) => {
1233
- const v = coerceBaseValue(baseType, t);
1234
- return v.kind === 'value' ? v.value : null;
1235
- }));
1236
- }
1237
- return coerceBaseValue(baseType, values[0] ?? '');
1329
+ return this.parseDeclarationValues(defaultEl, baseType, cardinality);
1238
1330
  }
1239
1331
  parseCorrectResponse(correctEl, baseType, cardinality) {
1240
- const values = findDescendants(correctEl, this.mapper.toNative('value')).map((v) => (v.textContent || '').trim());
1332
+ return this.parseDeclarationValues(correctEl, baseType, cardinality);
1333
+ }
1334
+ parseDeclarationValues(container, baseType, cardinality) {
1335
+ const valueElements = findDescendants(container, this.mapper.toNative('value'));
1336
+ if (cardinality === 'record') {
1337
+ const record = {};
1338
+ for (const valueElement of valueElements) {
1339
+ const fieldIdentifier = this.getAttrMapped(valueElement, 'fieldIdentifier');
1340
+ const fieldBaseType = this.getAttrMapped(valueElement, 'baseType');
1341
+ if (!fieldIdentifier || !fieldBaseType)
1342
+ continue;
1343
+ record[fieldIdentifier] = coerceBaseValue(fieldBaseType, valueElement.textContent || '');
1344
+ }
1345
+ return Object.keys(record).length > 0
1346
+ ? qtiValue(undefined, 'record', record)
1347
+ : qtiNull(undefined, 'record');
1348
+ }
1349
+ if (!baseType)
1350
+ return qtiNull(undefined, cardinality);
1351
+ const values = valueElements.map((value) => (value.textContent || '').trim());
1241
1352
  if (cardinality === 'multiple' || cardinality === 'ordered') {
1242
1353
  return qtiValue(baseType, cardinality, values.map((t) => {
1243
1354
  const v = coerceBaseValue(baseType, t);
@@ -1304,13 +1415,19 @@ export class Player {
1304
1415
  }
1305
1416
  return { defaultValue, lowerBound, upperBound, entries };
1306
1417
  }
1307
- coerceToDeclarationValue(baseType, cardinality, raw) {
1418
+ coerceToDeclarationValue(baseType, cardinality, raw, identifier) {
1308
1419
  if (raw === null || raw === undefined)
1309
1420
  return qtiNull(baseType, cardinality);
1310
1421
  // Allow callers to pass fully-formed QtiValue (e.g. session restore).
1311
1422
  if (typeof raw === 'object' && raw && 'kind' in raw) {
1312
1423
  return raw;
1313
1424
  }
1425
+ const extendedTextBase = identifier ? this.getExtendedTextBase(identifier) : undefined;
1426
+ if (cardinality === 'record') {
1427
+ return this.coerceRecordValue(raw, extendedTextBase ?? 10);
1428
+ }
1429
+ if (!baseType)
1430
+ return qtiNull(undefined, cardinality);
1314
1431
  // For file types, preserve QTIFileResponse objects directly
1315
1432
  if (baseType === 'file') {
1316
1433
  if (cardinality === 'multiple' || cardinality === 'ordered') {
@@ -1327,6 +1444,10 @@ export class Player {
1327
1444
  .map((v) => String(v ?? '').trim())
1328
1445
  .filter((s) => s.length > 0)
1329
1446
  .map((t) => {
1447
+ if (extendedTextBase && (baseType === 'integer' || baseType === 'float')) {
1448
+ const numeric = createExtendedTextNumericRecord(t, extendedTextBase);
1449
+ return baseType === 'integer' ? numeric.integerValue : numeric.floatValue;
1450
+ }
1330
1451
  const v = coerceBaseValue(baseType, t);
1331
1452
  return v.kind === 'value' ? v.value : null;
1332
1453
  })
@@ -1337,15 +1458,84 @@ export class Player {
1337
1458
  const t = String(raw ?? '').trim();
1338
1459
  if (t.length === 0)
1339
1460
  return qtiNull(baseType, cardinality);
1461
+ if (extendedTextBase && (baseType === 'integer' || baseType === 'float')) {
1462
+ const numeric = createExtendedTextNumericRecord(t, extendedTextBase);
1463
+ const value = baseType === 'integer' ? numeric.integerValue : numeric.floatValue;
1464
+ return value === null ? qtiNull(baseType, 'single') : qtiValue(baseType, 'single', value);
1465
+ }
1340
1466
  return coerceBaseValue(baseType, t);
1341
1467
  }
1468
+ getExtendedTextBase(responseIdentifier) {
1469
+ const interaction = this.itemDocument
1470
+ .findExtractionElements(['extendedTextInteraction'])
1471
+ .find((candidate) => candidate.responseIdentifier === responseIdentifier);
1472
+ if (!interaction)
1473
+ return undefined;
1474
+ const base = Number(interaction.element.getAttribute?.('base') ?? 10);
1475
+ return Number.isInteger(base) && base >= 2 && base <= 36 ? base : 10;
1476
+ }
1477
+ coerceRecordValue(raw, base) {
1478
+ let source = raw;
1479
+ if (typeof source === 'string') {
1480
+ const stringSource = source;
1481
+ if (stringSource.trim().length === 0)
1482
+ return qtiNull(undefined, 'record');
1483
+ if (stringSource.trimStart().startsWith('{')) {
1484
+ try {
1485
+ source = JSON.parse(stringSource);
1486
+ }
1487
+ catch {
1488
+ return qtiNull(undefined, 'record');
1489
+ }
1490
+ }
1491
+ else {
1492
+ source = createExtendedTextNumericRecord(stringSource, base);
1493
+ }
1494
+ }
1495
+ if (!source || typeof source !== 'object' || Array.isArray(source)) {
1496
+ return qtiNull(undefined, 'record');
1497
+ }
1498
+ const fields = {};
1499
+ for (const [fieldIdentifier, rawField] of Object.entries(source)) {
1500
+ if (rawField && typeof rawField === 'object' && 'kind' in rawField) {
1501
+ fields[fieldIdentifier] = rawField;
1502
+ continue;
1503
+ }
1504
+ let fieldBaseType = EXTENDED_TEXT_RECORD_FIELD_TYPES[fieldIdentifier];
1505
+ let fieldValue = rawField;
1506
+ if (rawField && typeof rawField === 'object' && !Array.isArray(rawField) && 'value' in rawField) {
1507
+ const serializedField = rawField;
1508
+ fieldBaseType = serializedField.baseType ?? fieldBaseType;
1509
+ fieldValue = serializedField.value;
1510
+ }
1511
+ if (!fieldBaseType) {
1512
+ fieldBaseType = typeof fieldValue === 'boolean'
1513
+ ? 'boolean'
1514
+ : typeof fieldValue === 'number'
1515
+ ? (Number.isInteger(fieldValue) ? 'integer' : 'float')
1516
+ : 'string';
1517
+ }
1518
+ if (fieldValue === null || fieldValue === undefined) {
1519
+ fields[fieldIdentifier] = qtiNull(fieldBaseType, 'single');
1520
+ }
1521
+ else if (fieldBaseType === 'file' && typeof fieldValue === 'object') {
1522
+ fields[fieldIdentifier] = qtiValue('file', 'single', fieldValue);
1523
+ }
1524
+ else {
1525
+ fields[fieldIdentifier] = coerceBaseValue(fieldBaseType, String(fieldValue));
1526
+ }
1527
+ }
1528
+ return Object.keys(fields).length > 0
1529
+ ? qtiValue(undefined, 'record', fields)
1530
+ : qtiNull(undefined, 'record');
1531
+ }
1342
1532
  collectOutcomes() {
1343
1533
  const out = {};
1344
1534
  for (const d of Object.values(this.decls)) {
1345
1535
  if (d.__kind !== 'outcome')
1346
1536
  continue;
1347
1537
  if (d.value.kind === 'value')
1348
- out[d.identifier] = d.value.value;
1538
+ out[d.identifier] = this.qtiValueToPublic(d.value);
1349
1539
  else if (d.value.kind === 'null')
1350
1540
  out[d.identifier] = null;
1351
1541
  }
@@ -1413,10 +1603,27 @@ function mergePnp(base, partial) {
1413
1603
  };
1414
1604
  }
1415
1605
  function createSessionGuid() {
1416
- if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
1417
- return crypto.randomUUID();
1418
- }
1419
- return `item-session-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
1606
+ // `Crypto` is typed as always providing `randomUUID`, but it is restricted to secure
1607
+ // contexts and so is genuinely absent when the player is served over plain HTTP.
1608
+ // Reading through a `Partial<Crypto>` keeps TypeScript from narrowing the fallback
1609
+ // branch to `never` on the strength of a type that overstates what is available.
1610
+ const webCrypto = typeof crypto !== 'undefined' ? crypto : undefined;
1611
+ if (typeof webCrypto?.randomUUID === 'function') {
1612
+ return webCrypto.randomUUID();
1613
+ }
1614
+ // `getRandomValues` carries no secure-context restriction and offers the same entropy
1615
+ // guarantee, so it covers the plain-HTTP case. The previous fallback here used
1616
+ // `Math.random()`, which is not a CSPRNG and left session GUIDs predictable in
1617
+ // exactly the environments that reached it.
1618
+ if (typeof webCrypto?.getRandomValues === 'function') {
1619
+ const bytes = new Uint8Array(16);
1620
+ webCrypto.getRandomValues(bytes);
1621
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
1622
+ return `item-session-${hex}`;
1623
+ }
1624
+ throw new Error('No Web Crypto API available: cannot generate a session GUID. @pie-qti/item-player ' +
1625
+ 'requires crypto.randomUUID or crypto.getRandomValues (present in all supported ' +
1626
+ 'browsers and in Node >= 20).');
1420
1627
  }
1421
1628
  function looksLikeCatalogUrl(value) {
1422
1629
  const trimmed = value.trim();