@pie-qti/ims-cp-core 1.0.0-beta.4 → 1.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,13 +46,18 @@ console.log(localized.availableLocales); // Set of all locales
46
46
  ### Passage Reusability
47
47
 
48
48
  ```typescript
49
- import { generateStablePassageId, PassageRegistry } from '@pie-qti/ims-cp-core/passage-reusability';
49
+ import { generateStablePassageId, parseObjectReference, PassageRegistry } from '@pie-qti/ims-cp-core/passage-reusability';
50
50
 
51
51
  // Generate stable ID from content (async)
52
52
  const id = await generateStablePassageId({
53
53
  content: '<p>The Industrial Revolution...</p>'
54
54
  });
55
55
 
56
+ // Parse an <object> element into a passage reference (sync).
57
+ // A text/* type is a passage; an untyped object only when its data file
58
+ // looks like a markup document (.html, .xhtml, .xml).
59
+ const reference = parseObjectReference(objectElement);
60
+
56
61
  // Track passage references across a package
57
62
  const registry = new PassageRegistry();
58
63
  registry.registerReference('item-1', {
@@ -66,8 +71,12 @@ registry.registerReference('item-1', {
66
71
 
67
72
  ### Breaking Changes from to-pie
68
73
 
69
- - `generateStablePassageId()` is now **async** (returns `Promise<string>`)
70
- - `PassageRegistry.detectAndMergeDuplicates()` is now **async**
74
+ - `generateStablePassageId()` is **async** (returns `Promise<string>`); inject a sync hash
75
+ with `createStablePassageIdGenerator(hashContent)` when you need synchronous IDs
76
+ - `PassageRegistry.detectAndMergeDuplicates()` is **async**
77
+ - `parseObjectReference()` is **sync** and strict about untyped objects: an `<object>`
78
+ without a `type` is a passage only when its `data` file looks like markup
79
+ (`.html`, `.xhtml`, `.xml`); figures and other assets are not passages
71
80
 
72
81
  ## License
73
82
 
@@ -8,6 +8,39 @@
8
8
  *
9
9
  * This module provides stable ID generation and reusability detection.
10
10
  */
11
+ /**
12
+ * Options for stable passage ID generation.
13
+ */
14
+ export interface StablePassageIdOptions {
15
+ /** QTI identifier from assessmentStimulus or assessmentPassage - USE DIRECTLY */
16
+ qtiIdentifier?: string;
17
+ /** File path from object data attribute */
18
+ filePath?: string;
19
+ /** Content hash for inline stimulus */
20
+ content?: string;
21
+ /** Prefix for generated IDs (only used for hashed IDs) */
22
+ prefix?: string;
23
+ }
24
+ /**
25
+ * Strategy that hashes passage content into a hex digest. Inject one to
26
+ * generate stable IDs synchronously (see {@link createStablePassageIdGenerator}).
27
+ */
28
+ export type PassageContentHash = (content: string) => string;
29
+ /**
30
+ * Create a synchronous stable-ID generator from a content-hash strategy.
31
+ *
32
+ * Strategy (in priority order):
33
+ * 1. Use QTI identifier directly - QTI identifiers are designed to be globally unique
34
+ * across vendors and packages (e.g., "urn:example.com:passage:12345")
35
+ * 2. Use file path for object references - stable within a package
36
+ * 3. Use content hash for inline stimulus - ensures same content = same ID
37
+ *
38
+ * @param hashContent Strategy hashing passage content into a hex digest
39
+ * (e.g. `createHash('sha256')` in Node.js).
40
+ * @returns A synchronous generator with the same semantics as
41
+ * {@link generateStablePassageId}.
42
+ */
43
+ export declare function createStablePassageIdGenerator(hashContent: PassageContentHash): (options: StablePassageIdOptions) => string;
11
44
  /**
12
45
  * Generate stable ID for passage content
13
46
  *
@@ -20,16 +53,7 @@
20
53
  * @param options Options for ID generation
21
54
  * @returns Stable passage ID (async for content hashing)
22
55
  */
23
- export declare function generateStablePassageId(options: {
24
- /** QTI identifier from assessmentStimulus or assessmentPassage - USE DIRECTLY */
25
- qtiIdentifier?: string;
26
- /** File path from object data attribute */
27
- filePath?: string;
28
- /** Content hash for inline stimulus */
29
- content?: string;
30
- /** Prefix for generated IDs (only used for hashed IDs) */
31
- prefix?: string;
32
- }): Promise<string>;
56
+ export declare function generateStablePassageId(options: StablePassageIdOptions): Promise<string>;
33
57
  /**
34
58
  * Passage reference information
35
59
  */
@@ -96,4 +120,4 @@ export declare class PassageRegistry {
96
120
  * @param objectElement Object element from QTI
97
121
  * @returns Passage reference or null
98
122
  */
99
- export declare function parseObjectReference(objectElement: any): Promise<PassageReference | null>;
123
+ export declare function parseObjectReference(objectElement: any): PassageReference | null;
@@ -9,6 +9,59 @@
9
9
  * This module provides stable ID generation and reusability detection.
10
10
  */
11
11
  import { sha256 } from './utils/hash.js';
12
+ /**
13
+ * Shared pieces of the ID strategy. The identifier and file-path strategies
14
+ * need no hashing; only the content strategy does, which is why callers can
15
+ * pick a sync or async hashing strategy without changing the semantics.
16
+ */
17
+ function passageIdPrefix(options) {
18
+ return options.prefix || 'passage';
19
+ }
20
+ function filePathPassageId(filePath, prefix) {
21
+ // Normalize path (remove leading ./ and ../) and use as-is with prefix
22
+ const normalizedPath = filePath
23
+ .replace(/^\.\//, '')
24
+ .replace(/\.\.\//g, '')
25
+ .replace(/\//g, '-')
26
+ .replace(/\.(xml|html|txt)$/, '');
27
+ return `${prefix}-${normalizedPath}`;
28
+ }
29
+ function contentPassageId(contentHash, prefix) {
30
+ return `${prefix}-content-${contentHash.substring(0, 12)}`;
31
+ }
32
+ const MISSING_SOURCE_ERROR = 'Must provide at least one of: qtiIdentifier, filePath, or content';
33
+ /**
34
+ * Create a synchronous stable-ID generator from a content-hash strategy.
35
+ *
36
+ * Strategy (in priority order):
37
+ * 1. Use QTI identifier directly - QTI identifiers are designed to be globally unique
38
+ * across vendors and packages (e.g., "urn:example.com:passage:12345")
39
+ * 2. Use file path for object references - stable within a package
40
+ * 3. Use content hash for inline stimulus - ensures same content = same ID
41
+ *
42
+ * @param hashContent Strategy hashing passage content into a hex digest
43
+ * (e.g. `createHash('sha256')` in Node.js).
44
+ * @returns A synchronous generator with the same semantics as
45
+ * {@link generateStablePassageId}.
46
+ */
47
+ export function createStablePassageIdGenerator(hashContent) {
48
+ return (options) => {
49
+ const prefix = passageIdPrefix(options);
50
+ // Priority 1: Use QTI identifier DIRECTLY (no prefix)
51
+ if (options.qtiIdentifier) {
52
+ return options.qtiIdentifier;
53
+ }
54
+ // Priority 2: Use file path for object references
55
+ if (options.filePath) {
56
+ return filePathPassageId(options.filePath, prefix);
57
+ }
58
+ // Priority 3: Use content hash for inline stimulus (stable for same content)
59
+ if (options.content) {
60
+ return contentPassageId(hashContent(options.content.trim()), prefix);
61
+ }
62
+ throw new Error(MISSING_SOURCE_ERROR);
63
+ };
64
+ }
12
65
  /**
13
66
  * Generate stable ID for passage content
14
67
  *
@@ -22,29 +75,21 @@ import { sha256 } from './utils/hash.js';
22
75
  * @returns Stable passage ID (async for content hashing)
23
76
  */
24
77
  export async function generateStablePassageId(options) {
25
- const prefix = options.prefix || 'passage';
78
+ const prefix = passageIdPrefix(options);
26
79
  // Priority 1: Use QTI identifier DIRECTLY (no prefix)
27
- // QTI identifiers are designed to be globally unique across vendors
28
- // Examples: "urn:example.com:passage:12345", "stim-industrial-revolution"
29
80
  if (options.qtiIdentifier) {
30
81
  return options.qtiIdentifier;
31
82
  }
32
83
  // Priority 2: Use file path for object references
33
- // Normalize path (remove leading ./ and ../) and use as-is with prefix
34
84
  if (options.filePath) {
35
- const normalizedPath = options.filePath
36
- .replace(/^\.\//, '')
37
- .replace(/\.\.\//g, '')
38
- .replace(/\//g, '-')
39
- .replace(/\.(xml|html|txt)$/, '');
40
- return `${prefix}-${normalizedPath}`;
85
+ return filePathPassageId(options.filePath, prefix);
41
86
  }
42
87
  // Priority 3: Use content hash for inline stimulus (stable for same content)
43
88
  if (options.content) {
44
89
  const contentHash = await sha256(options.content.trim());
45
- return `${prefix}-content-${contentHash.substring(0, 12)}`;
90
+ return contentPassageId(contentHash, prefix);
46
91
  }
47
- throw new Error('Must provide at least one of: qtiIdentifier, filePath, or content');
92
+ throw new Error(MISSING_SOURCE_ERROR);
48
93
  }
49
94
  /**
50
95
  * Track passage references across a package
@@ -147,19 +192,19 @@ export class PassageRegistry {
147
192
  * @param objectElement Object element from QTI
148
193
  * @returns Passage reference or null
149
194
  */
150
- export async function parseObjectReference(objectElement) {
195
+ export function parseObjectReference(objectElement) {
151
196
  const dataAttr = objectElement.getAttribute?.('data');
152
197
  const typeAttr = objectElement.getAttribute?.('type');
153
- // Check if it's a passage reference (text/html, text/plain, or no type)
154
- const isPassageType = !typeAttr ||
155
- typeAttr === 'text/html' ||
156
- typeAttr === 'text/plain' ||
157
- typeAttr.startsWith('text/');
198
+ // A text type names a passage; an untyped object is a passage only when the
199
+ // data file looks like a markup document - untyped objects embed figures too.
200
+ const isPassageType = typeAttr
201
+ ? typeAttr.startsWith('text/')
202
+ : /\.(?:html?|xhtml|xml)(?:[?#]|$)/i.test(dataAttr ?? '');
158
203
  if (!dataAttr || !isPassageType) {
159
204
  return null;
160
205
  }
161
206
  // Generate stable ID from file path
162
- const id = await generateStablePassageId({ filePath: dataAttr });
207
+ const id = filePathPassageId(dataAttr, passageIdPrefix({}));
163
208
  return {
164
209
  id,
165
210
  source: 'file',
@@ -1 +1 @@
1
- {"version":3,"file":"passage-reusability.js","sourceRoot":"","sources":["../src/passage-reusability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEzC;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,OAS7C;IACC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,SAAS,CAAC;IAE3C,sDAAsD;IACtD,oEAAoE;IACpE,0EAA0E;IAC1E,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC;QAC1B,OAAO,OAAO,CAAC,aAAa,CAAC;IAC/B,CAAC;IAED,kDAAkD;IAClD,uEAAuE;IACvE,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;QACrB,MAAM,cAAc,GAAG,OAAO,CAAC,QAAQ;aACpC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;aACpB,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC;aACtB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;aACnB,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC;QACpC,OAAO,GAAG,MAAM,IAAI,cAAc,EAAE,CAAC;IACvC,CAA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,CAAC","sourcesContent":["/**\n * Passage reusability detection and stable ID management\n *\n * QTI provides several mechanisms for reusable content:\n * 1. Manifest <dependency> elements - explicit reusability declaration\n * 2. Object <object data=\"...\"> references - shared file paths\n * 3. assessmentStimulus/assessmentPassage identifiers - stable IDs\n *\n * This module provides stable ID generation and reusability detection.\n */\n\nimport { sha256 } from './utils/hash.js';\n\n/**\n * Generate stable ID for passage content\n *\n * Strategy (in priority order):\n * 1. Use QTI identifier directly - QTI identifiers are designed to be globally unique\n * across vendors and packages (e.g., \"urn:example.com:passage:12345\")\n * 2. Use file path for object references - stable within a package\n * 3. Use content hash for inline stimulus - ensures same content = same ID\n *\n * @param options Options for ID generation\n * @returns Stable passage ID (async for content hashing)\n */\nexport async function generateStablePassageId(options: {\n /** QTI identifier from assessmentStimulus or assessmentPassage - USE DIRECTLY */\n qtiIdentifier?: string;\n /** File path from object data attribute */\n filePath?: string;\n /** Content hash for inline stimulus */\n content?: string;\n /** Prefix for generated IDs (only used for hashed IDs) */\n prefix?: string;\n}): Promise<string> {\n const prefix = options.prefix || 'passage';\n\n // Priority 1: Use QTI identifier DIRECTLY (no prefix)\n // QTI identifiers are designed to be globally unique across vendors\n // Examples: \"urn:example.com:passage:12345\", \"stim-industrial-revolution\"\n if (options.qtiIdentifier) {\n return options.qtiIdentifier;\n }\n\n // Priority 2: Use file path for object references\n // Normalize path (remove leading ./ and ../) and use as-is with prefix\n if (options.filePath) {\n const normalizedPath = options.filePath\n .replace(/^\\.\\//, '')\n .replace(/\\.\\.\\//g, '')\n .replace(/\\//g, '-')\n .replace(/\\.(xml|html|txt)$/, '');\n return `${prefix}-${normalizedPath}`;\n }\n\n // Priority 3: Use content hash for inline stimulus (stable for same content)\n if (options.content) {\n const contentHash = await sha256(options.content.trim());\n return `${prefix}-content-${contentHash.substring(0, 12)}`;\n }\n\n throw new Error('Must provide at least one of: qtiIdentifier, filePath, or content');\n}\n\n/**\n * Passage reference information\n */\nexport interface PassageReference {\n /** Stable passage ID */\n id: string;\n /** Source of the passage */\n source: 'inline' | 'file' | 'manifest' | 'qti-element';\n /** Original QTI identifier if available */\n qtiIdentifier?: string;\n /** File path if from object reference */\n filePath?: string;\n /** Whether this passage is referenced by multiple items */\n isReusable: boolean;\n}\n\n/**\n * Track passage references across a package\n * Used during batch transformation to detect reusable passages\n */\nexport class PassageRegistry {\n private passages = new Map<string, {\n reference: PassageReference;\n referencedBy: Set<string>;\n content?: string;\n }>();\n\n /**\n * Register a passage reference\n * @param itemId ID of the item referencing this passage\n * @param reference Passage reference information\n */\n registerReference(itemId: string, reference: PassageReference): void {\n const existing = this.passages.get(reference.id);\n\n if (existing) {\n // Passage already registered, add this item as a reference\n existing.referencedBy.add(itemId);\n existing.reference.isReusable = existing.referencedBy.size > 1;\n } else {\n // First reference to this passage\n this.passages.set(reference.id, {\n reference: { ...reference, isReusable: false },\n referencedBy: new Set([itemId]),\n });\n }\n }\n\n /**\n * Store passage content for deduplication\n * @param passageId Passage ID\n * @param content Passage content\n */\n storeContent(passageId: string, content: string): void {\n const entry = this.passages.get(passageId);\n if (entry) {\n entry.content = content;\n }\n }\n\n /**\n * Get passage reference by ID\n * @param passageId Passage ID\n * @returns Passage reference with updated reusability flag\n */\n getReference(passageId: string): PassageReference | undefined {\n return this.passages.get(passageId)?.reference;\n }\n\n /**\n * Get all items that reference a passage\n * @param passageId Passage ID\n * @returns Set of item IDs\n */\n getReferencingItems(passageId: string): Set<string> {\n return this.passages.get(passageId)?.referencedBy || new Set();\n }\n\n /**\n * Get all registered passages\n * @returns Array of passage references\n */\n getAllPassages(): PassageReference[] {\n return Array.from(this.passages.values()).map(entry => entry.reference);\n }\n\n /**\n * Get reusable passages (referenced by multiple items)\n * @returns Array of reusable passage references\n */\n getReusablePassages(): PassageReference[] {\n return this.getAllPassages().filter(ref => ref.isReusable);\n }\n\n /**\n * Detect duplicate content and merge passages\n * This handles cases where same content appears with different IDs\n */\n async detectAndMergeDuplicates(): Promise<Map<string, string>> {\n const contentMap = new Map<string, string>(); // content hash -> primary ID\n const mergeMap = new Map<string, string>(); // old ID -> new ID\n\n for (const [id, entry] of this.passages.entries()) {\n if (!entry.content) continue;\n\n const contentHash = await sha256(entry.content.trim());\n\n const existingId = contentMap.get(contentHash);\n if (existingId && existingId !== id) {\n // Duplicate content found - merge into existing\n mergeMap.set(id, existingId);\n\n const existingEntry = this.passages.get(existingId)!;\n for (const itemId of entry.referencedBy) {\n existingEntry.referencedBy.add(itemId);\n }\n existingEntry.reference.isReusable = existingEntry.referencedBy.size > 1;\n\n this.passages.delete(id);\n } else {\n contentMap.set(contentHash, id);\n }\n }\n\n return mergeMap;\n }\n}\n\n/**\n * Parse object tag to extract passage reference\n * @param objectElement Object element from QTI\n * @returns Passage reference or null\n */\nexport async function parseObjectReference(objectElement: any): Promise<PassageReference | null> {\n const dataAttr = objectElement.getAttribute?.('data');\n const typeAttr = objectElement.getAttribute?.('type');\n\n // Check if it's a passage reference (text/html, text/plain, or no type)\n const isPassageType = !typeAttr ||\n typeAttr === 'text/html' ||\n typeAttr === 'text/plain' ||\n typeAttr.startsWith('text/');\n\n if (!dataAttr || !isPassageType) {\n return null;\n }\n\n // Generate stable ID from file path\n const id = await generateStablePassageId({ filePath: dataAttr });\n\n return {\n id,\n source: 'file',\n filePath: dataAttr,\n isReusable: false, // Will be updated by registry\n };\n}\n"]}
1
+ {"version":3,"file":"passage-reusability.js","sourceRoot":"","sources":["../src/passage-reusability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAsBzC;;;;GAIG;AACH,SAAS,eAAe,CAAC,OAA+B;IACtD,OAAO,OAAO,CAAC,MAAM,IAAI,SAAS,CAAC;AACrC,CAAC;AAED,SAAS,iBAAiB,CAAC,QAAgB,EAAE,MAAc;IACzD,uEAAuE;IACvE,MAAM,cAAc,GAAG,QAAQ;SAC5B,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;SACpB,OAAO,CA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E,eAAe,CAAC,EAAE,CAAC,CAAC,CAAC;IAE5D,OAAO;QACL,EAAE;QACF,MAAM,EAAE,MAAM;QACd,QAAQ,EAAE,QAAQ;QAClB,UAAU,EAAE,KAAK,EAAE,8BAA8B;KAClD,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Passage reusability detection and stable ID management\n *\n * QTI provides several mechanisms for reusable content:\n * 1. Manifest <dependency> elements - explicit reusability declaration\n * 2. Object <object data=\"...\"> references - shared file paths\n * 3. assessmentStimulus/assessmentPassage identifiers - stable IDs\n *\n * This module provides stable ID generation and reusability detection.\n */\n\nimport { sha256 } from './utils/hash.js';\n\n/**\n * Options for stable passage ID generation.\n */\nexport interface StablePassageIdOptions {\n /** QTI identifier from assessmentStimulus or assessmentPassage - USE DIRECTLY */\n qtiIdentifier?: string;\n /** File path from object data attribute */\n filePath?: string;\n /** Content hash for inline stimulus */\n content?: string;\n /** Prefix for generated IDs (only used for hashed IDs) */\n prefix?: string;\n}\n\n/**\n * Strategy that hashes passage content into a hex digest. Inject one to\n * generate stable IDs synchronously (see {@link createStablePassageIdGenerator}).\n */\nexport type PassageContentHash = (content: string) => string;\n\n/**\n * Shared pieces of the ID strategy. The identifier and file-path strategies\n * need no hashing; only the content strategy does, which is why callers can\n * pick a sync or async hashing strategy without changing the semantics.\n */\nfunction passageIdPrefix(options: StablePassageIdOptions): string {\n return options.prefix || 'passage';\n}\n\nfunction filePathPassageId(filePath: string, prefix: string): string {\n // Normalize path (remove leading ./ and ../) and use as-is with prefix\n const normalizedPath = filePath\n .replace(/^\\.\\//, '')\n .replace(/\\.\\.\\//g, '')\n .replace(/\\//g, '-')\n .replace(/\\.(xml|html|txt)$/, '');\n return `${prefix}-${normalizedPath}`;\n}\n\nfunction contentPassageId(contentHash: string, prefix: string): string {\n return `${prefix}-content-${contentHash.substring(0, 12)}`;\n}\n\nconst MISSING_SOURCE_ERROR =\n 'Must provide at least one of: qtiIdentifier, filePath, or content';\n\n/**\n * Create a synchronous stable-ID generator from a content-hash strategy.\n *\n * Strategy (in priority order):\n * 1. Use QTI identifier directly - QTI identifiers are designed to be globally unique\n * across vendors and packages (e.g., \"urn:example.com:passage:12345\")\n * 2. Use file path for object references - stable within a package\n * 3. Use content hash for inline stimulus - ensures same content = same ID\n *\n * @param hashContent Strategy hashing passage content into a hex digest\n * (e.g. `createHash('sha256')` in Node.js).\n * @returns A synchronous generator with the same semantics as\n * {@link generateStablePassageId}.\n */\nexport function createStablePassageIdGenerator(\n hashContent: PassageContentHash\n): (options: StablePassageIdOptions) => string {\n return (options: StablePassageIdOptions): string => {\n const prefix = passageIdPrefix(options);\n\n // Priority 1: Use QTI identifier DIRECTLY (no prefix)\n if (options.qtiIdentifier) {\n return options.qtiIdentifier;\n }\n\n // Priority 2: Use file path for object references\n if (options.filePath) {\n return filePathPassageId(options.filePath, prefix);\n }\n\n // Priority 3: Use content hash for inline stimulus (stable for same content)\n if (options.content) {\n return contentPassageId(hashContent(options.content.trim()), prefix);\n }\n\n throw new Error(MISSING_SOURCE_ERROR);\n };\n}\n\n/**\n * Generate stable ID for passage content\n *\n * Strategy (in priority order):\n * 1. Use QTI identifier directly - QTI identifiers are designed to be globally unique\n * across vendors and packages (e.g., \"urn:example.com:passage:12345\")\n * 2. Use file path for object references - stable within a package\n * 3. Use content hash for inline stimulus - ensures same content = same ID\n *\n * @param options Options for ID generation\n * @returns Stable passage ID (async for content hashing)\n */\nexport async function generateStablePassageId(\n options: StablePassageIdOptions\n): Promise<string> {\n const prefix = passageIdPrefix(options);\n\n // Priority 1: Use QTI identifier DIRECTLY (no prefix)\n if (options.qtiIdentifier) {\n return options.qtiIdentifier;\n }\n\n // Priority 2: Use file path for object references\n if (options.filePath) {\n return filePathPassageId(options.filePath, prefix);\n }\n\n // Priority 3: Use content hash for inline stimulus (stable for same content)\n if (options.content) {\n const contentHash = await sha256(options.content.trim());\n return contentPassageId(contentHash, prefix);\n }\n\n throw new Error(MISSING_SOURCE_ERROR);\n}\n\n/**\n * Passage reference information\n */\nexport interface PassageReference {\n /** Stable passage ID */\n id: string;\n /** Source of the passage */\n source: 'inline' | 'file' | 'manifest' | 'qti-element';\n /** Original QTI identifier if available */\n qtiIdentifier?: string;\n /** File path if from object reference */\n filePath?: string;\n /** Whether this passage is referenced by multiple items */\n isReusable: boolean;\n}\n\n/**\n * Track passage references across a package\n * Used during batch transformation to detect reusable passages\n */\nexport class PassageRegistry {\n private passages = new Map<string, {\n reference: PassageReference;\n referencedBy: Set<string>;\n content?: string;\n }>();\n\n /**\n * Register a passage reference\n * @param itemId ID of the item referencing this passage\n * @param reference Passage reference information\n */\n registerReference(itemId: string, reference: PassageReference): void {\n const existing = this.passages.get(reference.id);\n\n if (existing) {\n // Passage already registered, add this item as a reference\n existing.referencedBy.add(itemId);\n existing.reference.isReusable = existing.referencedBy.size > 1;\n } else {\n // First reference to this passage\n this.passages.set(reference.id, {\n reference: { ...reference, isReusable: false },\n referencedBy: new Set([itemId]),\n });\n }\n }\n\n /**\n * Store passage content for deduplication\n * @param passageId Passage ID\n * @param content Passage content\n */\n storeContent(passageId: string, content: string): void {\n const entry = this.passages.get(passageId);\n if (entry) {\n entry.content = content;\n }\n }\n\n /**\n * Get passage reference by ID\n * @param passageId Passage ID\n * @returns Passage reference with updated reusability flag\n */\n getReference(passageId: string): PassageReference | undefined {\n return this.passages.get(passageId)?.reference;\n }\n\n /**\n * Get all items that reference a passage\n * @param passageId Passage ID\n * @returns Set of item IDs\n */\n getReferencingItems(passageId: string): Set<string> {\n return this.passages.get(passageId)?.referencedBy || new Set();\n }\n\n /**\n * Get all registered passages\n * @returns Array of passage references\n */\n getAllPassages(): PassageReference[] {\n return Array.from(this.passages.values()).map(entry => entry.reference);\n }\n\n /**\n * Get reusable passages (referenced by multiple items)\n * @returns Array of reusable passage references\n */\n getReusablePassages(): PassageReference[] {\n return this.getAllPassages().filter(ref => ref.isReusable);\n }\n\n /**\n * Detect duplicate content and merge passages\n * This handles cases where same content appears with different IDs\n */\n async detectAndMergeDuplicates(): Promise<Map<string, string>> {\n const contentMap = new Map<string, string>(); // content hash -> primary ID\n const mergeMap = new Map<string, string>(); // old ID -> new ID\n\n for (const [id, entry] of this.passages.entries()) {\n if (!entry.content) continue;\n\n const contentHash = await sha256(entry.content.trim());\n\n const existingId = contentMap.get(contentHash);\n if (existingId && existingId !== id) {\n // Duplicate content found - merge into existing\n mergeMap.set(id, existingId);\n\n const existingEntry = this.passages.get(existingId)!;\n for (const itemId of entry.referencedBy) {\n existingEntry.referencedBy.add(itemId);\n }\n existingEntry.reference.isReusable = existingEntry.referencedBy.size > 1;\n\n this.passages.delete(id);\n } else {\n contentMap.set(contentHash, id);\n }\n }\n\n return mergeMap;\n }\n}\n\n/**\n * Parse object tag to extract passage reference\n * @param objectElement Object element from QTI\n * @returns Passage reference or null\n */\nexport function parseObjectReference(objectElement: any): PassageReference | null {\n const dataAttr = objectElement.getAttribute?.('data');\n const typeAttr = objectElement.getAttribute?.('type');\n\n // A text type names a passage; an untyped object is a passage only when the\n // data file looks like a markup document - untyped objects embed figures too.\n const isPassageType = typeAttr\n ? typeAttr.startsWith('text/')\n : /\\.(?:html?|xhtml|xml)(?:[?#]|$)/i.test(dataAttr ?? '');\n\n if (!dataAttr || !isPassageType) {\n return null;\n }\n\n // Generate stable ID from file path\n const id = filePathPassageId(dataAttr, passageIdPrefix({}));\n\n return {\n id,\n source: 'file',\n filePath: dataAttr,\n isReusable: false, // Will be updated by registry\n };\n}\n"]}
@@ -101,8 +101,7 @@ export function extractExtensionsFromQtiXml(xmlContent) {
101
101
  if (pieExtensionMatch && pieExtensionMatch[1]) {
102
102
  try {
103
103
  const sourceModel = JSON.parse(pieExtensionMatch[1].trim());
104
- // `searchMetaData` is the bag's name in PIE items written before `extensions`
105
- const extensions = sourceModel.extensions ?? sourceModel.searchMetaData;
104
+ const extensions = sourceModel.extensions;
106
105
  if (extensions) {
107
106
  return extensions;
108
107
  }
@@ -1 +1 @@
1
- {"version":3,"file":"qti-xml.js","sourceRoot":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AC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,iCAAiC,CAAC,UAAkB;IACnE,IAAI,CAAC,UAAU;QAAE,OAAO,EAAE,CAAC;IAE3B,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;IAE3C,+BAA+B;IAC/B,MAAM,iBAAiB,GAAG;QACzB,mBAAmB;QACnB,kBAAkB;QAClB,sBAAsB;QACtB,kBAAkB;QAClB,qBAAqB;QACrB,yBAAyB;QACzB,sBAAsB;QACtB,yBAAyB;QACzB,oBAAoB;QACpB,oBAAoB;QACpB,wBAAwB;QACxB,yBAAyB;QACzB,6BAA6B;QAC7B,4BAA4B;QAC5B,2BAA2B;QAC3B,mBAAmB;QACnB,oBAAoB;QACpB,mBAAmB;QACnB,mBAAmB;QACnB,uBAAuB;KACvB,CAAC;IAEF,KAAK,MAAM,eAAe,IAAI,iBAAiB,EAAE,CAAC;QACjD,MAAM,OAAO,GAAG,IAAI,MAAM,CAAC,IAAI,eAAe,QAAQ,EAAE,GAAG,CAAC,CAAC;QAC7D,IAAI,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAC9B,gBAAgB,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QACvC,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;AACrC,CAAC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,sBAAsB,CAAC,UAAkB;IACxD,OAAO;QACN,UAAU,EAAE,2BAA2B,CAAC,UAAU,CAAC;QACnD,KAAK,EAAE,sBAAsB,CAAC,UAAU,CAAC;QACzC,UAAU,EAAE,2BAA2B,CAAC,UAAU,CAAC;QACnD,gBAAgB,EAAE,iCAAiC,CAAC,UAAU,CAAC;KAC/D,CAAC;AACH,CAAC","sourcesContent":["/**\n * QTI XML utilities for extracting metadata and information from QTI XML content\n *\n * These utilities use regex-based parsing to remain environment-agnostic\n * (works in both browser and Node.js without heavy dependencies).\n */\n\n/**\n * Comprehensive QTI item metadata\n */\nexport interface QtiItemMetadata {\n\t/** Item identifier */\n\tidentifier?: string;\n\t/** Item title */\n\ttitle?: string;\n\t/** Item description */\n\tdescription?: string;\n\t/** Language code (e.g., \"en-US\") */\n\tlanguage?: string;\n\t/** Host-owned key/value pairs of the PIE item, or the QTI metadata fields */\n\textensions?: Record<string, any>;\n\t/** Detected interaction types */\n\tinteractionTypes?: string[];\n}\n\n/**\n * Extract title from QTI item/test XML content\n *\n * Handles multiple QTI title formats:\n * - Attribute-style: `<assessmentItem title=\"...\">`\n * - Attribute-style: `<assessmentTest title=\"...\">`\n * - Element-style: `<title>...</title>` within assessment elements\n * - Fallback: Any `<title>` element in the document\n *\n * @param xmlContent QTI XML content as string\n * @returns Extracted title or undefined if not found\n *\n * @example\n * ```ts\n * const xml = '<assessmentItem identifier=\"item1\" title=\"Question 1\">...</assessmentItem>';\n * const title = extractTitleFromQtiXml(xml); // \"Question 1\"\n * ```\n */\nexport function extractTitleFromQtiXml(xmlContent: string): string | undefined {\n\tif (!xmlContent) return undefined;\n\n\t// Try attribute-style title first: <assessmentItem title=\"...\">\n\tconst attributeMatch = xmlContent.match(/<assessmentItem[^>]*\\s+title=[\"']([^\"']+)[\"']/i);\n\tif (attributeMatch && attributeMatch[1]) {\n\t\treturn attributeMatch[1].trim();\n\t}\n\n\t// Try test attribute-style: <assessmentTest title=\"...\">\n\tconst testAttributeMatch = xmlContent.match(/<assessmentTest[^>]*\\s+title=[\"']([^\"']+)[\"']/i);\n\tif (testAttributeMatch && testAttributeMatch[1]) {\n\t\treturn testAttributeMatch[1].trim();\n\t}\n\n\t// Try element-style title: <title>...</title>\n\t// Look for title element that's a direct child of assessmentItem or assessmentTest\n\tconst elementMatch = xmlContent.match(\n\t\t/<(?:assessmentItem|assessmentTest)[^>]*>[\\s\\S]*?<title[^>]*>([^<]+)<\\/title>/i\n\t);\n\tif (elementMatch && elementMatch[1]) {\n\t\treturn elementMatch[1].trim();\n\t}\n\n\t// Fallback: look for any <title> element (less specific but might catch some cases)\n\tconst fallbackMatch = xmlContent.match(/<title[^>]*>([^<]+)<\\/title>/i);\n\tif (fallbackMatch && fallbackMatch[1]) {\n\t\treturn fallbackMatch[1].trim();\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Extract identifier from QTI item/test XML content\n *\n * @param xmlContent QTI XML content as string\n * @returns Extracted identifier or undefined if not found\n */\nexport function extractIdentifierFromQtiXml(xmlContent: string): string | undefined {\n\tif (!xmlContent) return undefined;\n\n\t// Try assessmentItem identifier\n\tconst itemMatch = xmlContent.match(/<assessmentItem[^>]*\\s+identifier=[\"']([^\"']+)[\"']/i);\n\tif (itemMatch && itemMatch[1]) {\n\t\treturn itemMatch[1].trim();\n\t}\n\n\t// Try assessmentTest identifier\n\tconst testMatch = xmlContent.match(/<assessmentTest[^>]*\\s+identifier=[\"']([^\"']+)[\"']/i);\n\tif (testMatch && testMatch[1]) {\n\t\treturn testMatch[1].trim();\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Extract a PIE item's extensions from QTI item XML content\n *\n * Priority 1: Check for PIE extension with embedded extensions (perfect reconstruction)\n * Priority 2: Parse QTI metadata section with qti-metadata-field elements\n *\n * @param xmlContent QTI XML content as string\n * @returns Extracted search metadata object\n *\n * @example\n * ```ts\n * const xml = `\n * <assessmentItem>\n * <qti-metadata>\n * <qti-metadata-field name=\"domain\" value=\"math\" />\n * <qti-metadata-field name=\"gradeLevel\" value=\"5,6,7\" data-type=\"array\" />\n * </qti-metadata>\n * </assessmentItem>\n * `;\n * const metadata = extractExtensionsFromQtiXml(xml);\n * // { domain: \"math\", gradeLevel: [\"5\", \"6\", \"7\"] }\n * ```\n */\nexport function extractExtensionsFromQtiXml(xmlContent: string): Record<string, any> {\n\tif (!xmlContent) return {};\n\n\tconst metadata: Record<string, any> = {};\n\n\t// Priority 1: Try PIE extension first (perfect reconstruction)\n\tconst pieExtensionMatch = xmlContent.match(\n\t\t/<pie:sourceModel[^>]*>([\\s\\S]*?)<\\/pie:sourceModel>/i\n\t);\n\n\tif (pieExtensionMatch && pieExtensionMatch[1]) {\n\t\ttry {\n\t\t\tconst sourceModel = JSON.parse(pieExtensionMatch[1].trim());\n\t\t\t// `searchMetaData` is the bag's name in PIE items written before `extensions`\n\t\t\tconst extensions = sourceModel.extensions ?? sourceModel.searchMetaData;\n\t\t\tif (extensions) {\n\t\t\t\treturn extensions;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// Fall through to QTI metadata parsing\n\t\t}\n\t}\n\n\t// Priority 2: Parse <qti-metadata> section\n\tconst metadataSection = xmlContent.match(/<qti-metadata[^>]*>([\\s\\S]*?)<\\/qti-metadata>/i);\n\n\tif (metadataSection && metadataSection[1]) {\n\t\tconst fieldsContent = metadataSection[1];\n\n\t\t// Extract all qti-metadata-field elements\n\t\tconst fieldMatches = fieldsContent.matchAll(\n\t\t\t/<qti-metadata-field\\s+([^>]+)\\/?>(?:<\\/qti-metadata-field>)?/gi\n\t\t);\n\n\t\tfor (const match of fieldMatches) {\n\t\t\tconst attributesStr = match[1];\n\n\t\t\t// Extract name, value, and data-type attributes\n\t\t\tconst nameMatch = attributesStr.match(/name=[\"']([^\"']+)[\"']/i);\n\t\t\tconst valueMatch = attributesStr.match(/value=[\"']([^\"']*)[\"']/i);\n\t\t\tconst dataTypeMatch = attributesStr.match(/data-type=[\"']([^\"']+)[\"']/i);\n\n\t\t\tconst name = nameMatch?.[1];\n\t\t\tconst value = valueMatch?.[1];\n\t\t\tconst dataType = dataTypeMatch?.[1];\n\n\t\t\tif (!name || value === undefined) continue;\n\n\t\t\t// Restore original type\n\t\t\tif (dataType === 'array') {\n\t\t\t\tmetadata[name] = value.split(',').map((v) => v.trim());\n\t\t\t} else if (dataType === 'number') {\n\t\t\t\tmetadata[name] = parseFloat(value);\n\t\t\t} else {\n\t\t\t\tmetadata[name] = value;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn metadata;\n}\n\n/**\n * Extract interaction types from QTI item XML content\n *\n * Detects all QTI interaction types present in the item.\n *\n * @param xmlContent QTI XML content as string\n * @returns Array of detected interaction type names (e.g., [\"choiceInteraction\", \"textEntryInteraction\"])\n */\nexport function extractInteractionTypesFromQtiXml(xmlContent: string): string[] {\n\tif (!xmlContent) return [];\n\n\tconst interactionTypes = new Set<string>();\n\n\t// Common QTI interaction types\n\tconst knownInteractions = [\n\t\t'choiceInteraction',\n\t\t'orderInteraction',\n\t\t'associateInteraction',\n\t\t'matchInteraction',\n\t\t'gapMatchInteraction',\n\t\t'inlineChoiceInteraction',\n\t\t'textEntryInteraction',\n\t\t'extendedTextInteraction',\n\t\t'hottextInteraction',\n\t\t'hotspotInteraction',\n\t\t'selectPointInteraction',\n\t\t'graphicOrderInteraction',\n\t\t'graphicAssociateInteraction',\n\t\t'graphicGapMatchInteraction',\n\t\t'positionObjectInteraction',\n\t\t'sliderInteraction',\n\t\t'drawingInteraction',\n\t\t'uploadInteraction',\n\t\t'customInteraction',\n\t\t'endAttemptInteraction',\n\t];\n\n\tfor (const interactionType of knownInteractions) {\n\t\tconst pattern = new RegExp(`<${interactionType}[^>]*>`, 'i');\n\t\tif (pattern.test(xmlContent)) {\n\t\t\tinteractionTypes.add(interactionType);\n\t\t}\n\t}\n\n\treturn Array.from(interactionTypes);\n}\n\n/**\n * Extract comprehensive metadata from QTI item XML content\n *\n * Combines all metadata extraction functions to provide a complete metadata object.\n *\n * @param xmlContent QTI XML content as string\n * @returns Comprehensive QTI item metadata\n *\n * @example\n * ```ts\n * const xml = `<assessmentItem identifier=\"item1\" title=\"Question 1\">...</assessmentItem>`;\n * const metadata = extractQtiItemMetadata(xml);\n * // {\n * // identifier: \"item1\",\n * // title: \"Question 1\",\n * // extensions: {...},\n * // interactionTypes: [\"choiceInteraction\"]\n * // }\n * ```\n */\nexport function extractQtiItemMetadata(xmlContent: string): QtiItemMetadata {\n\treturn {\n\t\tidentifier: extractIdentifierFromQtiXml(xmlContent),\n\t\ttitle: extractTitleFromQtiXml(xmlContent),\n\t\textensions: extractExtensionsFromQtiXml(xmlContent),\n\t\tinteractionTypes: extractInteractionTypesFromQtiXml(xmlContent),\n\t};\n}\n"]}
1
+ {"version":3,"file":"qti-xml.js","sourceRoot":"","sources":["../../src/utils/qti-xml.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAoBH;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,sBAAsB,CAAC,UAAkB;IACxD,IAAI,CAAC,UAAU;QAAE,OAAO,SAAS,CAAC;IAElC,gEAAgE;IAChE,MAAM,cAAc,GAAG,UAAU,CAAC,KAAK,CAAC,gDAAgD,CAAC,CAAC;IAC1F,IAAI,cAAc,IAAI,cAAc,CAAC,CAAC,CAAC,EAAE,CAAC;QACzC,OAAO,cAAc,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACjC,CAAC;IAED,yDAAyD;IACzD,MAAM,kBAAkB,GAAG,UAAU,CAAC,KAAK,CAAC,gDAAgD,CAAC,CAAC;IAC9F,IAAI,kBAAkB,IAAI,kBAAkB,CAAC,CAAC,CAAC,EAAE,CAAC;QACjD,OAAO,kBAAkB,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACrC,CAAC;IAED,8CAA8C;IAC9C,mFAAmF;IACnF,MAAM,YAAY,GAAG,UAAU,CAAC,KAAK,CACpC,+EAA+E,CAC/E,CAAC;IACF,IAAI,YAAY,IAAI,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;QACrC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/B,CAAC;IAED,oFAAoF;IACpF,MAAM,aAAa,GAAG,UAAU,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACxE,IAAI,aAAa,IAAI,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,OAAO,aAAa,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAChC,CAAC;IAED,OAAO,SAAS,CAAC;A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,CAAC","sourcesContent":["/**\n * QTI XML utilities for extracting metadata and information from QTI XML content\n *\n * These utilities use regex-based parsing to remain environment-agnostic\n * (works in both browser and Node.js without heavy dependencies).\n */\n\n/**\n * Comprehensive QTI item metadata\n */\nexport interface QtiItemMetadata {\n\t/** Item identifier */\n\tidentifier?: string;\n\t/** Item title */\n\ttitle?: string;\n\t/** Item description */\n\tdescription?: string;\n\t/** Language code (e.g., \"en-US\") */\n\tlanguage?: string;\n\t/** Host-owned key/value pairs of the PIE item, or the QTI metadata fields */\n\textensions?: Record<string, any>;\n\t/** Detected interaction types */\n\tinteractionTypes?: string[];\n}\n\n/**\n * Extract title from QTI item/test XML content\n *\n * Handles multiple QTI title formats:\n * - Attribute-style: `<assessmentItem title=\"...\">`\n * - Attribute-style: `<assessmentTest title=\"...\">`\n * - Element-style: `<title>...</title>` within assessment elements\n * - Fallback: Any `<title>` element in the document\n *\n * @param xmlContent QTI XML content as string\n * @returns Extracted title or undefined if not found\n *\n * @example\n * ```ts\n * const xml = '<assessmentItem identifier=\"item1\" title=\"Question 1\">...</assessmentItem>';\n * const title = extractTitleFromQtiXml(xml); // \"Question 1\"\n * ```\n */\nexport function extractTitleFromQtiXml(xmlContent: string): string | undefined {\n\tif (!xmlContent) return undefined;\n\n\t// Try attribute-style title first: <assessmentItem title=\"...\">\n\tconst attributeMatch = xmlContent.match(/<assessmentItem[^>]*\\s+title=[\"']([^\"']+)[\"']/i);\n\tif (attributeMatch && attributeMatch[1]) {\n\t\treturn attributeMatch[1].trim();\n\t}\n\n\t// Try test attribute-style: <assessmentTest title=\"...\">\n\tconst testAttributeMatch = xmlContent.match(/<assessmentTest[^>]*\\s+title=[\"']([^\"']+)[\"']/i);\n\tif (testAttributeMatch && testAttributeMatch[1]) {\n\t\treturn testAttributeMatch[1].trim();\n\t}\n\n\t// Try element-style title: <title>...</title>\n\t// Look for title element that's a direct child of assessmentItem or assessmentTest\n\tconst elementMatch = xmlContent.match(\n\t\t/<(?:assessmentItem|assessmentTest)[^>]*>[\\s\\S]*?<title[^>]*>([^<]+)<\\/title>/i\n\t);\n\tif (elementMatch && elementMatch[1]) {\n\t\treturn elementMatch[1].trim();\n\t}\n\n\t// Fallback: look for any <title> element (less specific but might catch some cases)\n\tconst fallbackMatch = xmlContent.match(/<title[^>]*>([^<]+)<\\/title>/i);\n\tif (fallbackMatch && fallbackMatch[1]) {\n\t\treturn fallbackMatch[1].trim();\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Extract identifier from QTI item/test XML content\n *\n * @param xmlContent QTI XML content as string\n * @returns Extracted identifier or undefined if not found\n */\nexport function extractIdentifierFromQtiXml(xmlContent: string): string | undefined {\n\tif (!xmlContent) return undefined;\n\n\t// Try assessmentItem identifier\n\tconst itemMatch = xmlContent.match(/<assessmentItem[^>]*\\s+identifier=[\"']([^\"']+)[\"']/i);\n\tif (itemMatch && itemMatch[1]) {\n\t\treturn itemMatch[1].trim();\n\t}\n\n\t// Try assessmentTest identifier\n\tconst testMatch = xmlContent.match(/<assessmentTest[^>]*\\s+identifier=[\"']([^\"']+)[\"']/i);\n\tif (testMatch && testMatch[1]) {\n\t\treturn testMatch[1].trim();\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Extract a PIE item's extensions from QTI item XML content\n *\n * Priority 1: Check for PIE extension with embedded extensions (perfect reconstruction)\n * Priority 2: Parse QTI metadata section with qti-metadata-field elements\n *\n * @param xmlContent QTI XML content as string\n * @returns Extracted search metadata object\n *\n * @example\n * ```ts\n * const xml = `\n * <assessmentItem>\n * <qti-metadata>\n * <qti-metadata-field name=\"domain\" value=\"math\" />\n * <qti-metadata-field name=\"gradeLevel\" value=\"5,6,7\" data-type=\"array\" />\n * </qti-metadata>\n * </assessmentItem>\n * `;\n * const metadata = extractExtensionsFromQtiXml(xml);\n * // { domain: \"math\", gradeLevel: [\"5\", \"6\", \"7\"] }\n * ```\n */\nexport function extractExtensionsFromQtiXml(xmlContent: string): Record<string, any> {\n\tif (!xmlContent) return {};\n\n\tconst metadata: Record<string, any> = {};\n\n\t// Priority 1: Try PIE extension first (perfect reconstruction)\n\tconst pieExtensionMatch = xmlContent.match(\n\t\t/<pie:sourceModel[^>]*>([\\s\\S]*?)<\\/pie:sourceModel>/i\n\t);\n\n\tif (pieExtensionMatch && pieExtensionMatch[1]) {\n\t\ttry {\n\t\t\tconst sourceModel = JSON.parse(pieExtensionMatch[1].trim());\n\t\t\tconst extensions = sourceModel.extensions;\n\t\t\tif (extensions) {\n\t\t\t\treturn extensions;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// Fall through to QTI metadata parsing\n\t\t}\n\t}\n\n\t// Priority 2: Parse <qti-metadata> section\n\tconst metadataSection = xmlContent.match(/<qti-metadata[^>]*>([\\s\\S]*?)<\\/qti-metadata>/i);\n\n\tif (metadataSection && metadataSection[1]) {\n\t\tconst fieldsContent = metadataSection[1];\n\n\t\t// Extract all qti-metadata-field elements\n\t\tconst fieldMatches = fieldsContent.matchAll(\n\t\t\t/<qti-metadata-field\\s+([^>]+)\\/?>(?:<\\/qti-metadata-field>)?/gi\n\t\t);\n\n\t\tfor (const match of fieldMatches) {\n\t\t\tconst attributesStr = match[1];\n\n\t\t\t// Extract name, value, and data-type attributes\n\t\t\tconst nameMatch = attributesStr.match(/name=[\"']([^\"']+)[\"']/i);\n\t\t\tconst valueMatch = attributesStr.match(/value=[\"']([^\"']*)[\"']/i);\n\t\t\tconst dataTypeMatch = attributesStr.match(/data-type=[\"']([^\"']+)[\"']/i);\n\n\t\t\tconst name = nameMatch?.[1];\n\t\t\tconst value = valueMatch?.[1];\n\t\t\tconst dataType = dataTypeMatch?.[1];\n\n\t\t\tif (!name || value === undefined) continue;\n\n\t\t\t// Restore original type\n\t\t\tif (dataType === 'array') {\n\t\t\t\tmetadata[name] = value.split(',').map((v) => v.trim());\n\t\t\t} else if (dataType === 'number') {\n\t\t\t\tmetadata[name] = parseFloat(value);\n\t\t\t} else {\n\t\t\t\tmetadata[name] = value;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn metadata;\n}\n\n/**\n * Extract interaction types from QTI item XML content\n *\n * Detects all QTI interaction types present in the item.\n *\n * @param xmlContent QTI XML content as string\n * @returns Array of detected interaction type names (e.g., [\"choiceInteraction\", \"textEntryInteraction\"])\n */\nexport function extractInteractionTypesFromQtiXml(xmlContent: string): string[] {\n\tif (!xmlContent) return [];\n\n\tconst interactionTypes = new Set<string>();\n\n\t// Common QTI interaction types\n\tconst knownInteractions = [\n\t\t'choiceInteraction',\n\t\t'orderInteraction',\n\t\t'associateInteraction',\n\t\t'matchInteraction',\n\t\t'gapMatchInteraction',\n\t\t'inlineChoiceInteraction',\n\t\t'textEntryInteraction',\n\t\t'extendedTextInteraction',\n\t\t'hottextInteraction',\n\t\t'hotspotInteraction',\n\t\t'selectPointInteraction',\n\t\t'graphicOrderInteraction',\n\t\t'graphicAssociateInteraction',\n\t\t'graphicGapMatchInteraction',\n\t\t'positionObjectInteraction',\n\t\t'sliderInteraction',\n\t\t'drawingInteraction',\n\t\t'uploadInteraction',\n\t\t'customInteraction',\n\t\t'endAttemptInteraction',\n\t];\n\n\tfor (const interactionType of knownInteractions) {\n\t\tconst pattern = new RegExp(`<${interactionType}[^>]*>`, 'i');\n\t\tif (pattern.test(xmlContent)) {\n\t\t\tinteractionTypes.add(interactionType);\n\t\t}\n\t}\n\n\treturn Array.from(interactionTypes);\n}\n\n/**\n * Extract comprehensive metadata from QTI item XML content\n *\n * Combines all metadata extraction functions to provide a complete metadata object.\n *\n * @param xmlContent QTI XML content as string\n * @returns Comprehensive QTI item metadata\n *\n * @example\n * ```ts\n * const xml = `<assessmentItem identifier=\"item1\" title=\"Question 1\">...</assessmentItem>`;\n * const metadata = extractQtiItemMetadata(xml);\n * // {\n * // identifier: \"item1\",\n * // title: \"Question 1\",\n * // extensions: {...},\n * // interactionTypes: [\"choiceInteraction\"]\n * // }\n * ```\n */\nexport function extractQtiItemMetadata(xmlContent: string): QtiItemMetadata {\n\treturn {\n\t\tidentifier: extractIdentifierFromQtiXml(xmlContent),\n\t\ttitle: extractTitleFromQtiXml(xmlContent),\n\t\textensions: extractExtensionsFromQtiXml(xmlContent),\n\t\tinteractionTypes: extractInteractionTypesFromQtiXml(xmlContent),\n\t};\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pie-qti/ims-cp-core",
3
- "version": "1.0.0-beta.4",
3
+ "version": "1.0.0-beta.5",
4
4
  "description": "Core IMS Content Package manifest parsing utilities (browser + Node.js)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -40,7 +40,7 @@
40
40
  }
41
41
  },
42
42
  "dependencies": {
43
- "@pie-qti/logger": "1.0.0-beta.4",
43
+ "@pie-qti/logger": "1.0.0-beta.5",
44
44
  "node-html-parser": "^9.0.5"
45
45
  },
46
46
  "devDependencies": {