@pie-qti/transform-core 0.1.1
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/.turbo/turbo-build.log +1 -0
- package/CHANGELOG.md +10 -0
- package/VALIDATION.md +217 -0
- package/dist/engine/index.d.ts +2 -0
- package/dist/engine/index.d.ts.map +1 -0
- package/dist/engine/index.js +2 -0
- package/dist/engine/index.js.map +1 -0
- package/dist/engine/transform-engine.d.ts +58 -0
- package/dist/engine/transform-engine.d.ts.map +1 -0
- package/dist/engine/transform-engine.js +173 -0
- package/dist/engine/transform-engine.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/registry/index.d.ts +2 -0
- package/dist/registry/index.d.ts.map +1 -0
- package/dist/registry/index.js +2 -0
- package/dist/registry/index.js.map +1 -0
- package/dist/registry/plugin-registry.d.ts +54 -0
- package/dist/registry/plugin-registry.d.ts.map +1 -0
- package/dist/registry/plugin-registry.js +86 -0
- package/dist/registry/plugin-registry.js.map +1 -0
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/index.js +2 -0
- package/dist/utils/index.js.map +1 -0
- package/dist/utils/logger.d.ts +40 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/logger.js +61 -0
- package/dist/utils/logger.js.map +1 -0
- package/dist/utils/validator.d.ts +60 -0
- package/dist/utils/validator.d.ts.map +1 -0
- package/dist/utils/validator.js +161 -0
- package/dist/utils/validator.js.map +1 -0
- package/package.json +38 -0
- package/src/engine/index.ts +1 -0
- package/src/engine/transform-engine.ts +257 -0
- package/src/index.ts +18 -0
- package/src/registry/index.ts +1 -0
- package/src/registry/plugin-registry.ts +116 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/logger.ts +79 -0
- package/src/utils/validator.ts +193 -0
- package/tests/plugin-registry.test.ts +154 -0
- package/tests/transform-engine.test.ts +168 -0
- package/tests/validator.test.ts +234 -0
- package/tsconfig.json +13 -0
- package/tsconfig.tsbuildinfo +1 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transform Engine
|
|
3
|
+
*
|
|
4
|
+
* Core transformation engine that orchestrates plugins
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type {
|
|
8
|
+
TransformContext,
|
|
9
|
+
TransformFormat,
|
|
10
|
+
TransformInput,
|
|
11
|
+
TransformLogger,
|
|
12
|
+
TransformOutput,
|
|
13
|
+
TransformPlugin,
|
|
14
|
+
} from '@pie-qti/transform-types';
|
|
15
|
+
import { PluginRegistry } from '../registry/plugin-registry.js';
|
|
16
|
+
import { ConsoleLogger } from '../utils/logger.js';
|
|
17
|
+
|
|
18
|
+
export interface TransformOptions {
|
|
19
|
+
/** Source format (will be auto-detected if not provided) */
|
|
20
|
+
sourceFormat?: TransformFormat;
|
|
21
|
+
|
|
22
|
+
/** Target format */
|
|
23
|
+
targetFormat: TransformFormat;
|
|
24
|
+
|
|
25
|
+
/** Vendor-specific options */
|
|
26
|
+
vendor?: string;
|
|
27
|
+
|
|
28
|
+
/** Logger instance */
|
|
29
|
+
logger?: TransformLogger;
|
|
30
|
+
|
|
31
|
+
/** Additional options */
|
|
32
|
+
[key: string]: any;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class TransformEngine {
|
|
36
|
+
private registry: PluginRegistry;
|
|
37
|
+
private defaultLogger: TransformLogger;
|
|
38
|
+
|
|
39
|
+
constructor() {
|
|
40
|
+
this.registry = new PluginRegistry();
|
|
41
|
+
this.defaultLogger = new ConsoleLogger();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Register a plugin
|
|
46
|
+
*/
|
|
47
|
+
use(plugin: TransformPlugin): this {
|
|
48
|
+
this.registry.register(plugin);
|
|
49
|
+
return this;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Transform input to target format
|
|
54
|
+
*/
|
|
55
|
+
async transform(
|
|
56
|
+
input: string | object,
|
|
57
|
+
options: TransformOptions
|
|
58
|
+
): Promise<TransformOutput> {
|
|
59
|
+
const startTime = Date.now();
|
|
60
|
+
const logger = options.logger || this.defaultLogger;
|
|
61
|
+
|
|
62
|
+
// Prepare input
|
|
63
|
+
const transformInput: TransformInput = {
|
|
64
|
+
content: input,
|
|
65
|
+
format: options.sourceFormat,
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
// Detect format if not provided
|
|
69
|
+
const sourceFormat = options.sourceFormat || (await this.detectFormat(transformInput));
|
|
70
|
+
|
|
71
|
+
logger.info(`Transforming from ${sourceFormat} to ${options.targetFormat}`);
|
|
72
|
+
|
|
73
|
+
// Find appropriate plugin
|
|
74
|
+
const plugin = this.registry.findPlugin(sourceFormat, options.targetFormat);
|
|
75
|
+
|
|
76
|
+
if (!plugin) {
|
|
77
|
+
throw new Error(
|
|
78
|
+
`No plugin found for transformation: ${sourceFormat} → ${options.targetFormat}`
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
logger.debug(`Using plugin: ${plugin.name} (${plugin.id})`);
|
|
83
|
+
|
|
84
|
+
// Create context
|
|
85
|
+
const context: TransformContext = {
|
|
86
|
+
logger,
|
|
87
|
+
vendor: options.vendor,
|
|
88
|
+
options,
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// Initialize plugin if needed
|
|
92
|
+
if (plugin.initialize) {
|
|
93
|
+
logger.debug('Initializing plugin...');
|
|
94
|
+
await plugin.initialize(options);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Transform
|
|
98
|
+
logger.info('Starting transformation...');
|
|
99
|
+
const output = await plugin.transform(transformInput, context);
|
|
100
|
+
|
|
101
|
+
// Validate output if plugin supports it
|
|
102
|
+
if (plugin.validate) {
|
|
103
|
+
logger.debug('Validating output...');
|
|
104
|
+
const validation = await plugin.validate(output);
|
|
105
|
+
if (!validation.valid) {
|
|
106
|
+
logger.warn('Validation warnings/errors detected');
|
|
107
|
+
if (validation.errors && validation.errors.length > 0) {
|
|
108
|
+
validation.errors.forEach((error) => logger.error(error));
|
|
109
|
+
}
|
|
110
|
+
if (validation.warnings && validation.warnings.length > 0) {
|
|
111
|
+
validation.warnings.forEach((warning) => logger.warn(warning));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Update metadata
|
|
117
|
+
const processingTime = Date.now() - startTime;
|
|
118
|
+
output.metadata = {
|
|
119
|
+
...output.metadata,
|
|
120
|
+
sourceFormat,
|
|
121
|
+
targetFormat: options.targetFormat,
|
|
122
|
+
pluginId: plugin.id,
|
|
123
|
+
timestamp: new Date(),
|
|
124
|
+
itemCount: output.items.length,
|
|
125
|
+
processingTime,
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
logger.info(
|
|
129
|
+
`Transformation complete: ${output.items.length} items in ${processingTime}ms`
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
return output;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Transform multiple inputs in batch
|
|
137
|
+
*/
|
|
138
|
+
async transformBatch(
|
|
139
|
+
inputs: Array<string | object>,
|
|
140
|
+
options: TransformOptions & { parallel?: number }
|
|
141
|
+
): Promise<TransformOutput[]> {
|
|
142
|
+
const parallelism = options.parallel || 5;
|
|
143
|
+
const logger = options.logger || this.defaultLogger;
|
|
144
|
+
|
|
145
|
+
logger.info(`Batch transforming ${inputs.length} items with parallelism=${parallelism}`);
|
|
146
|
+
|
|
147
|
+
const results: TransformOutput[] = [];
|
|
148
|
+
const chunks: Array<Array<string | object>> = [];
|
|
149
|
+
|
|
150
|
+
// Split into chunks
|
|
151
|
+
for (let i = 0; i < inputs.length; i += parallelism) {
|
|
152
|
+
chunks.push(inputs.slice(i, i + parallelism));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Process chunks
|
|
156
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
157
|
+
const chunk = chunks[i];
|
|
158
|
+
logger.debug(`Processing chunk ${i + 1}/${chunks.length} (${chunk.length} items)`);
|
|
159
|
+
|
|
160
|
+
const chunkResults = await Promise.all(
|
|
161
|
+
chunk.map((input) => this.transform(input, options))
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
results.push(...chunkResults);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
logger.info(`Batch transformation complete: ${results.length} outputs`);
|
|
168
|
+
return results;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Transform stream of inputs
|
|
173
|
+
*/
|
|
174
|
+
async *transformStream(
|
|
175
|
+
inputs: AsyncIterable<string | object>,
|
|
176
|
+
options: TransformOptions
|
|
177
|
+
): AsyncGenerator<TransformOutput> {
|
|
178
|
+
const logger = options.logger || this.defaultLogger;
|
|
179
|
+
|
|
180
|
+
logger.info('Starting streaming transformation...');
|
|
181
|
+
|
|
182
|
+
let count = 0;
|
|
183
|
+
for await (const input of inputs) {
|
|
184
|
+
const output = await this.transform(input, options);
|
|
185
|
+
count++;
|
|
186
|
+
logger.debug(`Streamed ${count} items`);
|
|
187
|
+
yield output;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
logger.info(`Streaming transformation complete: ${count} items`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Auto-detect input format
|
|
195
|
+
*/
|
|
196
|
+
private async detectFormat(input: TransformInput): Promise<TransformFormat> {
|
|
197
|
+
// If content is string, try to detect XML (QTI) vs JSON (PIE)
|
|
198
|
+
if (typeof input.content === 'string') {
|
|
199
|
+
const trimmed = input.content.trim();
|
|
200
|
+
|
|
201
|
+
if (trimmed.startsWith('<?xml') || trimmed.startsWith('<')) {
|
|
202
|
+
// It's XML - this repo only supports QTI 2.2.x at transform time.
|
|
203
|
+
if (
|
|
204
|
+
trimmed.includes('imsqti_v2p2') ||
|
|
205
|
+
trimmed.includes('http://www.imsglobal.org/xsd/imsqti_v2p2')
|
|
206
|
+
) {
|
|
207
|
+
return 'qti22';
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
throw new Error(
|
|
211
|
+
'Unsupported QTI namespace. Expected QTI 2.2 (imsqti_v2p2).'
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
216
|
+
// It's JSON - assume PIE
|
|
217
|
+
return 'pie';
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// If object, assume PIE
|
|
222
|
+
if (typeof input.content === 'object') {
|
|
223
|
+
return 'pie';
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
throw new Error('Could not detect input format');
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Get all registered plugins
|
|
231
|
+
*/
|
|
232
|
+
getPlugins(): TransformPlugin[] {
|
|
233
|
+
return this.registry.getAll();
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Get plugin by ID
|
|
238
|
+
*/
|
|
239
|
+
getPlugin(id: string): TransformPlugin | undefined {
|
|
240
|
+
return this.registry.get(id);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Cleanup resources
|
|
245
|
+
*/
|
|
246
|
+
async dispose(): Promise<void> {
|
|
247
|
+
const plugins = this.registry.getAll();
|
|
248
|
+
|
|
249
|
+
for (const plugin of plugins) {
|
|
250
|
+
if (plugin.dispose) {
|
|
251
|
+
await plugin.dispose();
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
this.registry.clear();
|
|
256
|
+
}
|
|
257
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @pie-qti/transform-core
|
|
3
|
+
*
|
|
4
|
+
* Core transformation engine and plugin system
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
// Re-export types from transform-types
|
|
8
|
+
export type * from '@pie-qti/transform-types';
|
|
9
|
+
|
|
10
|
+
// Engine
|
|
11
|
+
export * from './engine/transform-engine.js';
|
|
12
|
+
|
|
13
|
+
// Registry
|
|
14
|
+
export * from './registry/plugin-registry.js';
|
|
15
|
+
|
|
16
|
+
// Utilities
|
|
17
|
+
export * from './utils/logger.js';
|
|
18
|
+
export * from './utils/validator.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './plugin-registry';
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin Registry
|
|
3
|
+
*
|
|
4
|
+
* Central registry for managing transformation plugins
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type {
|
|
8
|
+
TransformFormat,
|
|
9
|
+
TransformInput,
|
|
10
|
+
TransformPlugin,
|
|
11
|
+
} from '@pie-qti/transform-types';
|
|
12
|
+
|
|
13
|
+
export class PluginRegistry {
|
|
14
|
+
private plugins = new Map<string, TransformPlugin>();
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Register a plugin
|
|
18
|
+
*/
|
|
19
|
+
register(plugin: TransformPlugin): void {
|
|
20
|
+
if (this.plugins.has(plugin.id)) {
|
|
21
|
+
throw new Error(`Plugin with id '${plugin.id}' is already registered`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
this.plugins.set(plugin.id, plugin);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Unregister a plugin
|
|
29
|
+
*/
|
|
30
|
+
unregister(pluginId: string): boolean {
|
|
31
|
+
return this.plugins.delete(pluginId);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Get a plugin by ID
|
|
36
|
+
*/
|
|
37
|
+
get(pluginId: string): TransformPlugin | undefined {
|
|
38
|
+
return this.plugins.get(pluginId);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Check if a plugin is registered
|
|
43
|
+
*/
|
|
44
|
+
has(pluginId: string): boolean {
|
|
45
|
+
return this.plugins.has(pluginId);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Get all registered plugins
|
|
50
|
+
*/
|
|
51
|
+
getAll(): TransformPlugin[] {
|
|
52
|
+
return Array.from(this.plugins.values());
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Find plugin that can handle transformation from source to target format
|
|
57
|
+
*/
|
|
58
|
+
findPlugin(
|
|
59
|
+
sourceFormat: TransformFormat,
|
|
60
|
+
targetFormat: TransformFormat
|
|
61
|
+
): TransformPlugin | undefined {
|
|
62
|
+
return Array.from(this.plugins.values()).find(
|
|
63
|
+
(plugin) =>
|
|
64
|
+
plugin.sourceFormat === sourceFormat &&
|
|
65
|
+
plugin.targetFormat === targetFormat
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Find plugins that can handle the given input
|
|
71
|
+
*/
|
|
72
|
+
async findCompatiblePlugins(input: TransformInput): Promise<TransformPlugin[]> {
|
|
73
|
+
const compatible: TransformPlugin[] = [];
|
|
74
|
+
|
|
75
|
+
for (const plugin of this.plugins.values()) {
|
|
76
|
+
const canHandle = await plugin.canHandle(input);
|
|
77
|
+
if (canHandle) {
|
|
78
|
+
compatible.push(plugin);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return compatible;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Get plugins by source format
|
|
87
|
+
*/
|
|
88
|
+
getBySourceFormat(format: TransformFormat): TransformPlugin[] {
|
|
89
|
+
return Array.from(this.plugins.values()).filter(
|
|
90
|
+
(plugin) => plugin.sourceFormat === format
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Get plugins by target format
|
|
96
|
+
*/
|
|
97
|
+
getByTargetFormat(format: TransformFormat): TransformPlugin[] {
|
|
98
|
+
return Array.from(this.plugins.values()).filter(
|
|
99
|
+
(plugin) => plugin.targetFormat === format
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Clear all registered plugins
|
|
105
|
+
*/
|
|
106
|
+
clear(): void {
|
|
107
|
+
this.plugins.clear();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Get count of registered plugins
|
|
112
|
+
*/
|
|
113
|
+
get size(): number {
|
|
114
|
+
return this.plugins.size;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './logger';
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logger Utilities
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { TransformLogger } from '@pie-qti/transform-types';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Simple console logger
|
|
9
|
+
*/
|
|
10
|
+
export class ConsoleLogger implements TransformLogger {
|
|
11
|
+
debug(message: string, itemId?: string): void {
|
|
12
|
+
const prefix = itemId ? `[${itemId}]` : '';
|
|
13
|
+
console.debug(`[DEBUG] ${prefix} ${message}`);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
info(message: string, itemId?: string): void {
|
|
17
|
+
const prefix = itemId ? `[${itemId}]` : '';
|
|
18
|
+
console.info(`[INFO] ${prefix} ${message}`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
warn(message: string, itemId?: string): void {
|
|
22
|
+
const prefix = itemId ? `[${itemId}]` : '';
|
|
23
|
+
console.warn(`[WARN] ${prefix} ${message}`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
error(message: string, itemId?: string): void {
|
|
27
|
+
const prefix = itemId ? `[${itemId}]` : '';
|
|
28
|
+
console.error(`[ERROR] ${prefix} ${message}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Silent logger (no output)
|
|
34
|
+
*/
|
|
35
|
+
export class SilentLogger implements TransformLogger {
|
|
36
|
+
debug(): void {}
|
|
37
|
+
info(): void {}
|
|
38
|
+
warn(): void {}
|
|
39
|
+
error(): void {}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Memory logger (stores messages in memory)
|
|
44
|
+
*/
|
|
45
|
+
export class MemoryLogger implements TransformLogger {
|
|
46
|
+
public messages: Array<{
|
|
47
|
+
level: 'debug' | 'info' | 'warn' | 'error';
|
|
48
|
+
message: string;
|
|
49
|
+
itemId?: string;
|
|
50
|
+
timestamp: Date;
|
|
51
|
+
}> = [];
|
|
52
|
+
|
|
53
|
+
debug(message: string, itemId?: string): void {
|
|
54
|
+
this.messages.push({ level: 'debug', message, itemId, timestamp: new Date() });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
info(message: string, itemId?: string): void {
|
|
58
|
+
this.messages.push({ level: 'info', message, itemId, timestamp: new Date() });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
warn(message: string, itemId?: string): void {
|
|
62
|
+
this.messages.push({ level: 'warn', message, itemId, timestamp: new Date() });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
error(message: string, itemId?: string): void {
|
|
66
|
+
this.messages.push({ level: 'error', message, itemId, timestamp: new Date() });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
clear(): void {
|
|
70
|
+
this.messages = [];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
getMessages(level?: 'debug' | 'info' | 'warn' | 'error'): typeof this.messages {
|
|
74
|
+
if (level) {
|
|
75
|
+
return this.messages.filter((msg) => msg.level === level);
|
|
76
|
+
}
|
|
77
|
+
return this.messages;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validation utilities for PIE items and QTI content
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { type ElementType, loadSchema } from '@pie-qti/element-schemas';
|
|
6
|
+
import type { ValidationResult as BaseValidationResult, PieItem } from '@pie-qti/transform-types';
|
|
7
|
+
import Ajv from 'ajv';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Detailed validation error with path information
|
|
11
|
+
*/
|
|
12
|
+
export interface ValidationError {
|
|
13
|
+
path: string;
|
|
14
|
+
message: string;
|
|
15
|
+
value?: any;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Extended validation result with detailed error information
|
|
20
|
+
*/
|
|
21
|
+
export interface DetailedValidationResult extends BaseValidationResult {
|
|
22
|
+
detailedErrors?: ValidationError[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* PIE Item Validator
|
|
27
|
+
* Validates PIE items against JSON schemas
|
|
28
|
+
*/
|
|
29
|
+
export class PieItemValidator {
|
|
30
|
+
private ajv: Ajv;
|
|
31
|
+
private schemas: Map<string, object>;
|
|
32
|
+
|
|
33
|
+
constructor() {
|
|
34
|
+
this.ajv = new Ajv({
|
|
35
|
+
allErrors: true,
|
|
36
|
+
verbose: true,
|
|
37
|
+
strict: false // PIE schemas may not be strict
|
|
38
|
+
});
|
|
39
|
+
this.schemas = new Map();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Register a PIE element schema
|
|
44
|
+
* @param elementType - Element type (e.g., '@pie-element/multiple-choice')
|
|
45
|
+
* @param schema - JSON Schema object
|
|
46
|
+
*/
|
|
47
|
+
registerSchema(elementType: string, schema: object): void {
|
|
48
|
+
this.schemas.set(elementType, schema);
|
|
49
|
+
this.ajv.addSchema(schema, elementType);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Load a schema from the schemas package
|
|
54
|
+
* @param elementType - Element type (e.g., '@pie-element/multiple-choice')
|
|
55
|
+
*/
|
|
56
|
+
async loadSchemaForElement(elementType: string): Promise<void> {
|
|
57
|
+
try {
|
|
58
|
+
// Extract element name from full element type
|
|
59
|
+
// e.g., '@pie-element/multiple-choice' -> 'multiple-choice'
|
|
60
|
+
const elementName = elementType.replace('@pie-element/', '') as ElementType;
|
|
61
|
+
const schema = await loadSchema(elementName);
|
|
62
|
+
this.registerSchema(elementType, schema);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
throw new Error(`Failed to load schema for ${elementType}: ${(error as Error).message}`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Load a schema from a file path (for custom schemas)
|
|
70
|
+
* @param elementType - Element type
|
|
71
|
+
* @param schemaPath - Path to pie-schema.json
|
|
72
|
+
*/
|
|
73
|
+
async loadSchemaFromFile(elementType: string, schemaPath: string): Promise<void> {
|
|
74
|
+
try {
|
|
75
|
+
const fs = await import('node:fs/promises');
|
|
76
|
+
const schemaContent = await fs.readFile(schemaPath, 'utf-8');
|
|
77
|
+
const schema = JSON.parse(schemaContent);
|
|
78
|
+
this.registerSchema(elementType, schema);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
throw new Error(`Failed to load schema from ${schemaPath}: ${(error as Error).message}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Validate a PIE item
|
|
86
|
+
* @param item - PIE item to validate
|
|
87
|
+
* @returns Validation result
|
|
88
|
+
*/
|
|
89
|
+
validate(item: PieItem): DetailedValidationResult {
|
|
90
|
+
const errors: ValidationError[] = [];
|
|
91
|
+
|
|
92
|
+
// Validate basic structure
|
|
93
|
+
if (!item.id) {
|
|
94
|
+
errors.push({ path: 'id', message: 'Item ID is required' });
|
|
95
|
+
}
|
|
96
|
+
if (!item.uuid) {
|
|
97
|
+
errors.push({ path: 'uuid', message: 'Item UUID is required' });
|
|
98
|
+
}
|
|
99
|
+
if (!item.config) {
|
|
100
|
+
errors.push({ path: 'config', message: 'Item config is required' });
|
|
101
|
+
return {
|
|
102
|
+
valid: false,
|
|
103
|
+
errors: errors.map(e => `${e.path}: ${e.message}`),
|
|
104
|
+
detailedErrors: errors
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Validate models against their schemas
|
|
109
|
+
if (item.config.models) {
|
|
110
|
+
for (let i = 0; i < item.config.models.length; i++) {
|
|
111
|
+
const model = item.config.models[i];
|
|
112
|
+
if (!model.element) {
|
|
113
|
+
errors.push({
|
|
114
|
+
path: `config.models[${i}].element`,
|
|
115
|
+
message: 'Model element type is required'
|
|
116
|
+
});
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Check if we have a schema for this element type
|
|
121
|
+
const schema = this.schemas.get(model.element);
|
|
122
|
+
if (schema) {
|
|
123
|
+
const validate = this.ajv.compile(schema);
|
|
124
|
+
const valid = validate(model);
|
|
125
|
+
|
|
126
|
+
if (!valid && validate.errors) {
|
|
127
|
+
for (const error of validate.errors) {
|
|
128
|
+
errors.push({
|
|
129
|
+
path: `config.models[${i}]${error.instancePath}`,
|
|
130
|
+
message: error.message || 'Validation error',
|
|
131
|
+
value: error.data,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
valid: errors.length === 0,
|
|
141
|
+
errors: errors.length > 0 ? errors.map(e => `${e.path}: ${e.message}`) : undefined,
|
|
142
|
+
detailedErrors: errors.length > 0 ? errors : undefined,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Validate multiple items
|
|
148
|
+
*/
|
|
149
|
+
validateMany(items: PieItem[]): DetailedValidationResult[] {
|
|
150
|
+
return items.map(item => this.validate(item));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Basic structural validation for PIE items
|
|
156
|
+
* Used when schemas are not available
|
|
157
|
+
*/
|
|
158
|
+
export function validatePieItemStructure(item: any): DetailedValidationResult {
|
|
159
|
+
const errors: ValidationError[] = [];
|
|
160
|
+
|
|
161
|
+
if (typeof item !== 'object' || item === null) {
|
|
162
|
+
errors.push({ path: '', message: 'Item must be an object' });
|
|
163
|
+
return {
|
|
164
|
+
valid: false,
|
|
165
|
+
errors: ['Item must be an object'],
|
|
166
|
+
detailedErrors: errors
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Check required fields
|
|
171
|
+
const requiredFields = ['id', 'uuid', 'config'];
|
|
172
|
+
for (const field of requiredFields) {
|
|
173
|
+
if (!(field in item)) {
|
|
174
|
+
errors.push({ path: field, message: `${field} is required` });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Check config structure
|
|
179
|
+
if (item.config) {
|
|
180
|
+
if (!Array.isArray(item.config.models)) {
|
|
181
|
+
errors.push({ path: 'config.models', message: 'config.models must be an array' });
|
|
182
|
+
}
|
|
183
|
+
if (typeof item.config.elements !== 'object') {
|
|
184
|
+
errors.push({ path: 'config.elements', message: 'config.elements must be an object' });
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return {
|
|
189
|
+
valid: errors.length === 0,
|
|
190
|
+
errors: errors.length > 0 ? errors.map(e => `${e.path}: ${e.message}`) : undefined,
|
|
191
|
+
detailedErrors: errors.length > 0 ? errors : undefined,
|
|
192
|
+
};
|
|
193
|
+
}
|