@pie-qti/ims-cp-core 0.1.0 → 0.1.4

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.
@@ -1,273 +0,0 @@
1
- /**
2
- * QTI Manifest (imsmanifest.xml) parser
3
- *
4
- * Parses IMS Content Package manifests to extract:
5
- * - Resource definitions (items, passages, assessments)
6
- * - Dependencies between resources
7
- * - File locations and types
8
- */
9
-
10
- import type { HTMLElement } from 'node-html-parser';
11
- import { parse } from 'node-html-parser';
12
- import { PassageRegistry } from './passage-reusability.js';
13
-
14
- /**
15
- * QTI resource type
16
- */
17
- export type ResourceType =
18
- | 'imsqti_item_xmlv2p1'
19
- | 'imsqti_item_xmlv2p2'
20
- | 'imsqti_test_xmlv2p1'
21
- | 'imsqti_test_xmlv2p2'
22
- | 'imsqti_assessment_xmlv2p1'
23
- | 'imsqti_apip_xmlv2p2'
24
- | 'webcontent'
25
- | 'associatedcontent/imsqti_item_xmlv2p1'
26
- | string;
27
-
28
- /**
29
- * Manifest resource entry
30
- */
31
- export interface ManifestResource {
32
- /** Resource identifier */
33
- identifier: string;
34
- /** Resource type */
35
- type: ResourceType;
36
- /**
37
- * Optional xml:base for this resource element.
38
- * Used by IMS CP to resolve relative hrefs when packages use nested bases.
39
- */
40
- xmlBase?: string;
41
- /** Main file href */
42
- href?: string;
43
- /** All files in this resource */
44
- files: string[];
45
- /** Dependencies (identifierrefs) */
46
- dependencies: string[];
47
- /** Metadata */
48
- metadata?: {
49
- title?: string;
50
- description?: string;
51
- /** IMS LOM language code (e.g., "en-US", "es-ES") */
52
- language?: string;
53
- };
54
- }
55
-
56
- /**
57
- * Parsed manifest structure
58
- */
59
- export interface ParsedManifest {
60
- /** Manifest identifier */
61
- identifier?: string;
62
- /**
63
- * Optional xml:base at the manifest element level.
64
- * Used by IMS CP to resolve relative hrefs.
65
- */
66
- xmlBase?: string;
67
- /** All resources */
68
- resources: Map<string, ManifestResource>;
69
- /** Item resources */
70
- items: ManifestResource[];
71
- /** Passage/stimulus resources */
72
- passages: ManifestResource[];
73
- /** Test/assessment resources */
74
- tests: ManifestResource[];
75
- /** Base path for resolving relative paths */
76
- basePath?: string;
77
- }
78
-
79
- /**
80
- * Parse QTI manifest XML
81
- */
82
- export function parseManifest(manifestXml: string, basePath?: string): ParsedManifest {
83
- const doc = parse(manifestXml, {
84
- lowerCaseTagName: false,
85
- comment: false,
86
- });
87
-
88
- const manifest = doc.querySelector('manifest') || doc.getElementsByTagName('manifest')[0];
89
-
90
- if (!manifest) {
91
- throw new Error('No manifest element found in XML');
92
- }
93
-
94
- const manifestId = manifest.getAttribute('identifier');
95
- const manifestXmlBase = manifest.getAttribute('xml:base') || undefined;
96
-
97
- // Parse all resources
98
- const resourcesElement = manifest.querySelector('resources') ||
99
- manifest.getElementsByTagName('resources')[0];
100
-
101
- if (!resourcesElement) {
102
- return {
103
- identifier: manifestId,
104
- resources: new Map(),
105
- items: [],
106
- passages: [],
107
- tests: [],
108
- basePath,
109
- };
110
- }
111
-
112
- const resourceElements = resourcesElement.getElementsByTagName('resource');
113
- const resources = new Map<string, ManifestResource>();
114
- const items: ManifestResource[] = [];
115
- const passages: ManifestResource[] = [];
116
- const tests: ManifestResource[] = [];
117
-
118
- for (const resourceEl of Array.from(resourceElements)) {
119
- const resource = parseResource(resourceEl);
120
- resources.set(resource.identifier, resource);
121
-
122
- // Categorize by type
123
- if (isItemType(resource.type)) {
124
- items.push(resource);
125
- } else if (isPassageType(resource.type)) {
126
- passages.push(resource);
127
- } else if (isTestType(resource.type)) {
128
- tests.push(resource);
129
- }
130
- }
131
-
132
- return {
133
- identifier: manifestId,
134
- xmlBase: manifestXmlBase,
135
- resources,
136
- items,
137
- passages,
138
- tests,
139
- basePath,
140
- };
141
- }
142
-
143
- /**
144
- * Parse individual resource element
145
- */
146
- function parseResource(resourceEl: HTMLElement): ManifestResource {
147
- const identifier = resourceEl.getAttribute('identifier') || '';
148
- const type = resourceEl.getAttribute('type') || '';
149
- const href = resourceEl.getAttribute('href') || undefined;
150
- const xmlBase = resourceEl.getAttribute('xml:base') || undefined;
151
-
152
- // Extract all file elements
153
- const fileElements = resourceEl.getElementsByTagName('file');
154
- const files = Array.from(fileElements)
155
- .map(f => f.getAttribute('href'))
156
- .filter((h): h is string => !!h);
157
-
158
- // If href not specified but files exist, use first file as href
159
- const mainHref = href || (files.length > 0 ? files[0] : undefined);
160
-
161
- // Extract dependencies
162
- const depElements = resourceEl.getElementsByTagName('dependency');
163
- const dependencies = Array.from(depElements)
164
- .map(d => d.getAttribute('identifierref'))
165
- .filter((id): id is string => !!id);
166
-
167
- // Extract metadata if present
168
- let metadata: { title?: string; description?: string; language?: string } | undefined;
169
- const metadataEl = resourceEl.querySelector('metadata');
170
- if (metadataEl) {
171
- const title = metadataEl.querySelector('title')?.textContent?.trim();
172
- const description = metadataEl.querySelector('description')?.textContent?.trim();
173
-
174
- // Extract IMS LOM language (supports multiple selector patterns)
175
- const languageEl = metadataEl.querySelector('language, [\\:language]') ||
176
- metadataEl.querySelector('[name="language"]');
177
- const language = languageEl?.textContent?.trim();
178
-
179
- if (title || description || language) {
180
- metadata = { title, description, language };
181
- }
182
- }
183
-
184
- return {
185
- identifier,
186
- type,
187
- xmlBase,
188
- href: mainHref,
189
- files,
190
- dependencies,
191
- metadata,
192
- };
193
- }
194
-
195
- /**
196
- * Check if resource type is an item
197
- */
198
- function isItemType(type: string): boolean {
199
- return type.includes('imsqti_item') ||
200
- type.includes('qti_item') ||
201
- type === 'associatedcontent/imsqti_item_xmlv2p1';
202
- }
203
-
204
- /**
205
- * Check if resource type is a passage/stimulus
206
- */
207
- function isPassageType(type: string): boolean {
208
- return type === 'webcontent' ||
209
- type.includes('passage') ||
210
- type.includes('stimulus') ||
211
- type.includes('apip');
212
- }
213
-
214
- /**
215
- * Check if resource type is a test/assessment
216
- */
217
- function isTestType(type: string): boolean {
218
- return type.includes('test') || type.includes('assessment');
219
- }
220
-
221
- /**
222
- * Build passage registry from manifest
223
- *
224
- * Analyzes manifest to identify:
225
- * - Which passages are referenced by items
226
- * - Which passages are reusable (multiple items reference them)
227
- */
228
- export function buildPassageRegistryFromManifest(
229
- manifest: ParsedManifest
230
- ): PassageRegistry {
231
- const registry = new PassageRegistry();
232
-
233
- // Register all passage resources
234
- for (const passage of manifest.passages) {
235
- // Find all items that depend on this passage
236
- for (const item of manifest.items) {
237
- if (item.dependencies.includes(passage.identifier)) {
238
- registry.registerReference(item.identifier, {
239
- id: passage.identifier, // Use QTI identifier directly
240
- source: 'manifest',
241
- qtiIdentifier: passage.identifier,
242
- filePath: passage.href,
243
- isReusable: false, // Will be updated by registry
244
- });
245
- }
246
- }
247
- }
248
-
249
- return registry;
250
- }
251
-
252
- /**
253
- * Get passage content file path from manifest
254
- */
255
- export function getPassageFilePath(
256
- manifest: ParsedManifest,
257
- passageId: string
258
- ): string | undefined {
259
- const passage = manifest.resources.get(passageId);
260
- return passage?.href;
261
- }
262
-
263
- /**
264
- * Get all items that depend on a passage
265
- */
266
- export function getItemsReferencingPassage(
267
- manifest: ParsedManifest,
268
- passageId: string
269
- ): ManifestResource[] {
270
- return manifest.items.filter(item =>
271
- item.dependencies.includes(passageId)
272
- );
273
- }
@@ -1,221 +0,0 @@
1
- /**
2
- * Passage reusability detection and stable ID management
3
- *
4
- * QTI provides several mechanisms for reusable content:
5
- * 1. Manifest <dependency> elements - explicit reusability declaration
6
- * 2. Object <object data="..."> references - shared file paths
7
- * 3. assessmentStimulus/assessmentPassage identifiers - stable IDs
8
- *
9
- * This module provides stable ID generation and reusability detection.
10
- */
11
-
12
- import { sha256 } from './utils/hash.js';
13
-
14
- /**
15
- * Generate stable ID for passage content
16
- *
17
- * Strategy (in priority order):
18
- * 1. Use QTI identifier directly - QTI identifiers are designed to be globally unique
19
- * across vendors and packages (e.g., "urn:example.com:passage:12345")
20
- * 2. Use file path for object references - stable within a package
21
- * 3. Use content hash for inline stimulus - ensures same content = same ID
22
- *
23
- * @param options Options for ID generation
24
- * @returns Stable passage ID (async for content hashing)
25
- */
26
- export async function generateStablePassageId(options: {
27
- /** QTI identifier from assessmentStimulus or assessmentPassage - USE DIRECTLY */
28
- qtiIdentifier?: string;
29
- /** File path from object data attribute */
30
- filePath?: string;
31
- /** Content hash for inline stimulus */
32
- content?: string;
33
- /** Prefix for generated IDs (only used for hashed IDs) */
34
- prefix?: string;
35
- }): Promise<string> {
36
- const prefix = options.prefix || 'passage';
37
-
38
- // Priority 1: Use QTI identifier DIRECTLY (no prefix)
39
- // QTI identifiers are designed to be globally unique across vendors
40
- // Examples: "urn:example.com:passage:12345", "stim-industrial-revolution"
41
- if (options.qtiIdentifier) {
42
- return options.qtiIdentifier;
43
- }
44
-
45
- // Priority 2: Use file path for object references
46
- // Normalize path (remove leading ./ and ../) and use as-is with prefix
47
- if (options.filePath) {
48
- const normalizedPath = options.filePath
49
- .replace(/^\.\//, '')
50
- .replace(/\.\.\//g, '')
51
- .replace(/\//g, '-')
52
- .replace(/\.(xml|html|txt)$/, '');
53
- return `${prefix}-${normalizedPath}`;
54
- }
55
-
56
- // Priority 3: Use content hash for inline stimulus (stable for same content)
57
- if (options.content) {
58
- const contentHash = await sha256(options.content.trim());
59
- return `${prefix}-content-${contentHash.substring(0, 12)}`;
60
- }
61
-
62
- throw new Error('Must provide at least one of: qtiIdentifier, filePath, or content');
63
- }
64
-
65
- /**
66
- * Passage reference information
67
- */
68
- export interface PassageReference {
69
- /** Stable passage ID */
70
- id: string;
71
- /** Source of the passage */
72
- source: 'inline' | 'file' | 'manifest' | 'qti-element';
73
- /** Original QTI identifier if available */
74
- qtiIdentifier?: string;
75
- /** File path if from object reference */
76
- filePath?: string;
77
- /** Whether this passage is referenced by multiple items */
78
- isReusable: boolean;
79
- }
80
-
81
- /**
82
- * Track passage references across a package
83
- * Used during batch transformation to detect reusable passages
84
- */
85
- export class PassageRegistry {
86
- private passages = new Map<string, {
87
- reference: PassageReference;
88
- referencedBy: Set<string>;
89
- content?: string;
90
- }>();
91
-
92
- /**
93
- * Register a passage reference
94
- * @param itemId ID of the item referencing this passage
95
- * @param reference Passage reference information
96
- */
97
- registerReference(itemId: string, reference: PassageReference): void {
98
- const existing = this.passages.get(reference.id);
99
-
100
- if (existing) {
101
- // Passage already registered, add this item as a reference
102
- existing.referencedBy.add(itemId);
103
- existing.reference.isReusable = existing.referencedBy.size > 1;
104
- } else {
105
- // First reference to this passage
106
- this.passages.set(reference.id, {
107
- reference: { ...reference, isReusable: false },
108
- referencedBy: new Set([itemId]),
109
- });
110
- }
111
- }
112
-
113
- /**
114
- * Store passage content for deduplication
115
- * @param passageId Passage ID
116
- * @param content Passage content
117
- */
118
- storeContent(passageId: string, content: string): void {
119
- const entry = this.passages.get(passageId);
120
- if (entry) {
121
- entry.content = content;
122
- }
123
- }
124
-
125
- /**
126
- * Get passage reference by ID
127
- * @param passageId Passage ID
128
- * @returns Passage reference with updated reusability flag
129
- */
130
- getReference(passageId: string): PassageReference | undefined {
131
- return this.passages.get(passageId)?.reference;
132
- }
133
-
134
- /**
135
- * Get all items that reference a passage
136
- * @param passageId Passage ID
137
- * @returns Set of item IDs
138
- */
139
- getReferencingItems(passageId: string): Set<string> {
140
- return this.passages.get(passageId)?.referencedBy || new Set();
141
- }
142
-
143
- /**
144
- * Get all registered passages
145
- * @returns Array of passage references
146
- */
147
- getAllPassages(): PassageReference[] {
148
- return Array.from(this.passages.values()).map(entry => entry.reference);
149
- }
150
-
151
- /**
152
- * Get reusable passages (referenced by multiple items)
153
- * @returns Array of reusable passage references
154
- */
155
- getReusablePassages(): PassageReference[] {
156
- return this.getAllPassages().filter(ref => ref.isReusable);
157
- }
158
-
159
- /**
160
- * Detect duplicate content and merge passages
161
- * This handles cases where same content appears with different IDs
162
- */
163
- async detectAndMergeDuplicates(): Promise<Map<string, string>> {
164
- const contentMap = new Map<string, string>(); // content hash -> primary ID
165
- const mergeMap = new Map<string, string>(); // old ID -> new ID
166
-
167
- for (const [id, entry] of this.passages.entries()) {
168
- if (!entry.content) continue;
169
-
170
- const contentHash = await sha256(entry.content.trim());
171
-
172
- const existingId = contentMap.get(contentHash);
173
- if (existingId && existingId !== id) {
174
- // Duplicate content found - merge into existing
175
- mergeMap.set(id, existingId);
176
-
177
- const existingEntry = this.passages.get(existingId)!;
178
- for (const itemId of entry.referencedBy) {
179
- existingEntry.referencedBy.add(itemId);
180
- }
181
- existingEntry.reference.isReusable = existingEntry.referencedBy.size > 1;
182
-
183
- this.passages.delete(id);
184
- } else {
185
- contentMap.set(contentHash, id);
186
- }
187
- }
188
-
189
- return mergeMap;
190
- }
191
- }
192
-
193
- /**
194
- * Parse object tag to extract passage reference
195
- * @param objectElement Object element from QTI
196
- * @returns Passage reference or null
197
- */
198
- export async function parseObjectReference(objectElement: any): Promise<PassageReference | null> {
199
- const dataAttr = objectElement.getAttribute?.('data');
200
- const typeAttr = objectElement.getAttribute?.('type');
201
-
202
- // Check if it's a passage reference (text/html, text/plain, or no type)
203
- const isPassageType = !typeAttr ||
204
- typeAttr === 'text/html' ||
205
- typeAttr === 'text/plain' ||
206
- typeAttr.startsWith('text/');
207
-
208
- if (!dataAttr || !isPassageType) {
209
- return null;
210
- }
211
-
212
- // Generate stable ID from file path
213
- const id = await generateStablePassageId({ filePath: dataAttr });
214
-
215
- return {
216
- id,
217
- source: 'file',
218
- filePath: dataAttr,
219
- isReusable: false, // Will be updated by registry
220
- };
221
- }
package/src/utils/hash.ts DELETED
@@ -1,34 +0,0 @@
1
- /**
2
- * Universal SHA-256 hashing utility
3
- * Works in both browser (Web Crypto API) and Node.js (crypto module)
4
- */
5
-
6
- /**
7
- * Generate SHA-256 hash of content
8
- *
9
- * In browsers, uses the Web Crypto API (crypto.subtle.digest).
10
- * In Node.js, uses the crypto module (createHash).
11
- *
12
- * @param content String content to hash
13
- * @returns Hex-encoded hash string (64 characters)
14
- *
15
- * @example
16
- * ```typescript
17
- * const hash = await sha256('hello world');
18
- * console.log(hash); // "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
19
- * ```
20
- */
21
- export async function sha256(content: string): Promise<string> {
22
- // Browser environment: Use Web Crypto API
23
- if (typeof crypto !== 'undefined' && crypto.subtle) {
24
- const encoder = new TextEncoder();
25
- const data = encoder.encode(content);
26
- const hashBuffer = await crypto.subtle.digest('SHA-256', data);
27
- const hashArray = Array.from(new Uint8Array(hashBuffer));
28
- return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
29
- }
30
-
31
- // Node.js environment: Use crypto module
32
- const { createHash } = await import('crypto');
33
- return createHash('sha256').update(content).digest('hex');
34
- }
package/tsconfig.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./src",
6
- "lib": ["ES2022"]
7
- },
8
- "include": ["src/**/*"]
9
- }