@thanh01.pmt/interactive-quiz-kit 1.0.0

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/dist/index.js ADDED
@@ -0,0 +1,2779 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
45
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+
47
+ // src/index.ts
48
+ var index_exports = {};
49
+ __export(index_exports, {
50
+ QuizEngine: () => QuizEngine,
51
+ SCORMService: () => SCORMService,
52
+ cn: () => cn,
53
+ emptyQuiz: () => emptyQuiz,
54
+ exportQuizAsSCORMZip: () => exportQuizAsSCORMZip,
55
+ generateFillInTheBlanksQuestion: () => generateFillInTheBlanksQuestion,
56
+ generateLauncherHTML: () => generateLauncherHTML,
57
+ generateMCQQuestion: () => generateMCQQuestion,
58
+ generateMRQQuestion: () => generateMRQQuestion,
59
+ generateMatchingQuestion: () => generateMatchingQuestion,
60
+ generateNumericQuestion: () => generateNumericQuestion,
61
+ generateQuestionsFromQuizPlan: () => generateQuestionsFromQuizPlan,
62
+ generateQuizPlan: () => generateQuizPlan,
63
+ generateSCORMManifest: () => generateSCORMManifest,
64
+ generateSequenceQuestion: () => generateSequenceQuestion,
65
+ generateShortAnswerQuestion: () => generateShortAnswerQuestion,
66
+ generateTrueFalseQuestion: () => generateTrueFalseQuestion,
67
+ generateUniqueId: () => generateUniqueId,
68
+ sampleQuiz: () => sampleQuiz
69
+ });
70
+ module.exports = __toCommonJS(index_exports);
71
+
72
+ // src/services/SCORMService.ts
73
+ var SCORM_TRUE = "true";
74
+ var SCORM_NO_ERROR = "0";
75
+ var CMI_CORE_LESSON_STATUS_PASSED = "passed";
76
+ var CMI_CORE_LESSON_STATUS_FAILED = "failed";
77
+ var CMI_CORE_LESSON_STATUS_COMPLETED = "completed";
78
+ var CMI_CORE_LESSON_STATUS_INCOMPLETE = "incomplete";
79
+ var CMI_CORE_LESSON_STATUS_NOT_ATTEMPTED = "not attempted";
80
+ var CMI_COMPLETION_STATUS_COMPLETED = "completed";
81
+ var CMI_COMPLETION_STATUS_INCOMPLETE = "incomplete";
82
+ var CMI_SUCCESS_STATUS_PASSED = "passed";
83
+ var CMI_SUCCESS_STATUS_FAILED = "failed";
84
+ var SCORMService = class {
85
+ constructor(settings) {
86
+ this.scormAPI = null;
87
+ this.scormVersionFound = null;
88
+ this.isInitialized = false;
89
+ this.isTerminated = false;
90
+ this.studentName = null;
91
+ this.settings = __spreadValues({
92
+ setCompletionOnFinish: true,
93
+ setSuccessOnPass: true,
94
+ autoCommit: true
95
+ }, settings);
96
+ if (typeof window !== "undefined") {
97
+ this._findAPI();
98
+ }
99
+ }
100
+ _findAPIRecursive(win) {
101
+ if (win === null) return null;
102
+ if (win.API_1484_11) {
103
+ this.scormVersionFound = "2004";
104
+ return win.API_1484_11;
105
+ }
106
+ if (win.API) {
107
+ this.scormVersionFound = "1.2";
108
+ return win.API;
109
+ }
110
+ if (win.parent && win.parent !== win) {
111
+ return this._findAPIRecursive(win.parent);
112
+ }
113
+ if (win.opener && typeof win.opener !== "undefined" && win.opener !== win && win.opener !== win.parent) {
114
+ try {
115
+ if (win.opener.document) {
116
+ return this._findAPIRecursive(win.opener);
117
+ }
118
+ } catch (e) {
119
+ console.warn("SCORMService: Could not access win.opener for API search due to cross-origin restrictions.");
120
+ }
121
+ }
122
+ return null;
123
+ }
124
+ _findAPI() {
125
+ try {
126
+ this.scormAPI = this._findAPIRecursive(window);
127
+ if (this.scormAPI) {
128
+ if (!this.scormVersionFound) this.scormVersionFound = this.settings.version;
129
+ console.log(`SCORMService: API Found. Version determined: ${this.scormVersionFound}`);
130
+ } else {
131
+ console.warn("SCORMService: SCORM API not found in window hierarchy.");
132
+ }
133
+ } catch (e) {
134
+ console.error("SCORMService: Error finding SCORM API", e);
135
+ this.scormAPI = null;
136
+ }
137
+ }
138
+ hasAPI() {
139
+ return this.scormAPI !== null;
140
+ }
141
+ getSCORMVersion() {
142
+ return this.scormVersionFound;
143
+ }
144
+ initialize() {
145
+ if (!this.hasAPI()) return { success: false, error: "SCORM API not found." };
146
+ if (this.isInitialized) return { success: true, studentName: this.studentName || void 0 };
147
+ const result = this.scormVersionFound === "2004" ? this.scormAPI.Initialize("") : this.scormAPI.LMSInitialize("");
148
+ if (result.toString() === SCORM_TRUE || result === true) {
149
+ this.isInitialized = true;
150
+ this.isTerminated = false;
151
+ const studentNameVar = this.settings.studentNameVar || (this.scormVersionFound === "2004" ? "cmi.learner_name" : "cmi.core.student_name");
152
+ this.studentName = this.getValue(studentNameVar);
153
+ if (this.scormVersionFound === "2004") {
154
+ const completionStatusVar = this.settings.completionStatusVar_2004 || this.settings.lessonStatusVar || "cmi.completion_status";
155
+ if (this.getValue(completionStatusVar) === "not attempted") {
156
+ this.setValue(completionStatusVar, CMI_COMPLETION_STATUS_INCOMPLETE);
157
+ }
158
+ } else {
159
+ const lessonStatusVar = this.settings.lessonStatusVar_1_2 || this.settings.lessonStatusVar || "cmi.core.lesson_status";
160
+ if (this.getValue(lessonStatusVar) === CMI_CORE_LESSON_STATUS_NOT_ATTEMPTED) {
161
+ this.setValue(lessonStatusVar, CMI_CORE_LESSON_STATUS_INCOMPLETE);
162
+ }
163
+ }
164
+ if (this.settings.autoCommit) this.commit();
165
+ return { success: true, studentName: this.studentName || void 0 };
166
+ } else {
167
+ const error = this.getLastError();
168
+ return { success: false, error: `Initialization failed: ${error.message}` };
169
+ }
170
+ }
171
+ terminate() {
172
+ if (!this.hasAPI() || !this.isInitialized || this.isTerminated) {
173
+ const reason = !this.hasAPI() ? "API not found" : !this.isInitialized ? "Not initialized" : "Already terminated";
174
+ return { success: !this.hasAPI() || this.isTerminated, error: this.isTerminated ? void 0 : reason };
175
+ }
176
+ const result = this.scormVersionFound === "2004" ? this.scormAPI.Terminate("") : this.scormAPI.LMSFinish("");
177
+ if (result.toString() === SCORM_TRUE || result === true) {
178
+ this.isTerminated = true;
179
+ this.isInitialized = false;
180
+ return { success: true };
181
+ } else {
182
+ const error = this.getLastError();
183
+ return { success: false, error: `Termination failed: ${error.message}` };
184
+ }
185
+ }
186
+ setValue(element, value) {
187
+ if (!this.hasAPI() || !this.isInitialized) {
188
+ return { success: false, error: !this.hasAPI() ? "SCORM API not found." : "SCORM not initialized." };
189
+ }
190
+ const valStr = value.toString();
191
+ const result = this.scormVersionFound === "2004" ? this.scormAPI.SetValue(element, valStr) : this.scormAPI.LMSSetValue(element, valStr);
192
+ if (result.toString() === SCORM_TRUE || result === true) {
193
+ if (this.settings.autoCommit) this.commit();
194
+ return { success: true };
195
+ } else {
196
+ const error = this.getLastError();
197
+ return { success: false, error: `SetValue failed for ${element}: ${error.message}` };
198
+ }
199
+ }
200
+ getValue(element) {
201
+ var _a;
202
+ if (!this.hasAPI() || !this.isInitialized) return null;
203
+ const value = this.scormVersionFound === "2004" ? this.scormAPI.GetValue(element) : this.scormAPI.LMSGetValue(element);
204
+ const error = this.getLastError();
205
+ if (error.code !== SCORM_NO_ERROR && error.code !== "403" && error.code !== "0") {
206
+ console.warn(`SCORMService: GetValue for ${element} produced an error ${error.code}: ${error.message}. Returning raw value:`, value);
207
+ }
208
+ return (_a = value == null ? void 0 : value.toString()) != null ? _a : null;
209
+ }
210
+ commit() {
211
+ if (!this.hasAPI() || !this.isInitialized) {
212
+ return { success: false, error: !this.hasAPI() ? "SCORM API not found." : "SCORM not initialized." };
213
+ }
214
+ const result = this.scormVersionFound === "2004" ? this.scormAPI.Commit("") : this.scormAPI.LMSCommit("");
215
+ if (result.toString() === SCORM_TRUE || result === true) {
216
+ return { success: true };
217
+ } else {
218
+ const error = this.getLastError();
219
+ return { success: false, error: `Commit failed: ${error.message}` };
220
+ }
221
+ }
222
+ setScore(rawScore, maxScore, minScore = 0) {
223
+ if (!this.hasAPI() || !this.isInitialized) return;
224
+ if (this.scormVersionFound === "2004") {
225
+ const scoreRawVar = this.settings.scoreRawVar_2004 || this.settings.scoreRawVar || "cmi.score.raw";
226
+ const scoreMaxVar = this.settings.scoreMaxVar_2004 || this.settings.scoreMaxVar || "cmi.score.max";
227
+ const scoreMinVar = this.settings.scoreMinVar_2004 || this.settings.scoreMinVar || "cmi.score.min";
228
+ const scoreScaledVar = this.settings.scoreScaledVar_2004 || "cmi.score.scaled";
229
+ this.setValue(scoreMinVar, minScore);
230
+ this.setValue(scoreMaxVar, maxScore);
231
+ this.setValue(scoreRawVar, rawScore);
232
+ if (maxScore > minScore) {
233
+ const scaledScore = (rawScore - minScore) / (maxScore - minScore);
234
+ this.setValue(scoreScaledVar, parseFloat(scaledScore.toFixed(4)));
235
+ } else if (maxScore === minScore && maxScore !== 0) {
236
+ this.setValue(scoreScaledVar, rawScore >= maxScore ? 1 : 0);
237
+ } else {
238
+ this.setValue(scoreScaledVar, 0);
239
+ }
240
+ } else {
241
+ const scoreRawVar = this.settings.scoreRawVar_1_2 || this.settings.scoreRawVar || "cmi.core.score.raw";
242
+ const scoreMaxVar = this.settings.scoreMaxVar_1_2 || this.settings.scoreMaxVar || "cmi.core.score.max";
243
+ const scoreMinVar = this.settings.scoreMinVar_1_2 || this.settings.scoreMinVar || "cmi.core.score.min";
244
+ this.setValue(scoreMinVar, minScore);
245
+ this.setValue(scoreMaxVar, maxScore);
246
+ this.setValue(scoreRawVar, rawScore);
247
+ }
248
+ }
249
+ setLessonStatus(status, passed) {
250
+ if (!this.hasAPI() || !this.isInitialized) return;
251
+ if (this.scormVersionFound === "2004") {
252
+ const completionStatusVar = this.settings.completionStatusVar_2004 || this.settings.lessonStatusVar || "cmi.completion_status";
253
+ const successStatusVar = this.settings.successStatusVar_2004 || "cmi.success_status";
254
+ if (this.settings.setCompletionOnFinish && (status === "completed" || status === "passed" || status === "failed")) {
255
+ this.setValue(completionStatusVar, CMI_COMPLETION_STATUS_COMPLETED);
256
+ } else if (status === "incomplete" || status === "browsed") {
257
+ this.setValue(completionStatusVar, CMI_COMPLETION_STATUS_INCOMPLETE);
258
+ }
259
+ if (this.settings.setSuccessOnPass && passed !== void 0) {
260
+ this.setValue(successStatusVar, passed ? CMI_SUCCESS_STATUS_PASSED : CMI_SUCCESS_STATUS_FAILED);
261
+ }
262
+ } else {
263
+ const lessonStatusVar = this.settings.lessonStatusVar_1_2 || this.settings.lessonStatusVar || "cmi.core.lesson_status";
264
+ let finalStatus = status;
265
+ if (this.settings.setCompletionOnFinish) {
266
+ if (this.settings.setSuccessOnPass && passed !== void 0) {
267
+ finalStatus = passed ? CMI_CORE_LESSON_STATUS_PASSED : CMI_CORE_LESSON_STATUS_FAILED;
268
+ } else {
269
+ finalStatus = CMI_CORE_LESSON_STATUS_COMPLETED;
270
+ }
271
+ } else {
272
+ if (status === CMI_CORE_LESSON_STATUS_PASSED || status === CMI_CORE_LESSON_STATUS_FAILED) {
273
+ } else {
274
+ finalStatus = CMI_CORE_LESSON_STATUS_INCOMPLETE;
275
+ }
276
+ }
277
+ this.setValue(lessonStatusVar, finalStatus);
278
+ }
279
+ }
280
+ getLastError() {
281
+ var _a, _b;
282
+ if (!this.hasAPI()) return { code: "-1", message: "SCORM API not found." };
283
+ const errorCode = this.scormVersionFound === "2004" ? this.scormAPI.GetLastError() : this.scormAPI.LMSGetLastError();
284
+ if (errorCode === SCORM_NO_ERROR || errorCode === 0 || errorCode === "0") {
285
+ return { code: SCORM_NO_ERROR, message: "No error." };
286
+ }
287
+ const errorMessage = this.scormVersionFound === "2004" ? this.scormAPI.GetErrorString(errorCode.toString()) : this.scormAPI.LMSGetErrorString(errorCode.toString());
288
+ const diagnostic = this.scormVersionFound === "2004" ? this.scormAPI.GetDiagnostic(errorCode.toString()) : this.scormAPI.LMSGetDiagnostic(errorCode.toString());
289
+ return {
290
+ code: errorCode.toString(),
291
+ message: (_a = errorMessage == null ? void 0 : errorMessage.toString()) != null ? _a : "Unknown error.",
292
+ diagnostic: (_b = diagnostic == null ? void 0 : diagnostic.toString()) != null ? _b : void 0
293
+ };
294
+ }
295
+ formatCMITime(totalSeconds) {
296
+ const pad = (num, size = 2) => num.toString().padStart(size, "0");
297
+ if (this.scormVersionFound === "2004") {
298
+ const hours = Math.floor(totalSeconds / 3600);
299
+ const minutes = Math.floor(totalSeconds % 3600 / 60);
300
+ const seconds = parseFloat((totalSeconds % 60).toFixed(2));
301
+ let timeString = "PT";
302
+ if (hours > 0) timeString += `${hours}H`;
303
+ if (minutes > 0 || hours > 0 && seconds > 0) {
304
+ timeString += `${minutes}M`;
305
+ }
306
+ if (seconds > 0 || timeString === "PT") {
307
+ timeString += `${seconds}S`;
308
+ }
309
+ return timeString === "PT" ? "PT0S" : timeString;
310
+ } else {
311
+ const hours = Math.floor(totalSeconds / 3600);
312
+ const minutes = Math.floor(totalSeconds % 3600 / 60);
313
+ const secondsOnly = Math.floor(totalSeconds % 60);
314
+ const centiseconds = Math.floor((totalSeconds - Math.floor(totalSeconds)) * 100);
315
+ return `${pad(hours, 4)}:${pad(minutes)}:${pad(secondsOnly)}.${pad(centiseconds)}`;
316
+ }
317
+ }
318
+ };
319
+
320
+ // src/services/QuizEngine.ts
321
+ var QuizEngine = class {
322
+ // Stores time in seconds
323
+ constructor(options) {
324
+ this.userAnswers = /* @__PURE__ */ new Map();
325
+ this.currentQuestionIndex = 0;
326
+ this.timerId = null;
327
+ this.timeLeftInSeconds = null;
328
+ this.scormService = null;
329
+ this.quizResultState = { scormStatus: "idle" };
330
+ this.questionStartTime = null;
331
+ this.questionTimings = /* @__PURE__ */ new Map();
332
+ var _a, _b, _c, _d, _e;
333
+ this.config = options.config;
334
+ this.callbacks = options.callbacks || {};
335
+ this.questions = ((_a = this.config.settings) == null ? void 0 : _a.shuffleQuestions) ? [...this.config.questions].sort(() => Math.random() - 0.5) : this.config.questions;
336
+ this.overallStartTime = Date.now();
337
+ if (((_b = this.config.settings) == null ? void 0 : _b.timeLimitMinutes) && this.config.settings.timeLimitMinutes > 0) {
338
+ this.timeLeftInSeconds = this.config.settings.timeLimitMinutes * 60;
339
+ }
340
+ if ((_c = this.config.settings) == null ? void 0 : _c.scorm) {
341
+ this.quizResultState.scormStatus = "initializing";
342
+ this.scormService = new SCORMService(this.config.settings.scorm);
343
+ if (this.scormService.hasAPI()) {
344
+ const initResult = this.scormService.initialize();
345
+ if (initResult.success) {
346
+ this.quizResultState.scormStatus = "initialized";
347
+ this.quizResultState.studentName = initResult.studentName;
348
+ } else {
349
+ this.quizResultState.scormStatus = "error";
350
+ this.quizResultState.scormError = initResult.error || "SCORM initialization failed.";
351
+ }
352
+ } else {
353
+ this.quizResultState.scormStatus = "no_api";
354
+ }
355
+ }
356
+ const initialQ = this.getCurrentQuestion();
357
+ if (initialQ) {
358
+ this.questionStartTime = Date.now();
359
+ }
360
+ if (this.callbacks.onQuizStart) {
361
+ this.callbacks.onQuizStart({
362
+ initialQuestion: initialQ,
363
+ currentQuestionNumber: this.getCurrentQuestionNumber(),
364
+ totalQuestions: this.getTotalQuestions(),
365
+ timeLimitInSeconds: this.timeLeftInSeconds,
366
+ scormStatus: this.quizResultState.scormStatus,
367
+ studentName: this.quizResultState.studentName
368
+ });
369
+ }
370
+ if (this.timeLeftInSeconds !== null) {
371
+ this.startTimer();
372
+ }
373
+ (_e = (_d = this.callbacks).onQuestionChange) == null ? void 0 : _e.call(_d, initialQ, this.getCurrentQuestionNumber(), this.getTotalQuestions());
374
+ }
375
+ _recordCurrentQuestionTime() {
376
+ if (this.questionStartTime && this.currentQuestionIndex >= 0 && this.currentQuestionIndex < this.questions.length) {
377
+ const currentQId = this.questions[this.currentQuestionIndex].id;
378
+ const elapsedMs = Date.now() - this.questionStartTime;
379
+ const currentTotalTime = this.questionTimings.get(currentQId) || 0;
380
+ this.questionTimings.set(currentQId, currentTotalTime + elapsedMs / 1e3);
381
+ }
382
+ this.questionStartTime = null;
383
+ }
384
+ startTimer() {
385
+ if (this.timerId !== null) {
386
+ clearInterval(this.timerId);
387
+ }
388
+ this.timerId = setInterval(() => this.handleTick(), 1e3);
389
+ }
390
+ stopTimer() {
391
+ if (this.timerId !== null) {
392
+ clearInterval(this.timerId);
393
+ this.timerId = null;
394
+ }
395
+ }
396
+ handleTick() {
397
+ var _a, _b, _c, _d;
398
+ if (this.timeLeftInSeconds === null) return;
399
+ if (this.timeLeftInSeconds > 0) {
400
+ this.timeLeftInSeconds--;
401
+ (_b = (_a = this.callbacks).onTimeTick) == null ? void 0 : _b.call(_a, this.timeLeftInSeconds);
402
+ }
403
+ if (this.timeLeftInSeconds <= 0) {
404
+ this.stopTimer();
405
+ (_d = (_c = this.callbacks).onQuizTimeUp) == null ? void 0 : _d.call(_c);
406
+ this.calculateResults().then((results) => {
407
+ });
408
+ }
409
+ }
410
+ getTimeLeftInSeconds() {
411
+ return this.timeLeftInSeconds;
412
+ }
413
+ getCurrentQuestion() {
414
+ return this.questions[this.currentQuestionIndex] || null;
415
+ }
416
+ getCurrentQuestionNumber() {
417
+ return this.currentQuestionIndex + 1;
418
+ }
419
+ getTotalQuestions() {
420
+ return this.questions.length;
421
+ }
422
+ submitAnswer(questionId, answer) {
423
+ var _a, _b;
424
+ this.userAnswers.set(questionId, answer);
425
+ const question = this.questions.find((q) => q.id === questionId);
426
+ if (question) {
427
+ (_b = (_a = this.callbacks).onAnswerSubmit) == null ? void 0 : _b.call(_a, question, answer);
428
+ } else {
429
+ console.warn(`QuizEngine: Question with id ${questionId} not found for onAnswerSubmit.`);
430
+ }
431
+ }
432
+ getUserAnswer(questionId) {
433
+ return this.userAnswers.get(questionId);
434
+ }
435
+ nextQuestion() {
436
+ var _a, _b;
437
+ this._recordCurrentQuestionTime();
438
+ if (this.currentQuestionIndex < this.questions.length - 1) {
439
+ this.currentQuestionIndex++;
440
+ const currentQ = this.getCurrentQuestion();
441
+ this.questionStartTime = Date.now();
442
+ (_b = (_a = this.callbacks).onQuestionChange) == null ? void 0 : _b.call(_a, currentQ, this.getCurrentQuestionNumber(), this.getTotalQuestions());
443
+ return currentQ;
444
+ }
445
+ return null;
446
+ }
447
+ previousQuestion() {
448
+ var _a, _b;
449
+ this._recordCurrentQuestionTime();
450
+ if (this.currentQuestionIndex > 0) {
451
+ this.currentQuestionIndex--;
452
+ const currentQ = this.getCurrentQuestion();
453
+ this.questionStartTime = Date.now();
454
+ (_b = (_a = this.callbacks).onQuestionChange) == null ? void 0 : _b.call(_a, currentQ, this.getCurrentQuestionNumber(), this.getTotalQuestions());
455
+ return currentQ;
456
+ }
457
+ return null;
458
+ }
459
+ goToQuestion(index) {
460
+ var _a, _b;
461
+ if (index >= 0 && index < this.questions.length && index !== this.currentQuestionIndex) {
462
+ this._recordCurrentQuestionTime();
463
+ this.currentQuestionIndex = index;
464
+ const currentQ = this.getCurrentQuestion();
465
+ this.questionStartTime = Date.now();
466
+ (_b = (_a = this.callbacks).onQuestionChange) == null ? void 0 : _b.call(_a, currentQ, this.getCurrentQuestionNumber(), this.getTotalQuestions());
467
+ return currentQ;
468
+ }
469
+ return this.getCurrentQuestion();
470
+ }
471
+ isQuizFinished() {
472
+ return this.quizResultState.score !== void 0;
473
+ }
474
+ async _sendResultsToWebhook(results) {
475
+ var _a;
476
+ if (!((_a = this.config.settings) == null ? void 0 : _a.webhookUrl)) {
477
+ results.webhookStatus = "idle";
478
+ return;
479
+ }
480
+ results.webhookStatus = "sending";
481
+ try {
482
+ const response = await fetch(this.config.settings.webhookUrl, {
483
+ method: "POST",
484
+ headers: { "Content-Type": "application/json" },
485
+ body: JSON.stringify(results)
486
+ });
487
+ if (response.ok) {
488
+ results.webhookStatus = "success";
489
+ } else {
490
+ results.webhookStatus = "error";
491
+ results.webhookError = `Webhook returned status: ${response.status} ${response.statusText}`;
492
+ try {
493
+ const errorBody = await response.text();
494
+ results.webhookError += ` - Body: ${errorBody.substring(0, 200)}`;
495
+ } catch (e) {
496
+ }
497
+ }
498
+ } catch (error) {
499
+ results.webhookStatus = "error";
500
+ results.webhookError = error instanceof Error ? `Fetch error: ${error.message}` : "Unknown webhook error.";
501
+ }
502
+ }
503
+ _sendResultsToSCORM(results) {
504
+ var _a, _b, _c, _d, _e, _f, _g;
505
+ if (!this.scormService || !this.scormService.hasAPI() || this.quizResultState.scormStatus === "no_api") {
506
+ results.scormStatus = this.quizResultState.scormStatus || "idle";
507
+ return;
508
+ }
509
+ if (this.quizResultState.scormStatus === "error" && ((_a = this.quizResultState.scormError) == null ? void 0 : _a.includes("initialization failed"))) {
510
+ results.scormStatus = "error";
511
+ results.scormError = this.quizResultState.scormError;
512
+ return;
513
+ }
514
+ results.scormStatus = "sending_data";
515
+ try {
516
+ this.scormService.setScore(results.score, results.maxScore, 0);
517
+ let lessonStatusSetting = "completed";
518
+ if (((_b = this.config.settings) == null ? void 0 : _b.passingScorePercent) !== void 0 && ((_c = this.config.settings) == null ? void 0 : _c.passingScorePercent) !== null) {
519
+ lessonStatusSetting = results.passed ? "passed" : "failed";
520
+ } else if ((_e = (_d = this.config.settings) == null ? void 0 : _d.scorm) == null ? void 0 : _e.setCompletionOnFinish) {
521
+ lessonStatusSetting = "completed";
522
+ }
523
+ this.scormService.setLessonStatus(lessonStatusSetting, results.passed);
524
+ if (results.totalTimeSpentSeconds !== void 0 && this.scormService.formatCMITime) {
525
+ const cmiTime = this.scormService.formatCMITime(results.totalTimeSpentSeconds);
526
+ const sessionTimeVar = ((_g = (_f = this.config.settings) == null ? void 0 : _f.scorm) == null ? void 0 : _g.sessionTimeVar) || (this.scormService.getSCORMVersion() === "2004" ? "cmi.session_time" : "cmi.core.session_time");
527
+ if (sessionTimeVar) this.scormService.setValue(sessionTimeVar, cmiTime);
528
+ }
529
+ const commitResult = this.scormService.commit();
530
+ if (commitResult.success) {
531
+ results.scormStatus = "committed";
532
+ } else {
533
+ results.scormStatus = "error";
534
+ results.scormError = commitResult.error || "SCORM commit failed.";
535
+ }
536
+ } catch (e) {
537
+ results.scormStatus = "error";
538
+ results.scormError = e instanceof Error ? e.message : "Unknown SCORM data sending error.";
539
+ }
540
+ }
541
+ _calculateMetadataPerformance() {
542
+ const loPerformanceMap = /* @__PURE__ */ new Map();
543
+ const categoryPerformanceMap = /* @__PURE__ */ new Map();
544
+ const topicPerformanceMap = /* @__PURE__ */ new Map();
545
+ const difficultyPerformanceMap = /* @__PURE__ */ new Map();
546
+ const bloomLevelPerformanceMap = /* @__PURE__ */ new Map();
547
+ const updateMap = (map, key, points, isCorrect) => {
548
+ if (key === void 0 || key === null || key.trim() === "") return;
549
+ const current = map.get(key) || { totalQuestions: 0, correctQuestions: 0, pointsEarned: 0, maxPoints: 0 };
550
+ current.totalQuestions++;
551
+ current.maxPoints += points;
552
+ if (isCorrect) {
553
+ current.correctQuestions++;
554
+ current.pointsEarned += points;
555
+ }
556
+ map.set(key, current);
557
+ };
558
+ this.questions.forEach((q) => {
559
+ const qResult = this.userAnswers.get(q.id);
560
+ const { isCorrect } = this.evaluateQuestion(q, qResult || null);
561
+ const pointsForThisQuestion = q.points !== void 0 ? q.points : 0;
562
+ updateMap(loPerformanceMap, q.learningObjective, pointsForThisQuestion, isCorrect);
563
+ updateMap(categoryPerformanceMap, q.category, pointsForThisQuestion, isCorrect);
564
+ updateMap(topicPerformanceMap, q.topic, pointsForThisQuestion, isCorrect);
565
+ updateMap(difficultyPerformanceMap, q.difficulty, pointsForThisQuestion, isCorrect);
566
+ updateMap(bloomLevelPerformanceMap, q.bloomLevel, pointsForThisQuestion, isCorrect);
567
+ });
568
+ const formatPerformanceArray = (map, keyName) => {
569
+ return Array.from(map.entries()).map(([key, data]) => ({
570
+ [keyName]: key,
571
+ totalQuestions: data.totalQuestions,
572
+ correctQuestions: data.correctQuestions,
573
+ pointsEarned: data.pointsEarned,
574
+ maxPoints: data.maxPoints,
575
+ percentage: data.maxPoints > 0 ? parseFloat((data.pointsEarned / data.maxPoints * 100).toFixed(2)) : 0
576
+ }));
577
+ };
578
+ return {
579
+ performanceByLearningObjective: formatPerformanceArray(loPerformanceMap, "learningObjective"),
580
+ performanceByCategory: formatPerformanceArray(categoryPerformanceMap, "category"),
581
+ performanceByTopic: formatPerformanceArray(topicPerformanceMap, "topic"),
582
+ performanceByDifficulty: formatPerformanceArray(difficultyPerformanceMap, "difficulty"),
583
+ performanceByBloomLevel: formatPerformanceArray(bloomLevelPerformanceMap, "bloomLevel")
584
+ };
585
+ }
586
+ async calculateResults() {
587
+ var _a, _b, _c, _d;
588
+ this.stopTimer();
589
+ this._recordCurrentQuestionTime();
590
+ let totalScore = 0;
591
+ let maxScore = 0;
592
+ const questionResultsArray = [];
593
+ let accumulatedTotalTimeSpent = 0;
594
+ for (const question of this.questions) {
595
+ const userAnswer = this.userAnswers.get(question.id) || null;
596
+ const questionPoints = question.points !== void 0 ? question.points : 0;
597
+ maxScore += questionPoints;
598
+ const { isCorrect, correctAnswer, pointsEarned } = this.evaluateQuestion(question, userAnswer);
599
+ totalScore += pointsEarned;
600
+ const timeSpentOnThisQuestion = parseFloat((this.questionTimings.get(question.id) || 0).toFixed(2));
601
+ accumulatedTotalTimeSpent += timeSpentOnThisQuestion;
602
+ questionResultsArray.push({
603
+ questionId: question.id,
604
+ isCorrect,
605
+ pointsEarned,
606
+ userAnswer,
607
+ correctAnswer,
608
+ timeSpentSeconds: timeSpentOnThisQuestion
609
+ });
610
+ }
611
+ const percentage = maxScore > 0 ? parseFloat((totalScore / maxScore * 100).toFixed(2)) : 0;
612
+ let passed = void 0;
613
+ if (((_a = this.config.settings) == null ? void 0 : _a.passingScorePercent) !== void 0 && this.config.settings.passingScorePercent !== null) {
614
+ passed = percentage >= this.config.settings.passingScorePercent;
615
+ }
616
+ const totalQuizTimeSpentSeconds = parseFloat(accumulatedTotalTimeSpent.toFixed(2));
617
+ const averageTimePerQuestionSeconds = this.questions.length > 0 ? parseFloat((totalQuizTimeSpentSeconds / this.questions.length).toFixed(2)) : 0;
618
+ const metadataPerformance = this._calculateMetadataPerformance();
619
+ const finalResults = __spreadValues({
620
+ score: totalScore,
621
+ maxScore,
622
+ percentage,
623
+ answers: this.userAnswers,
624
+ questionResults: questionResultsArray,
625
+ passed,
626
+ webhookStatus: "idle",
627
+ scormStatus: this.quizResultState.scormStatus || "idle",
628
+ scormError: this.quizResultState.scormError,
629
+ studentName: this.quizResultState.studentName,
630
+ totalTimeSpentSeconds: totalQuizTimeSpentSeconds,
631
+ averageTimePerQuestionSeconds
632
+ }, metadataPerformance);
633
+ this.quizResultState = __spreadValues(__spreadValues({}, this.quizResultState), finalResults);
634
+ if ((_b = this.config.settings) == null ? void 0 : _b.scorm) {
635
+ this._sendResultsToSCORM(finalResults);
636
+ }
637
+ await this._sendResultsToWebhook(finalResults);
638
+ (_d = (_c = this.callbacks).onQuizFinish) == null ? void 0 : _d.call(_c, finalResults);
639
+ return finalResults;
640
+ }
641
+ evaluateQuestion(question, answer) {
642
+ let isCorrect = false;
643
+ let correctAnswerValue = null;
644
+ const points = question.points !== void 0 ? question.points : 0;
645
+ switch (question.questionType) {
646
+ case "multiple_choice":
647
+ correctAnswerValue = question.correctAnswerId;
648
+ isCorrect = answer === correctAnswerValue;
649
+ break;
650
+ case "multiple_response":
651
+ const mrq = question;
652
+ correctAnswerValue = mrq.correctAnswerIds;
653
+ if (Array.isArray(answer) && Array.isArray(correctAnswerValue)) {
654
+ const userAnswerSet = new Set(answer);
655
+ const correctAnswerSet = new Set(correctAnswerValue);
656
+ isCorrect = userAnswerSet.size === correctAnswerSet.size && [...userAnswerSet].every((id) => correctAnswerSet.has(id));
657
+ }
658
+ break;
659
+ case "fill_in_the_blanks":
660
+ const fitbq = question;
661
+ correctAnswerValue = {};
662
+ fitbq.answers.forEach((ans) => {
663
+ correctAnswerValue[ans.blankId] = ans.acceptedValues;
664
+ });
665
+ if (typeof answer === "object" && answer !== null && !Array.isArray(answer)) {
666
+ const userAnswerMap = answer;
667
+ isCorrect = fitbq.answers.every((correctAnsDef) => {
668
+ var _a;
669
+ const userValForBlank = (_a = userAnswerMap[correctAnsDef.blankId]) == null ? void 0 : _a.trim();
670
+ const acceptedValsForBlank = correctAnsDef.acceptedValues.map((v) => v.trim());
671
+ const caseSensitive = fitbq.isCaseSensitive === void 0 ? false : fitbq.isCaseSensitive;
672
+ if (userValForBlank === void 0) return false;
673
+ return caseSensitive ? acceptedValsForBlank.some((accVal) => accVal === userValForBlank) : acceptedValsForBlank.some((accVal) => accVal.toLowerCase() === userValForBlank.toLowerCase());
674
+ });
675
+ }
676
+ break;
677
+ case "drag_and_drop":
678
+ const dndq = question;
679
+ correctAnswerValue = {};
680
+ dndq.answerMap.forEach((map) => {
681
+ correctAnswerValue[map.draggableId] = map.dropZoneId;
682
+ });
683
+ if (typeof answer === "object" && answer !== null && !Array.isArray(answer)) {
684
+ const userAnswerMap = answer;
685
+ const correctPairsCount = dndq.answerMap.length;
686
+ isCorrect = dndq.answerMap.every((map) => userAnswerMap[map.draggableId] === map.dropZoneId) && Object.keys(userAnswerMap).length === correctPairsCount;
687
+ }
688
+ break;
689
+ case "true_false":
690
+ const tfq = question;
691
+ correctAnswerValue = tfq.correctAnswer;
692
+ let tfAnswer = answer;
693
+ if (typeof answer === "string") tfAnswer = answer.toLowerCase() === "true";
694
+ if (typeof tfAnswer === "boolean") isCorrect = tfAnswer === tfq.correctAnswer;
695
+ break;
696
+ case "short_answer":
697
+ const saq = question;
698
+ correctAnswerValue = saq.acceptedAnswers;
699
+ if (typeof answer === "string") {
700
+ const userAnswerTrimmed = answer.trim();
701
+ const caseSensitive = saq.isCaseSensitive === void 0 ? false : saq.isCaseSensitive;
702
+ isCorrect = saq.acceptedAnswers.some((accAns) => caseSensitive ? accAns.trim() === userAnswerTrimmed : accAns.trim().toLowerCase() === userAnswerTrimmed.toLowerCase());
703
+ }
704
+ break;
705
+ case "numeric":
706
+ const nq = question;
707
+ correctAnswerValue = { answer: nq.answer, tolerance: nq.tolerance };
708
+ if (typeof answer === "string" || typeof answer === "number") {
709
+ const userAnswerNum = parseFloat(String(answer));
710
+ if (!isNaN(userAnswerNum)) {
711
+ isCorrect = nq.tolerance !== void 0 && nq.tolerance !== null ? Math.abs(userAnswerNum - nq.answer) <= nq.tolerance : userAnswerNum === nq.answer;
712
+ }
713
+ }
714
+ break;
715
+ case "sequence":
716
+ const seqQ = question;
717
+ correctAnswerValue = seqQ.correctOrder;
718
+ if (Array.isArray(answer) && Array.isArray(seqQ.correctOrder) && answer.length === seqQ.correctOrder.length) {
719
+ isCorrect = answer.every((itemId, index) => itemId === seqQ.correctOrder[index]);
720
+ }
721
+ break;
722
+ case "matching":
723
+ const matQ = question;
724
+ correctAnswerValue = matQ.correctAnswerMap.reduce((acc, curr) => {
725
+ acc[curr.promptId] = curr.optionId;
726
+ return acc;
727
+ }, {});
728
+ if (typeof answer === "object" && answer !== null && !Array.isArray(answer)) {
729
+ const userAnswerMap = answer;
730
+ const correctMapPairsCount = matQ.correctAnswerMap.length;
731
+ isCorrect = matQ.correctAnswerMap.every((map) => userAnswerMap[map.promptId] === map.optionId) && Object.keys(userAnswerMap).length === correctMapPairsCount;
732
+ }
733
+ break;
734
+ case "hotspot":
735
+ const hsQ = question;
736
+ correctAnswerValue = hsQ.correctHotspotIds;
737
+ if (typeof answer === "string") {
738
+ isCorrect = hsQ.correctHotspotIds.includes(answer);
739
+ } else if (Array.isArray(answer)) {
740
+ const userAnswerSet = new Set(answer);
741
+ const correctAnswerSet = new Set(hsQ.correctHotspotIds);
742
+ isCorrect = userAnswerSet.size === correctAnswerSet.size && [...userAnswerSet].every((id) => correctAnswerSet.has(id));
743
+ }
744
+ break;
745
+ case "blockly_programming":
746
+ case "scratch_programming":
747
+ const progQ = question;
748
+ correctAnswerValue = progQ.solutionGeneratedCode;
749
+ if (typeof answer === "string" && typeof correctAnswerValue === "string") {
750
+ if (typeof window !== "undefined" && window.Blockly) {
751
+ const LocalBlockly = window.Blockly;
752
+ let generatedUserCode = "";
753
+ try {
754
+ const tempWorkspace = new LocalBlockly.Workspace();
755
+ const dom = LocalBlockly.Xml.textToDom(answer);
756
+ LocalBlockly.Xml.domToWorkspace(dom, tempWorkspace);
757
+ generatedUserCode = LocalBlockly.JavaScript.workspaceToCode(tempWorkspace) || "";
758
+ generatedUserCode = generatedUserCode.split("\\n").map((line) => line.trim()).filter((line) => line.length > 0).join("\\n");
759
+ tempWorkspace.dispose();
760
+ } catch (e) {
761
+ console.error(`Error generating code from user's ${progQ.questionType} XML for evaluation:`, e);
762
+ generatedUserCode = `Error generating code: ${e}`;
763
+ }
764
+ isCorrect = generatedUserCode === correctAnswerValue;
765
+ } else {
766
+ console.warn(`Blockly library not available in QuizEngine for ${progQ.questionType} code generation during evaluation. XML will be stored, but code comparison skipped.`);
767
+ isCorrect = false;
768
+ }
769
+ } else {
770
+ isCorrect = false;
771
+ }
772
+ break;
773
+ default:
774
+ const _exhaustiveCheck = question;
775
+ console.warn("Unsupported question type in QuizEngine evaluation:", _exhaustiveCheck);
776
+ isCorrect = false;
777
+ }
778
+ return { isCorrect, correctAnswer: correctAnswerValue, pointsEarned: isCorrect ? points : 0 };
779
+ }
780
+ getElapsedTime() {
781
+ return Date.now() - this.overallStartTime;
782
+ }
783
+ destroy() {
784
+ this.stopTimer();
785
+ this._recordCurrentQuestionTime();
786
+ if (this.scormService && this.scormService.hasAPI()) {
787
+ if (this.quizResultState.scormStatus === "initialized" || this.quizResultState.scormStatus === "committed" || this.quizResultState.scormStatus === "sending_data") {
788
+ const termResult = this.scormService.terminate();
789
+ if (termResult.success) {
790
+ this.quizResultState.scormStatus = "terminated";
791
+ } else {
792
+ this.quizResultState.scormStatus = "error";
793
+ this.quizResultState.scormError = termResult.error || "SCORM termination failed on destroy.";
794
+ }
795
+ }
796
+ }
797
+ this.scormService = null;
798
+ }
799
+ };
800
+
801
+ // src/services/HTMLLauncherGenerator.ts
802
+ var escapeAttribute = (unsafe) => {
803
+ if (typeof unsafe !== "string") return "";
804
+ return unsafe.replace(/"/g, "&quot;");
805
+ };
806
+ var generateLauncherHTML = (quizConfig, libraryJSPath = "lib/interactive-quiz-kit.esm.js", quizDataPath = "quiz_data.json", blocklyCSSPath = "blockly-styles.css", title) => {
807
+ const pageTitle = escapeAttribute(title || quizConfig.title || "Interactive Quiz");
808
+ const relLibraryJSPath = libraryJSPath.startsWith("./") ? libraryJSPath : `./${libraryJSPath}`;
809
+ const relQuizDataPath = quizDataPath.startsWith("./") ? quizDataPath : `./${quizDataPath}`;
810
+ const relBlocklyCSSPath = blocklyCSSPath.startsWith("./") ? blocklyCSSPath : `./${blocklyCSSPath}`;
811
+ return `<!DOCTYPE html>
812
+ <html lang="en">
813
+ <head>
814
+ <meta charset="UTF-8">
815
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
816
+ <title>${pageTitle}</title>
817
+ <style>
818
+ body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; background-color: #f0f2f5; color: #1f2937; display: flex; justify-content: center; align-items: flex-start; min-height: 100vh; padding-top: 20px; box-sizing: border-box; }
819
+ #root { width: 100%; max-width: 900px; background-color: #ffffff; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); padding: 20px; }
820
+ .loading-spinner {
821
+ border: 4px solid #e5e7eb; border-top: 4px solid #3b82f6;
822
+ border-radius: 50%; width: 40px; height: 40px;
823
+ animation: spin 1s linear infinite;
824
+ margin: 60px auto 20px auto;
825
+ }
826
+ @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
827
+ .status-message { text-align: center; padding: 20px; margin-top: 10px; color: #4b5563; }
828
+ /* Basic button styling for exit (if QuizPlayer doesn't provide one post-completion) */
829
+ .exit-button { display: block; margin: 20px auto; padding: 10px 20px; background-color: #3b82f6; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
830
+ .exit-button:hover { background-color: #2563eb; }
831
+ </style>
832
+ <link rel="stylesheet" href="${escapeAttribute(relBlocklyCSSPath)}">
833
+ <script type="importmap">
834
+ {
835
+ "imports": {
836
+ "react": "https://esm.sh/react@18.3.1",
837
+ "react-dom/client": "https://esm.sh/react-dom@18.3.1/client"
838
+ }
839
+ }
840
+ </script>
841
+ </head>
842
+ <body>
843
+ <div id="root">
844
+ <div class="loading-spinner" aria-label="Loading quiz content"></div>
845
+ <p class="status-message" role="status">Loading Quiz...</p>
846
+ </div>
847
+
848
+ <script type="module">
849
+ import React from 'react';
850
+ import ReactDOM from 'react-dom/client';
851
+ // The library path must be relative to this HTML file within the SCORM package
852
+ import { QuizPlayer } from '${escapeAttribute(relLibraryJSPath)}';
853
+
854
+ async function loadQuizData() {
855
+ try {
856
+ // quizDataPath is relative to this HTML file
857
+ const response = await fetch('${escapeAttribute(relQuizDataPath)}');
858
+ if (!response.ok) {
859
+ throw new Error('Failed to load quiz data: Status ' + response.status + ' - ' + response.statusText + '. Ensure quiz_data.json is in the same directory as the launcher HTML or the path is correct.');
860
+ }
861
+ return await response.json();
862
+ } catch (error) {
863
+ console.error("Error loading quiz data:", error);
864
+ showStatusMessage('Error: Could not load quiz configuration. ' + error.message, true);
865
+ return null;
866
+ }
867
+ }
868
+
869
+ function showStatusMessage(message, isError = false) {
870
+ const rootEl = document.getElementById('root');
871
+ if (rootEl) {
872
+ rootEl.innerHTML = ''; // Clear previous content (like spinner)
873
+ const messageEl = document.createElement('p');
874
+ messageEl.textContent = message;
875
+ messageEl.className = 'status-message';
876
+ if(isError) {
877
+ messageEl.style.color = '#ef4444'; // Red for errors
878
+ messageEl.setAttribute('role', 'alert');
879
+ } else {
880
+ messageEl.setAttribute('role', 'status');
881
+ }
882
+ rootEl.appendChild(messageEl);
883
+ }
884
+ }
885
+
886
+ function showCompletionScreen(message) {
887
+ const rootEl = document.getElementById('root');
888
+ if (rootEl) {
889
+ rootEl.innerHTML = ''; // Clear quiz player
890
+ const messageEl = document.createElement('p');
891
+ messageEl.textContent = message;
892
+ messageEl.className = 'status-message';
893
+ rootEl.appendChild(messageEl);
894
+
895
+ // Optional: Add a manual close button if LMS doesn't handle it or for testing
896
+ // const closeButton = document.createElement('button');
897
+ // closeButton.textContent = 'Close Quiz';
898
+ // closeButton.className = 'exit-button';
899
+ // closeButton.onclick = () => {
900
+ // try { window.close(); } catch(e) { console.warn("Could not close window programmatically."); }
901
+ // // SCORM termination should have happened in QuizPlayer/QuizEngine
902
+ // };
903
+ // rootEl.appendChild(closeButton);
904
+ }
905
+ }
906
+
907
+ async function main() {
908
+ const quizConfigData = await loadQuizData();
909
+ if (!quizConfigData) {
910
+ return; // Error message already shown by loadQuizData
911
+ }
912
+
913
+ // Check if QuizPlayer is available
914
+ if (typeof QuizPlayer !== 'function') {
915
+ showStatusMessage('Error: QuizPlayer component not found. Check library bundle.', true);
916
+ return;
917
+ }
918
+
919
+ const App = () => {
920
+ const handleQuizComplete = (result) => {
921
+ console.log("Quiz Complete (SCORM Launcher):", result);
922
+ let completionMessage = 'Quiz completed. ';
923
+ if (result.passed !== undefined) {
924
+ completionMessage += result.passed ? 'You passed!' : 'You did not pass.';
925
+ }
926
+ completionMessage += ' You may now close this window, or your Learning Management System will manage navigation.';
927
+ showCompletionScreen(completionMessage);
928
+ // SCORM termination logic should be handled by QuizEngine/QuizPlayer via SCORMService.destroy()
929
+ };
930
+
931
+ const handleExitQuiz = () => {
932
+ console.log("Quiz Exited (SCORM Launcher)");
933
+ showCompletionScreen('Quiz exited. You may close this window or your Learning Management System will manage navigation.');
934
+ // SCORM termination logic should be handled by QuizEngine/QuizPlayer via SCORMService.destroy()
935
+ };
936
+
937
+ // Fallback if quizConfigData is malformed but loaded
938
+ if (!quizConfigData.questions || !Array.isArray(quizConfigData.questions)) {
939
+ showStatusMessage('Error: Quiz data is malformed. "questions" array is missing.', true);
940
+ return React.createElement('div', null, 'Error rendering quiz.');
941
+ }
942
+
943
+
944
+ return React.createElement(QuizPlayer, {
945
+ quizConfig: quizConfigData,
946
+ onQuizComplete: handleQuizComplete,
947
+ onExitQuiz: handleExitQuiz,
948
+ // You might pass isScormContext=true if QuizPlayer needs it
949
+ });
950
+ };
951
+
952
+ const rootElement = document.getElementById('root');
953
+ if (rootElement) {
954
+ rootElement.innerHTML = ''; // Clear loading message before rendering React app
955
+ const reactRoot = ReactDOM.createRoot(rootElement);
956
+ reactRoot.render(React.createElement(React.StrictMode, null, React.createElement(App)));
957
+ } else {
958
+ console.error('Root element (#root) not found for SCORM launcher.');
959
+ document.body.innerHTML = '<p style="color: red; text-align: center; padding: 20px;">Critical Error: Root HTML element not found.</p>';
960
+ }
961
+ }
962
+
963
+ // Ensure DOM is ready before trying to find #root
964
+ if (document.readyState === 'loading') {
965
+ document.addEventListener('DOMContentLoaded', main);
966
+ } else {
967
+ main();
968
+ }
969
+ </script>
970
+ </body>
971
+ </html>
972
+ `;
973
+ };
974
+
975
+ // src/services/SCORMManifestGenerator.ts
976
+ var escapeXML = (unsafe) => {
977
+ if (typeof unsafe !== "string") return "";
978
+ return unsafe.replace(/[<>&'"]/g, (c) => {
979
+ switch (c) {
980
+ case "<":
981
+ return "&lt;";
982
+ case ">":
983
+ return "&gt;";
984
+ case "&":
985
+ return "&amp;";
986
+ case "'":
987
+ return "&apos;";
988
+ case '"':
989
+ return "&quot;";
990
+ default:
991
+ return c;
992
+ }
993
+ });
994
+ };
995
+ var generateSCORMManifest = (quizConfig, scormVersion, launcherFile = "index.html", libraryJSPath = "lib/interactive-quiz-kit.esm.js", quizDataPath = "quiz_data.json", blocklyCSSPath = "blockly-styles.css") => {
996
+ var _a;
997
+ const uniqueId = `iqk_${quizConfig.id.replace(/[^a-zA-Z0-9_]/g, "_")}`;
998
+ const organizationId = `ORG-${uniqueId}`;
999
+ const itemId = `ITEM-${uniqueId}`;
1000
+ const resourceId = `RES-${uniqueId}`;
1001
+ const quizTitle = escapeXML(quizConfig.title);
1002
+ const passingScore = (_a = quizConfig.settings) == null ? void 0 : _a.passingScorePercent;
1003
+ const effectiveScormVersion = scormVersion;
1004
+ const schemaVersion = effectiveScormVersion === "2004" ? "2004 4th Edition" : "1.2";
1005
+ const adlcpNamespace = effectiveScormVersion === "2004" ? "http://www.adlnet.org/xsd/adlcp_v1p3" : "http://www.adlnet.org/xsd/adlcp_rootv1p2";
1006
+ const imsmdNamespace = effectiveScormVersion === "2004" ? "http://www.imsglobal.org/xsd/imsmd_v1p2" : "http://www.imsglobal.org/xsd/imsmd_rootv1p2p1";
1007
+ const xsiSchemaLocation = effectiveScormVersion === "2004" ? "http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd http://www.adlnet.org/xsd/adlcp_v1p3 adlcp_v1p3.xsd http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd" : "http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd";
1008
+ const files = [
1009
+ launcherFile,
1010
+ libraryJSPath,
1011
+ quizDataPath,
1012
+ blocklyCSSPath
1013
+ ].map((file) => `<file href="${escapeXML(file)}"/>`).join("\n ");
1014
+ const manifestHeader = effectiveScormVersion === "2004" ? `<?xml version="1.0" encoding="UTF-8"?>
1015
+ <manifest identifier="${uniqueId}-MANIFEST" version="1.0"
1016
+ xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"
1017
+ xmlns:adlcp="${adlcpNamespace}"
1018
+ xmlns:imsmd="${imsmdNamespace}"
1019
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1020
+ xsi:schemaLocation="${xsiSchemaLocation}">` : (
1021
+ // SCORM 1.2
1022
+ `<?xml version="1.0" encoding="UTF-8"?>
1023
+ <manifest identifier="${uniqueId}-MANIFEST" version="1.2"
1024
+ xmlns="http://www.imsproject.org/xsd/imscp_rootv1p1p2"
1025
+ xmlns:adlcp="${adlcpNamespace}"
1026
+ xmlns:imsmd="${imsmdNamespace}"
1027
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1028
+ xsi:schemaLocation="${xsiSchemaLocation}">`
1029
+ );
1030
+ const organizationStructure = effectiveScormVersion === "2004" ? `<organizations default="${organizationId}">
1031
+ <organization identifier="${organizationId}" structure="hierarchical">
1032
+ <title>${quizTitle}</title>
1033
+ <item identifier="${itemId}" identifierref="${resourceId}">
1034
+ <title>${quizTitle}</title>
1035
+ ${passingScore !== void 0 ? `<adlcp:masteryscore>${passingScore}</adlcp:masteryscore>` : ""}
1036
+ </item>
1037
+ </organization>
1038
+ </organizations>` : (
1039
+ // SCORM 1.2
1040
+ `<organizations default="${organizationId}">
1041
+ <organization identifier="${organizationId}">
1042
+ <title>${quizTitle}</title>
1043
+ <item identifier="${itemId}" identifierref="${resourceId}" isvisible="true">
1044
+ <title>${quizTitle}</title>
1045
+ ${passingScore !== void 0 ? `<adlcp:masteryscore>${passingScore}</adlcp:masteryscore>` : ""}
1046
+ </item>
1047
+ </organization>
1048
+ </organizations>`
1049
+ );
1050
+ const resourceScormType = effectiveScormVersion === "2004" ? "sco" : "sco";
1051
+ return `${manifestHeader}
1052
+ <metadata>
1053
+ <schema>ADL SCORM</schema>
1054
+ <schemaversion>${schemaVersion}</schemaversion>
1055
+ <imsmd:lom>
1056
+ <imsmd:general>
1057
+ <imsmd:title>
1058
+ <imsmd:langstring xml:lang="en">${quizTitle}</imsmd:langstring>
1059
+ </imsmd:title>
1060
+ ${quizConfig.description ? `<imsmd:description><imsmd:langstring xml:lang="en">${escapeXML(quizConfig.description)}</imsmd:langstring></imsmd:description>` : ""}
1061
+ </imsmd:general>
1062
+ </imsmd:lom>
1063
+ </metadata>
1064
+ ${organizationStructure}
1065
+ <resources>
1066
+ <resource identifier="${resourceId}" type="webcontent" adlcp:scormtype="${resourceScormType}" href="${escapeXML(launcherFile)}">
1067
+ ${files}
1068
+ </resource>
1069
+ </resources>
1070
+ </manifest>`;
1071
+ };
1072
+
1073
+ // src/utils/idGenerators.ts
1074
+ function generateUniqueId(prefix = "id_") {
1075
+ return prefix + Date.now().toString(36) + Math.random().toString(36).substring(2, 7);
1076
+ }
1077
+
1078
+ // src/services/sampleQuiz.ts
1079
+ var trueFalseQ1 = {
1080
+ id: generateUniqueId("tfq_"),
1081
+ questionType: "true_false",
1082
+ prompt: "B\u1EA7u tr\u1EDDi c\xF3 m\xE0u xanh do hi\u1EC7n t\u01B0\u1EE3ng t\xE1n x\u1EA1 Rayleigh.",
1083
+ correctAnswer: true,
1084
+ points: 10,
1085
+ explanation: "T\xE1n x\u1EA1 Rayleigh khi\u1EBFn \xE1nh s\xE1ng xanh t\xE1n x\u1EA1 nhi\u1EC1u h\u01A1n c\xE1c m\xE0u kh\xE1c v\xEC n\xF3 truy\u1EC1n \u0111i d\u01B0\u1EDBi d\u1EA1ng s\xF3ng ng\u1EAFn h\u01A1n, nh\u1ECF h\u01A1n.",
1086
+ difficulty: "easy",
1087
+ topic: "V\u1EADt l\xFD",
1088
+ category: "Khoa h\u1ECDc",
1089
+ learningObjective: "Hi\u1EC3u v\u1EC1 quang h\u1ECDc kh\xED quy\u1EC3n c\u01A1 b\u1EA3n."
1090
+ };
1091
+ var mcq1 = {
1092
+ id: generateUniqueId("mcq_"),
1093
+ questionType: "multiple_choice",
1094
+ prompt: "Th\u1EE7 \u0111\xF4 c\u1EE7a Ph\xE1p l\xE0 g\xEC?",
1095
+ options: [
1096
+ { id: generateUniqueId("opt_"), text: "Berlin" },
1097
+ { id: generateUniqueId("opt_"), text: "Madrid" },
1098
+ { id: generateUniqueId("opt_"), text: "Paris" },
1099
+ { id: generateUniqueId("opt_"), text: "Rome" }
1100
+ ],
1101
+ correctAnswerId: "",
1102
+ points: 15,
1103
+ difficulty: "easy",
1104
+ topic: "\u0110\u1ECBa l\xFD",
1105
+ category: "Khoa h\u1ECDc X\xE3 h\u1ED9i"
1106
+ };
1107
+ var parisOption = mcq1.options.find((opt) => opt.text === "Paris");
1108
+ if (parisOption) {
1109
+ mcq1.correctAnswerId = parisOption.id;
1110
+ }
1111
+ var mrq1_opt1_id = generateUniqueId("opt_");
1112
+ var mrq1_opt2_id = generateUniqueId("opt_");
1113
+ var mrq1_opt3_id = generateUniqueId("opt_");
1114
+ var mrq1_opt4_id = generateUniqueId("opt_");
1115
+ var mrq1_opt5_id = generateUniqueId("opt_");
1116
+ var mrq1 = {
1117
+ id: generateUniqueId("mrq_"),
1118
+ questionType: "multiple_response",
1119
+ prompt: "Nh\u1EEFng h\xE0nh tinh n\xE0o sau \u0111\xE2y thu\u1ED9c H\u1EC7 M\u1EB7t Tr\u1EDDi c\xF3 v\xE0nh \u0111ai (rings)?",
1120
+ options: [
1121
+ { id: mrq1_opt1_id, text: "Sao Th\u1ED5 (Saturn)" },
1122
+ { id: mrq1_opt2_id, text: "Sao M\u1ED9c (Jupiter)" },
1123
+ { id: mrq1_opt3_id, text: "Sao Thi\xEAn V\u01B0\u01A1ng (Uranus)" },
1124
+ { id: mrq1_opt4_id, text: "Sao H\u1EA3i V\u01B0\u01A1ng (Neptune)" },
1125
+ { id: mrq1_opt5_id, text: "Tr\xE1i \u0110\u1EA5t (Earth)" }
1126
+ ],
1127
+ correctAnswerIds: [mrq1_opt1_id, mrq1_opt2_id, mrq1_opt3_id, mrq1_opt4_id],
1128
+ points: 20,
1129
+ explanation: "Sao Th\u1ED5 n\u1ED5i ti\u1EBFng v\u1EDBi h\u1EC7 th\u1ED1ng v\xE0nh \u0111ai ph\u1EE9c t\u1EA1p. Sao M\u1ED9c, Sao Thi\xEAn V\u01B0\u01A1ng v\xE0 Sao H\u1EA3i V\u01B0\u01A1ng c\u0169ng c\xF3 v\xE0nh \u0111ai, m\u1EB7c d\xF9 ch\xFAng m\u1EDD h\u01A1n v\xE0 kh\xF3 quan s\xE1t h\u01A1n nhi\u1EC1u so v\u1EDBi v\xE0nh \u0111ai c\u1EE7a Sao Th\u1ED5.",
1130
+ difficulty: "medium",
1131
+ topic: "Thi\xEAn v\u0103n h\u1ECDc",
1132
+ category: "Khoa h\u1ECDc"
1133
+ };
1134
+ var shortAnswerQ1 = {
1135
+ id: generateUniqueId("saq_"),
1136
+ questionType: "short_answer",
1137
+ prompt: "Ng\xF4n ng\u1EEF l\u1EADp tr\xECnh n\xE0o th\u01B0\u1EDDng \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng ch\u1EE7 y\u1EBFu cho ph\xE1t tri\u1EC3n web ph\xEDa client-side \u0111\u1EC3 l\xE0m cho c\xE1c trang web tr\u1EDF n\xEAn t\u01B0\u01A1ng t\xE1c?",
1138
+ acceptedAnswers: ["JavaScript", "Javascript", "javascript", "JS", "js"],
1139
+ points: 10,
1140
+ explanation: "JavaScript l\xE0 ng\xF4n ng\u1EEF k\u1ECBch b\u1EA3n ch\xEDnh ch\u1EA1y tr\xEAn tr\xECnh duy\u1EC7t c\u1EE7a ng\u01B0\u1EDDi d\xF9ng \u0111\u1EC3 t\u1EA1o ra c\xE1c trang web t\u01B0\u01A1ng t\xE1c.",
1141
+ difficulty: "easy",
1142
+ topic: "Ph\xE1t tri\u1EC3n Web",
1143
+ category: "C\xF4ng ngh\u1EC7",
1144
+ isCaseSensitive: false
1145
+ };
1146
+ var numericQ1 = {
1147
+ id: generateUniqueId("nq_"),
1148
+ questionType: "numeric",
1149
+ prompt: "Nhi\u1EC7t \u0111\u1ED9 s\xF4i c\u1EE7a n\u01B0\u1EDBc \u1EDF \xE1p su\u1EA5t kh\xED quy\u1EC3n ti\xEAu chu\u1EA9n l\xE0 bao nhi\xEAu \u0111\u1ED9 C?",
1150
+ answer: 100,
1151
+ tolerance: 1,
1152
+ points: 10,
1153
+ explanation: "N\u01B0\u1EDBc s\xF4i \u1EDF 100 \u0111\u1ED9 C (212 \u0111\u1ED9 F) \u1EDF \xE1p su\u1EA5t kh\xED quy\u1EC3n ti\xEAu chu\u1EA9n.",
1154
+ difficulty: "easy",
1155
+ topic: "H\xF3a h\u1ECDc",
1156
+ category: "Khoa h\u1ECDc"
1157
+ };
1158
+ var fillInTheBlanksQ1 = {
1159
+ id: generateUniqueId("fitb_"),
1160
+ questionType: "fill_in_the_blanks",
1161
+ prompt: "\u0110i\u1EC1n v\xE0o ch\u1ED7 tr\u1ED1ng \u0111\u1EC3 ho\xE0n th\xE0nh c\xE2u sau:",
1162
+ segments: [
1163
+ { type: "text", content: "N\u01B0\u1EDBc \u0111\u01B0\u1EE3c c\u1EA5u t\u1EA1o t\u1EEB hai nguy\xEAn t\u1ED1 l\xE0 " },
1164
+ { type: "blank", id: "fitb_h" },
1165
+ { type: "text", content: " v\xE0 " },
1166
+ { type: "blank", id: "fitb_o" },
1167
+ { type: "text", content: "." }
1168
+ ],
1169
+ answers: [
1170
+ { blankId: "fitb_h", acceptedValues: ["Hydro", "Hydrogen", "H"] },
1171
+ { blankId: "fitb_o", acceptedValues: ["Oxy", "Oxygen", "O"] }
1172
+ ],
1173
+ isCaseSensitive: false,
1174
+ points: 15,
1175
+ explanation: "N\u01B0\u1EDBc (H\u2082O) \u0111\u01B0\u1EE3c t\u1EA1o th\xE0nh t\u1EEB hai nguy\xEAn t\u1EED Hydro v\xE0 m\u1ED9t nguy\xEAn t\u1EED Oxy.",
1176
+ difficulty: "easy",
1177
+ topic: "H\xF3a h\u1ECDc C\u01A1 b\u1EA3n",
1178
+ category: "Khoa h\u1ECDc"
1179
+ };
1180
+ var sequenceQ1_item1_id = generateUniqueId("seqi_");
1181
+ var sequenceQ1_item2_id = generateUniqueId("seqi_");
1182
+ var sequenceQ1_item3_id = generateUniqueId("seqi_");
1183
+ var sequenceQ1_item4_id = generateUniqueId("seqi_");
1184
+ var sequenceQ1 = {
1185
+ id: generateUniqueId("seqq_"),
1186
+ questionType: "sequence",
1187
+ prompt: "S\u1EAFp x\u1EBFp c\xE1c h\xE0nh tinh sau theo th\u1EE9 t\u1EF1 t\u1EEB g\u1EA7n M\u1EB7t Tr\u1EDDi nh\u1EA5t \u0111\u1EBFn xa nh\u1EA5t:",
1188
+ items: [
1189
+ { id: sequenceQ1_item1_id, content: "Sao H\u1ECFa (Mars)" },
1190
+ { id: sequenceQ1_item2_id, content: "Tr\xE1i \u0110\u1EA5t (Earth)" },
1191
+ { id: sequenceQ1_item3_id, content: "Sao Th\u1EE7y (Mercury)" },
1192
+ { id: sequenceQ1_item4_id, content: "Sao Kim (Venus)" }
1193
+ ],
1194
+ correctOrder: [sequenceQ1_item3_id, sequenceQ1_item4_id, sequenceQ1_item2_id, sequenceQ1_item1_id],
1195
+ points: 20,
1196
+ explanation: "Th\u1EE9 t\u1EF1 \u0111\xFAng c\u1EE7a c\xE1c h\xE0nh tinh t\u1EEB g\u1EA7n M\u1EB7t Tr\u1EDDi nh\u1EA5t l\xE0: Sao Th\u1EE7y, Sao Kim, Tr\xE1i \u0110\u1EA5t, Sao H\u1ECFa.",
1197
+ difficulty: "medium",
1198
+ topic: "Thi\xEAn v\u0103n h\u1ECDc",
1199
+ category: "Khoa h\u1ECDc"
1200
+ };
1201
+ var matchingQ1_prompt_vn = generateUniqueId("matp_");
1202
+ var matchingQ1_prompt_jp = generateUniqueId("matp_");
1203
+ var matchingQ1_prompt_us = generateUniqueId("matp_");
1204
+ var matchingQ1_opt_hanoi = generateUniqueId("mato_");
1205
+ var matchingQ1_opt_tokyo = generateUniqueId("mato_");
1206
+ var matchingQ1_opt_dc = generateUniqueId("mato_");
1207
+ var matchingQ1 = {
1208
+ id: generateUniqueId("matq_"),
1209
+ questionType: "matching",
1210
+ prompt: "H\xE3y gh\xE9p m\u1ED7i qu\u1ED1c gia v\u1EDBi th\u1EE7 \u0111\xF4 t\u01B0\u01A1ng \u1EE9ng.",
1211
+ prompts: [
1212
+ { id: matchingQ1_prompt_vn, content: "Vi\u1EC7t Nam" },
1213
+ { id: matchingQ1_prompt_jp, content: "Nh\u1EADt B\u1EA3n" },
1214
+ { id: matchingQ1_prompt_us, content: "Hoa K\u1EF3" }
1215
+ ],
1216
+ options: [
1217
+ { id: matchingQ1_opt_tokyo, content: "Tokyo" },
1218
+ { id: matchingQ1_opt_hanoi, content: "H\xE0 N\u1ED9i" },
1219
+ { id: matchingQ1_opt_dc, content: "Washington D.C." }
1220
+ ],
1221
+ correctAnswerMap: [
1222
+ { promptId: matchingQ1_prompt_vn, optionId: matchingQ1_opt_hanoi },
1223
+ { promptId: matchingQ1_prompt_jp, optionId: matchingQ1_opt_tokyo },
1224
+ { promptId: matchingQ1_prompt_us, optionId: matchingQ1_opt_dc }
1225
+ ],
1226
+ points: 15,
1227
+ explanation: "H\xE0 N\u1ED9i l\xE0 th\u1EE7 \u0111\xF4 c\u1EE7a Vi\u1EC7t Nam, Tokyo l\xE0 c\u1EE7a Nh\u1EADt B\u1EA3n, v\xE0 Washington D.C. l\xE0 c\u1EE7a Hoa K\u1EF3.",
1228
+ difficulty: "easy",
1229
+ topic: "\u0110\u1ECBa l\xFD Th\u1EBF gi\u1EDBi",
1230
+ shuffleOptions: true
1231
+ };
1232
+ var dndQ1_drag_apple = generateUniqueId("dndi_");
1233
+ var dndQ1_drag_banana = generateUniqueId("dndi_");
1234
+ var dndQ1_drag_orange = generateUniqueId("dndi_");
1235
+ var dndQ1_drop_red = generateUniqueId("dndz_");
1236
+ var dndQ1_drop_yellow = generateUniqueId("dndz_");
1237
+ var dndQ1_drop_orange_color = generateUniqueId("dndz_");
1238
+ var dragAndDropQ1 = {
1239
+ id: generateUniqueId("dndq_"),
1240
+ questionType: "drag_and_drop",
1241
+ prompt: "K\xE9o c\xE1c lo\u1EA1i tr\xE1i c\xE2y v\xE0o \u0111\xFAng gi\u1ECF m\xE0u c\u1EE7a ch\xFAng (theo logic gh\xE9p n\u1ED1i \u0111\u01A1n gi\u1EA3n).",
1242
+ draggableItems: [
1243
+ { id: dndQ1_drag_apple, content: "T\xE1o" },
1244
+ { id: dndQ1_drag_banana, content: "Chu\u1ED1i" },
1245
+ { id: dndQ1_drag_orange, content: "Cam" }
1246
+ ],
1247
+ dropZones: [
1248
+ { id: dndQ1_drop_red, label: "Gi\u1ECF \u0110\u1ECF" },
1249
+ { id: dndQ1_drop_yellow, label: "Gi\u1ECF V\xE0ng" },
1250
+ { id: dndQ1_drop_orange_color, label: "Gi\u1ECF Cam" }
1251
+ ],
1252
+ answerMap: [
1253
+ { draggableId: dndQ1_drag_apple, dropZoneId: dndQ1_drop_red },
1254
+ { draggableId: dndQ1_drag_banana, dropZoneId: dndQ1_drop_yellow },
1255
+ { draggableId: dndQ1_drag_orange, dropZoneId: dndQ1_drop_orange_color }
1256
+ ],
1257
+ points: 15,
1258
+ explanation: "T\xE1o th\u01B0\u1EDDng c\xF3 m\xE0u \u0111\u1ECF (gi\u1ECF \u0111\u1ECF), chu\u1ED1i m\xE0u v\xE0ng (gi\u1ECF v\xE0ng), v\xE0 cam c\xF3 m\xE0u cam (gi\u1ECF cam).",
1259
+ difficulty: "easy",
1260
+ topic: "M\xE0u s\u1EAFc v\xE0 V\u1EADt th\u1EC3",
1261
+ backgroundImageUrl: "https://placehold.co/600x200.png",
1262
+ imageAltText: "colored baskets"
1263
+ };
1264
+ var hotspotQ1_engine_left = generateUniqueId("hs_");
1265
+ var hotspotQ1_engine_right = generateUniqueId("hs_");
1266
+ var hotspotQ1_cockpit = generateUniqueId("hs_");
1267
+ var hotspotQ1 = {
1268
+ id: generateUniqueId("hsq_"),
1269
+ questionType: "hotspot",
1270
+ prompt: "Nh\u1EA5p v\xE0o (c\xE1c) \u0111\u1ED9ng c\u01A1 c\u1EE7a m\xE1y bay trong h\xECnh.",
1271
+ imageUrl: "https://placehold.co/600x400.png",
1272
+ imageAltText: "airplane diagram",
1273
+ hotspots: [
1274
+ { id: hotspotQ1_engine_left, shape: "rect", coords: [150, 200, 80, 60], description: "\u0110\u1ED9ng c\u01A1 b\xEAn tr\xE1i" },
1275
+ { id: hotspotQ1_engine_right, shape: "rect", coords: [370, 200, 80, 60], description: "\u0110\u1ED9ng c\u01A1 b\xEAn ph\u1EA3i" },
1276
+ { id: hotspotQ1_cockpit, shape: "rect", coords: [250, 120, 100, 70], description: "Bu\u1ED3ng l\xE1i" }
1277
+ ],
1278
+ correctHotspotIds: [hotspotQ1_engine_left, hotspotQ1_engine_right],
1279
+ points: 15,
1280
+ explanation: "M\xE1y bay n\xE0y c\xF3 hai \u0111\u1ED9ng c\u01A1 ch\xEDnh, n\u1EB1m d\u01B0\u1EDBi c\xE1nh.",
1281
+ difficulty: "medium",
1282
+ topic: "H\xE0ng kh\xF4ng",
1283
+ category: "K\u1EF9 thu\u1EADt"
1284
+ };
1285
+ var blocklyQ1 = {
1286
+ id: generateUniqueId("blkq_"),
1287
+ questionType: "blockly_programming",
1288
+ prompt: "S\u1EED d\u1EE5ng c\xE1c kh\u1ED1i l\u1EC7nh \u0111\u1EC3 t\u1EA1o m\u1ED9t ch\u01B0\u01A1ng tr\xECnh in ra d\xF2ng ch\u1EEF 'Hello, World!' v\xE0o console.",
1289
+ points: 25,
1290
+ difficulty: "easy",
1291
+ topic: "L\u1EADp tr\xECnh C\u01A1 b\u1EA3n",
1292
+ category: "C\xF4ng ngh\u1EC7 Th\xF4ng tin",
1293
+ toolboxDefinition: `
1294
+ <xml xmlns="https://developers.google.com/blockly/xml">
1295
+ <category name="Text" colour="%{BKY_TEXTS_HUE}">
1296
+ <block type="text"></block>
1297
+ <block type="text_print"></block>
1298
+ </category>
1299
+ </xml>
1300
+ `,
1301
+ initialWorkspace: `
1302
+ <xml xmlns="https://developers.google.com/blockly/xml">
1303
+ <block type="text_print" id="${generateUniqueId("blki_")}" x="70" y="70">
1304
+ <value name="TEXT">
1305
+ <shadow type="text" id="${generateUniqueId("blki_")}">
1306
+ <field name="TEXT">abc</field>
1307
+ </shadow>
1308
+ </value>
1309
+ </block>
1310
+ </xml>
1311
+ `,
1312
+ solutionWorkspaceXML: `
1313
+ <xml xmlns="https://developers.google.com/blockly/xml">
1314
+ <block type="text_print" id="${generateUniqueId("blki_solution_")}" x="70" y="70">
1315
+ <value name="TEXT">
1316
+ <block type="text" id="${generateUniqueId("blki_text_solution_")}">
1317
+ <field name="TEXT">Hello, World!</field>
1318
+ </block>
1319
+ </value>
1320
+ </block>
1321
+ </xml>
1322
+ `,
1323
+ solutionGeneratedCode: "window.alert('Hello, World!');",
1324
+ // Normalized JS code
1325
+ explanation: "Ch\u01B0\u01A1ng tr\xECnh c\u1EA7n s\u1EED d\u1EE5ng kh\u1ED1i 'print' v\u1EDBi \u0111\u1EA7u v\xE0o l\xE0 kh\u1ED1i v\u0103n b\u1EA3n ch\u1EE9a 'Hello, World!'."
1326
+ };
1327
+ var scratchQ1 = {
1328
+ id: generateUniqueId("scrq_"),
1329
+ questionType: "scratch_programming",
1330
+ prompt: "D\xF9ng kh\u1ED1i l\u1EC7nh Scratch \u0111\u1EC3 di chuy\u1EC3n nh\xE2n v\u1EADt v\u1EC1 ph\xEDa tr\u01B0\u1EDBc 10 b\u01B0\u1EDBc khi c\u1EDD xanh \u0111\u01B0\u1EE3c click.",
1331
+ points: 20,
1332
+ difficulty: "easy",
1333
+ topic: "L\u1EADp tr\xECnh Scratch",
1334
+ category: "C\xF4ng ngh\u1EC7 Th\xF4ng tin",
1335
+ toolboxDefinition: `
1336
+ <xml xmlns="https://developers.google.com/blockly/xml">
1337
+ <category name="Motion" colour="#4C97FF">
1338
+ <block type="motion_movesteps"></block>
1339
+ </category>
1340
+ <category name="Events" colour="#FFBF00">
1341
+ <block type="event_whenflagclicked"></block>
1342
+ </category>
1343
+ </xml>
1344
+ `,
1345
+ initialWorkspace: `
1346
+ <xml xmlns="https://developers.google.com/blockly/xml"></xml>
1347
+ `,
1348
+ solutionWorkspaceXML: `
1349
+ <xml xmlns="https://developers.google.com/blockly/xml">
1350
+ <block type="event_whenflagclicked" id="${generateUniqueId("scr_event_")}" x="50" y="50">
1351
+ <next>
1352
+ <block type="motion_movesteps" id="${generateUniqueId("scr_motion_")}">
1353
+ <value name="STEPS">
1354
+ <shadow type="math_number">
1355
+ <field name="NUM">10</field>
1356
+ </shadow>
1357
+ </value>
1358
+ </block>
1359
+ </next>
1360
+ </block>
1361
+ </xml>
1362
+ `,
1363
+ solutionGeneratedCode: "whenGreenFlagClicked(() => { move(10); });",
1364
+ // Example pseudo-code or JS representation
1365
+ explanation: "S\u1EED d\u1EE5ng kh\u1ED1i 'when green flag clicked' t\u1EEB Events v\xE0 kh\u1ED1i 'move 10 steps' t\u1EEB Motion."
1366
+ };
1367
+ var sampleQuiz = {
1368
+ id: "sample-quiz-001",
1369
+ title: "Sample Quiz for Testers",
1370
+ description: "A short quiz with a few different question types to test the QuizKit functionality.",
1371
+ questions: [
1372
+ trueFalseQ1,
1373
+ mcq1,
1374
+ mrq1,
1375
+ shortAnswerQ1,
1376
+ numericQ1,
1377
+ fillInTheBlanksQ1,
1378
+ sequenceQ1,
1379
+ matchingQ1,
1380
+ dragAndDropQ1,
1381
+ hotspotQ1,
1382
+ blocklyQ1,
1383
+ scratchQ1
1384
+ // Added Scratch question
1385
+ ],
1386
+ settings: {
1387
+ shuffleQuestions: true,
1388
+ shuffleOptions: true,
1389
+ showCorrectAnswers: "end_of_quiz",
1390
+ passingScorePercent: 70,
1391
+ timeLimitMinutes: 25
1392
+ }
1393
+ };
1394
+ var emptyQuiz = {
1395
+ id: generateUniqueId("quiz_"),
1396
+ title: "New Quiz",
1397
+ description: "",
1398
+ questions: [],
1399
+ settings: {
1400
+ shuffleQuestions: false,
1401
+ shuffleOptions: false,
1402
+ showCorrectAnswers: "end_of_quiz",
1403
+ passingScorePercent: 0,
1404
+ timeLimitMinutes: 0
1405
+ }
1406
+ };
1407
+
1408
+ // src/services/scormPackaging.ts
1409
+ var import_jszip = __toESM(require("jszip"));
1410
+ var sanitizeFilename = (name) => {
1411
+ return name.replace(/[^a-z0-9_.-]/gi, "_").toLowerCase();
1412
+ };
1413
+ var exportQuizAsSCORMZip = async (quiz, options) => {
1414
+ try {
1415
+ const zip = new import_jszip.default();
1416
+ const quizDataString = JSON.stringify(quiz, null, 2);
1417
+ zip.file("quiz_data.json", quizDataString);
1418
+ const libraryJSPath = "lib/interactive-quiz-kit.esm.js";
1419
+ const blocklyCSSPath = "blockly-styles.css";
1420
+ const manifestContent = generateSCORMManifest(
1421
+ quiz,
1422
+ options.scormVersion,
1423
+ "index.html",
1424
+ // Launcher file name in ZIP
1425
+ libraryJSPath,
1426
+ // Expected path for lib JS in ZIP
1427
+ "quiz_data.json",
1428
+ // Path to quiz data in ZIP
1429
+ blocklyCSSPath
1430
+ // Expected path for Blockly CSS in ZIP
1431
+ );
1432
+ zip.file("imsmanifest.xml", manifestContent);
1433
+ const launcherContent = generateLauncherHTML(
1434
+ quiz,
1435
+ // Pass full quizConfig for title and other potential uses
1436
+ libraryJSPath,
1437
+ // Path to library JS, relative within ZIP
1438
+ "quiz_data.json",
1439
+ // Path to quiz data, relative within ZIP
1440
+ blocklyCSSPath,
1441
+ // Path to Blockly CSS, relative within ZIP
1442
+ quiz.title
1443
+ // Explicitly pass title for the HTML page
1444
+ );
1445
+ zip.file("index.html", launcherContent);
1446
+ const blob = await zip.generateAsync({ type: "blob" });
1447
+ const fileName = `${sanitizeFilename(quiz.title || "quiz")}_scorm_${options.scormVersion.replace(".", "_")}.zip`;
1448
+ const link = document.createElement("a");
1449
+ link.href = URL.createObjectURL(blob);
1450
+ link.download = fileName;
1451
+ document.body.appendChild(link);
1452
+ link.click();
1453
+ document.body.removeChild(link);
1454
+ URL.revokeObjectURL(link.href);
1455
+ return { success: true, fileName };
1456
+ } catch (err) {
1457
+ console.error("Error creating SCORM ZIP:", err);
1458
+ return { success: false, error: err instanceof Error ? err.message : "Unknown error during ZIP creation." };
1459
+ }
1460
+ };
1461
+
1462
+ // src/ai/genkit.ts
1463
+ var import_genkit = require("genkit");
1464
+ var import_googleai = require("@genkit-ai/googleai");
1465
+ var ai = (0, import_genkit.genkit)({
1466
+ plugins: [(0, import_googleai.googleAI)()],
1467
+ model: "googleai/gemini-2.0-flash"
1468
+ });
1469
+
1470
+ // src/ai/flows/generate-fitb-question.ts
1471
+ var import_genkit3 = require("genkit");
1472
+ var GenerateFillInTheBlanksQuestionInputSchema = import_genkit3.z.object({
1473
+ topic: import_genkit3.z.string().describe("The topic for the question."),
1474
+ difficulty: import_genkit3.z.enum(["easy", "medium", "hard"]).optional().default("medium"),
1475
+ numberOfBlanks: import_genkit3.z.number().int().min(1).max(5).optional().default(1).describe("Number of blanks to include (1-5)."),
1476
+ isCaseSensitive: import_genkit3.z.boolean().optional().default(false).describe("Whether answers should be case-sensitive."),
1477
+ contextDescription: import_genkit3.z.string().optional().describe("A specific context or scenario for the question, complementing the main topic."),
1478
+ selectedContextId: import_genkit3.z.string().optional().describe("The ID of the selected context, if any.")
1479
+ });
1480
+ var AIFillInTheBlanksOutputFieldsSchema = import_genkit3.z.object({
1481
+ prompt: import_genkit3.z.string().describe("The overall instruction for the question (e.g., 'Fill in the blanks in the sentence below.')."),
1482
+ sentenceWithPlaceholders: import_genkit3.z.string().describe("The sentence containing placeholders for blanks, e.g., 'The capital of {{country}} is {{city}}.' or 'Water is made of {{element1}} and {{element2}}.' Placeholders should be distinct and clearly marked, e.g., using {{placeholder_name}} format."),
1483
+ blanks: import_genkit3.z.array(
1484
+ import_genkit3.z.object({
1485
+ placeholder: import_genkit3.z.string().describe("The exact placeholder string used in 'sentenceWithPlaceholders' (e.g., 'country', 'element1'). Do not include the curly braces."),
1486
+ acceptedAnswers: import_genkit3.z.array(import_genkit3.z.string()).min(1).describe("An array of acceptable answers for this blank.")
1487
+ })
1488
+ ).min(1).describe("An array defining each placeholder and its accepted answers."),
1489
+ isCaseSensitive: import_genkit3.z.boolean().optional().describe("Should answer evaluation be case sensitive? Defaults to input or false."),
1490
+ explanation: import_genkit3.z.string().optional().describe("Explanation for the correct answer(s)."),
1491
+ points: import_genkit3.z.number().optional().default(10),
1492
+ difficulty: import_genkit3.z.enum(["easy", "medium", "hard"]).optional(),
1493
+ topic: import_genkit3.z.string().optional()
1494
+ });
1495
+ var FillInTheBlanksQuestionZodSchema = import_genkit3.z.object({
1496
+ id: import_genkit3.z.string(),
1497
+ questionType: import_genkit3.z.literal("fill_in_the_blanks"),
1498
+ prompt: import_genkit3.z.string(),
1499
+ segments: import_genkit3.z.array(import_genkit3.z.object({ type: import_genkit3.z.enum(["text", "blank"]), content: import_genkit3.z.string().optional(), id: import_genkit3.z.string().optional() })),
1500
+ answers: import_genkit3.z.array(import_genkit3.z.object({ blankId: import_genkit3.z.string(), acceptedValues: import_genkit3.z.array(import_genkit3.z.string()) })),
1501
+ isCaseSensitive: import_genkit3.z.boolean().optional(),
1502
+ points: import_genkit3.z.number().optional(),
1503
+ explanation: import_genkit3.z.string().optional(),
1504
+ learningObjective: import_genkit3.z.string().optional(),
1505
+ glossary: import_genkit3.z.array(import_genkit3.z.string()).optional(),
1506
+ bloomLevel: import_genkit3.z.string().optional(),
1507
+ difficulty: import_genkit3.z.enum(["easy", "medium", "hard"]).optional(),
1508
+ contextCode: import_genkit3.z.string().optional(),
1509
+ gradeBand: import_genkit3.z.string().optional(),
1510
+ course: import_genkit3.z.string().optional(),
1511
+ category: import_genkit3.z.string().optional(),
1512
+ topic: import_genkit3.z.string().optional()
1513
+ });
1514
+ var GenerateFillInTheBlanksQuestionOutputSchema = import_genkit3.z.object({
1515
+ question: FillInTheBlanksQuestionZodSchema.optional().describe("The generated Fill-In-The-Blanks question.")
1516
+ });
1517
+ async function generateFillInTheBlanksQuestion(input) {
1518
+ return generateFillInTheBlanksQuestionFlow(input);
1519
+ }
1520
+ var fitbAIPrompt = ai.definePrompt({
1521
+ name: "fitbQuestionGeneratorPrompt",
1522
+ input: { schema: GenerateFillInTheBlanksQuestionInputSchema },
1523
+ output: { schema: AIFillInTheBlanksOutputFieldsSchema },
1524
+ prompt: `You are an expert quiz question writer.
1525
+ Generate a single Fill-In-The-Blanks question with approximately {{{numberOfBlanks}}} blanks.
1526
+ Provide:
1527
+ 1. An overall 'prompt' or instruction.
1528
+ 2. A 'sentenceWithPlaceholders' where blanks are clearly marked with double curly braces, e.g., "{{blank_name}}". Each placeholder name inside the braces must be unique.
1529
+ 3. A 'blanks' array, where each object defines a 'placeholder' (matching a name from the sentence, without braces) and its 'acceptedAnswers'.
1530
+ 4. Specify 'isCaseSensitive' (defaulting to {{{isCaseSensitive}}}).
1531
+ 5. Optional 'explanation', 'points' (default 10), refined 'topic', and 'difficulty'.
1532
+
1533
+ Topic: {{{topic}}}
1534
+ {{#if contextDescription}}
1535
+ Context: {{{contextDescription}}}
1536
+ {{/if}}
1537
+ Difficulty: {{{difficulty}}}
1538
+ Target Number of Blanks: {{{numberOfBlanks}}}
1539
+ Case Sensitive: {{{isCaseSensitive}}}
1540
+
1541
+ Example for 'sentenceWithPlaceholders': "The {{color_of_sky}} sky is beautiful, and the {{type_of_grass}} grass is green."
1542
+ Example for 'blanks' array entry for the above: { "placeholder": "color_of_sky", "acceptedAnswers": ["blue"] }
1543
+
1544
+ Ensure your output strictly matches the requested JSON schema. The number of entries in the 'blanks' array should correspond to the number of unique placeholders in 'sentenceWithPlaceholders'.
1545
+ `
1546
+ });
1547
+ var generateFillInTheBlanksQuestionFlow = ai.defineFlow(
1548
+ {
1549
+ name: "generateFillInTheBlanksQuestionFlow",
1550
+ inputSchema: GenerateFillInTheBlanksQuestionInputSchema,
1551
+ outputSchema: GenerateFillInTheBlanksQuestionOutputSchema
1552
+ },
1553
+ async (input) => {
1554
+ try {
1555
+ const { output: aiGeneratedContent } = await fitbAIPrompt(input);
1556
+ if (aiGeneratedContent) {
1557
+ const segments = [];
1558
+ const answers = [];
1559
+ const placeholderToBlankIdMap = {};
1560
+ aiGeneratedContent.blanks.forEach((blankInfo) => {
1561
+ const blankId = generateUniqueId("blank_");
1562
+ placeholderToBlankIdMap[blankInfo.placeholder] = blankId;
1563
+ answers.push({
1564
+ blankId,
1565
+ acceptedValues: blankInfo.acceptedAnswers
1566
+ });
1567
+ });
1568
+ let remainingSentence = aiGeneratedContent.sentenceWithPlaceholders;
1569
+ const placeholderRegex = /\{\{([^}]+)\}\}/g;
1570
+ let lastIndex = 0;
1571
+ let match;
1572
+ while ((match = placeholderRegex.exec(remainingSentence)) !== null) {
1573
+ const placeholderName = match[1];
1574
+ const blankId = placeholderToBlankIdMap[placeholderName];
1575
+ if (match.index > lastIndex) {
1576
+ segments.push({ type: "text", content: remainingSentence.substring(lastIndex, match.index) });
1577
+ }
1578
+ if (blankId) {
1579
+ segments.push({ type: "blank", id: blankId });
1580
+ } else {
1581
+ console.warn(`Placeholder {{${placeholderName}}} found in sentence but not in blanks definition. Treating as text.`);
1582
+ segments.push({ type: "text", content: match[0] });
1583
+ }
1584
+ lastIndex = placeholderRegex.lastIndex;
1585
+ }
1586
+ if (lastIndex < remainingSentence.length) {
1587
+ segments.push({ type: "text", content: remainingSentence.substring(lastIndex) });
1588
+ }
1589
+ if (answers.length === 0 && segments.some((s) => s.type === "blank")) {
1590
+ throw new Error("AI generated blank segments but no corresponding answer definitions.");
1591
+ }
1592
+ if (segments.filter((s) => s.type === "blank").length !== answers.length) {
1593
+ console.warn(`Mismatch between number of blank segments (${segments.filter((s) => s.type === "blank").length}) and answer definitions (${answers.length}). Review AI output.`);
1594
+ if (answers.length === 0 && segments.filter((s) => s.type === "blank").length > 0) {
1595
+ throw new Error("AI generated blank segments but no answer definitions for them.");
1596
+ }
1597
+ }
1598
+ const completeQuestion = {
1599
+ id: generateUniqueId("fitb_ai_"),
1600
+ questionType: "fill_in_the_blanks",
1601
+ prompt: aiGeneratedContent.prompt,
1602
+ segments,
1603
+ answers,
1604
+ isCaseSensitive: aiGeneratedContent.isCaseSensitive === void 0 ? input.isCaseSensitive : aiGeneratedContent.isCaseSensitive,
1605
+ explanation: aiGeneratedContent.explanation,
1606
+ points: aiGeneratedContent.points,
1607
+ topic: aiGeneratedContent.topic || input.topic,
1608
+ difficulty: aiGeneratedContent.difficulty || input.difficulty,
1609
+ contextCode: input.contextDescription ? input.selectedContextId : void 0
1610
+ };
1611
+ return { question: completeQuestion };
1612
+ } else {
1613
+ throw new Error("AI did not return content for the Fill-In-The-Blanks question.");
1614
+ }
1615
+ } catch (error) {
1616
+ console.error("Error generating Fill-In-The-Blanks question in flow:", error);
1617
+ throw new Error(`Failed to generate Fill-In-The-Blanks question: ${error.message}`);
1618
+ }
1619
+ }
1620
+ );
1621
+
1622
+ // src/ai/flows/generate-matching-question.ts
1623
+ var import_genkit5 = require("genkit");
1624
+ var GenerateMatchingQuestionInputSchema = import_genkit5.z.object({
1625
+ topic: import_genkit5.z.string().describe("The topic for the question."),
1626
+ difficulty: import_genkit5.z.enum(["easy", "medium", "hard"]).optional().default("medium"),
1627
+ numberOfPairs: import_genkit5.z.number().int().min(2).max(8).optional().default(4).describe("Number of pairs to match (2-8)."),
1628
+ shuffleOptions: import_genkit5.z.boolean().optional().default(true).describe("Whether the options should be shuffled for the user."),
1629
+ contextDescription: import_genkit5.z.string().optional().describe("A specific context or scenario for the question, complementing the main topic."),
1630
+ selectedContextId: import_genkit5.z.string().optional().describe("The ID of the selected context, if any.")
1631
+ });
1632
+ var AIMatchingOutputFieldsSchema = import_genkit5.z.object({
1633
+ prompt: import_genkit5.z.string().describe("The overall instruction (e.g., 'Match the terms to their definitions.')."),
1634
+ correctPairs: import_genkit5.z.array(
1635
+ import_genkit5.z.object({
1636
+ promptText: import_genkit5.z.string().describe("The text for a prompt item (e.g., a term)."),
1637
+ optionText: import_genkit5.z.string().describe("The text for the corresponding option item (e.g., its definition).")
1638
+ })
1639
+ ).min(2).describe("An array of objects, each representing a correct prompt-option pair."),
1640
+ explanation: import_genkit5.z.string().optional().describe("General explanation if needed."),
1641
+ points: import_genkit5.z.number().optional().default(10),
1642
+ difficulty: import_genkit5.z.enum(["easy", "medium", "hard"]).optional(),
1643
+ topic: import_genkit5.z.string().optional()
1644
+ });
1645
+ var MatchingQuestionZodSchema = import_genkit5.z.object({
1646
+ id: import_genkit5.z.string(),
1647
+ questionType: import_genkit5.z.literal("matching"),
1648
+ prompt: import_genkit5.z.string(),
1649
+ prompts: import_genkit5.z.array(import_genkit5.z.object({ id: import_genkit5.z.string(), content: import_genkit5.z.string() })),
1650
+ options: import_genkit5.z.array(import_genkit5.z.object({ id: import_genkit5.z.string(), content: import_genkit5.z.string() })),
1651
+ correctAnswerMap: import_genkit5.z.array(import_genkit5.z.object({ promptId: import_genkit5.z.string(), optionId: import_genkit5.z.string() })),
1652
+ shuffleOptions: import_genkit5.z.boolean().optional(),
1653
+ points: import_genkit5.z.number().optional(),
1654
+ explanation: import_genkit5.z.string().optional(),
1655
+ learningObjective: import_genkit5.z.string().optional(),
1656
+ glossary: import_genkit5.z.array(import_genkit5.z.string()).optional(),
1657
+ bloomLevel: import_genkit5.z.string().optional(),
1658
+ difficulty: import_genkit5.z.enum(["easy", "medium", "hard"]).optional(),
1659
+ contextCode: import_genkit5.z.string().optional(),
1660
+ gradeBand: import_genkit5.z.string().optional(),
1661
+ course: import_genkit5.z.string().optional(),
1662
+ category: import_genkit5.z.string().optional(),
1663
+ topic: import_genkit5.z.string().optional()
1664
+ });
1665
+ var GenerateMatchingQuestionOutputSchema = import_genkit5.z.object({
1666
+ question: MatchingQuestionZodSchema.optional().describe("The generated Matching question.")
1667
+ });
1668
+ async function generateMatchingQuestion(input) {
1669
+ return generateMatchingQuestionFlow(input);
1670
+ }
1671
+ var matchingAIPrompt = ai.definePrompt({
1672
+ name: "matchingQuestionGeneratorPrompt",
1673
+ input: { schema: GenerateMatchingQuestionInputSchema },
1674
+ output: { schema: AIMatchingOutputFieldsSchema },
1675
+ prompt: `You are an expert quiz question writer.
1676
+ Generate a single Matching question with exactly {{{numberOfPairs}}} correct pairs.
1677
+ Provide:
1678
+ 1. An overall 'prompt' or instruction.
1679
+ 2. A 'correctPairs' array: each object in this array should contain a 'promptText' and its corresponding 'optionText'. These represent items that correctly match.
1680
+ 3. Optional 'explanation', 'points' (default 10), refined 'topic', and 'difficulty'.
1681
+
1682
+ Topic: {{{topic}}}
1683
+ {{#if contextDescription}}
1684
+ Context: {{{contextDescription}}}
1685
+ {{/if}}
1686
+ Difficulty: {{{difficulty}}}
1687
+ Number of Pairs: {{{numberOfPairs}}}
1688
+
1689
+ Ensure your output strictly matches the requested JSON schema. 'correctPairs' must have {{{numberOfPairs}}} elements.
1690
+ The promptText and optionText within each pair should be distinct and meaningful for a matching question.
1691
+ `
1692
+ });
1693
+ var generateMatchingQuestionFlow = ai.defineFlow(
1694
+ {
1695
+ name: "generateMatchingQuestionFlow",
1696
+ inputSchema: GenerateMatchingQuestionInputSchema,
1697
+ outputSchema: GenerateMatchingQuestionOutputSchema
1698
+ },
1699
+ async (input) => {
1700
+ try {
1701
+ const { output: aiGeneratedContent } = await matchingAIPrompt(input);
1702
+ if (aiGeneratedContent) {
1703
+ if (aiGeneratedContent.correctPairs.length !== input.numberOfPairs) {
1704
+ throw new Error(`AI generated ${aiGeneratedContent.correctPairs.length} pairs, but ${input.numberOfPairs} were requested.`);
1705
+ }
1706
+ const finalPrompts = [];
1707
+ const finalOptions = [];
1708
+ const finalCorrectAnswerMap = [];
1709
+ const promptTextToId = {};
1710
+ const optionTextToId = {};
1711
+ aiGeneratedContent.correctPairs.forEach((pair) => {
1712
+ let promptId = promptTextToId[pair.promptText];
1713
+ if (!promptId) {
1714
+ promptId = generateUniqueId("m_p_");
1715
+ promptTextToId[pair.promptText] = promptId;
1716
+ finalPrompts.push({ id: promptId, content: pair.promptText });
1717
+ }
1718
+ let optionId = optionTextToId[pair.optionText];
1719
+ if (!optionId) {
1720
+ optionId = generateUniqueId("m_o_");
1721
+ optionTextToId[pair.optionText] = optionId;
1722
+ finalOptions.push({ id: optionId, content: pair.optionText });
1723
+ }
1724
+ if (!finalCorrectAnswerMap.find((m) => m.promptId === promptId && m.optionId === optionId)) {
1725
+ finalCorrectAnswerMap.push({ promptId, optionId });
1726
+ }
1727
+ });
1728
+ if (finalPrompts.length < input.numberOfPairs || finalOptions.length < input.numberOfPairs) {
1729
+ console.warn(`AI generated ${finalPrompts.length} unique prompts and ${finalOptions.length} unique options for ${input.numberOfPairs} requested pairs. This might lead to an unbalanced matching question or indicate duplicate content from AI.`);
1730
+ }
1731
+ if (finalCorrectAnswerMap.length !== input.numberOfPairs) {
1732
+ throw new Error(`Could not form the required ${input.numberOfPairs} unique mappings from AI output. AI provided ${finalCorrectAnswerMap.length} valid mappings.`);
1733
+ }
1734
+ const completeQuestion = {
1735
+ id: generateUniqueId("match_ai_"),
1736
+ questionType: "matching",
1737
+ prompt: aiGeneratedContent.prompt,
1738
+ prompts: finalPrompts,
1739
+ options: finalOptions,
1740
+ correctAnswerMap: finalCorrectAnswerMap,
1741
+ shuffleOptions: input.shuffleOptions,
1742
+ explanation: aiGeneratedContent.explanation,
1743
+ points: aiGeneratedContent.points,
1744
+ topic: aiGeneratedContent.topic || input.topic,
1745
+ difficulty: aiGeneratedContent.difficulty || input.difficulty,
1746
+ contextCode: input.contextDescription ? input.selectedContextId : void 0
1747
+ };
1748
+ return { question: completeQuestion };
1749
+ } else {
1750
+ throw new Error("AI did not return content for the Matching question.");
1751
+ }
1752
+ } catch (error) {
1753
+ console.error("Error generating Matching question in flow:", error);
1754
+ throw new Error(`Failed to generate Matching question: ${error.message}`);
1755
+ }
1756
+ }
1757
+ );
1758
+
1759
+ // src/ai/flows/generate-mcq-question.ts
1760
+ var import_genkit7 = require("genkit");
1761
+ var GenerateMCQQuestionInputSchema = import_genkit7.z.object({
1762
+ topic: import_genkit7.z.string().describe("The topic for the question."),
1763
+ difficulty: import_genkit7.z.enum(["easy", "medium", "hard"]).optional().default("medium"),
1764
+ numberOfOptions: import_genkit7.z.number().int().min(2).max(6).optional().default(4).describe("Number of answer options to generate (2-6)."),
1765
+ contextDescription: import_genkit7.z.string().optional().describe("A specific context or scenario for the question, complementing the main topic."),
1766
+ selectedContextId: import_genkit7.z.string().optional().describe("The ID of the selected context, if any.")
1767
+ });
1768
+ var AIMCQOutputFieldsSchema = import_genkit7.z.object({
1769
+ prompt: import_genkit7.z.string().describe("The question statement itself."),
1770
+ options: import_genkit7.z.array(
1771
+ import_genkit7.z.object({
1772
+ tempId: import_genkit7.z.string().describe("A temporary, unique identifier for this option (e.g., 'A', 'B', '1', '2')."),
1773
+ text: import_genkit7.z.string().describe("The text content of this answer option.")
1774
+ })
1775
+ ).min(2).max(6).describe("An array of answer choices that matches the numberOfOptions specified in the input."),
1776
+ correctTempOptionId: import_genkit7.z.string().describe("The temporary ID of the correct option from the generated options array."),
1777
+ explanation: import_genkit7.z.string().optional().describe("A brief explanation of why the answer is correct."),
1778
+ points: import_genkit7.z.number().optional().default(10).describe("Points for a correct answer."),
1779
+ difficulty: import_genkit7.z.enum(["easy", "medium", "hard"]).optional().describe("Assessed difficulty."),
1780
+ topic: import_genkit7.z.string().optional().describe("Refined topic.")
1781
+ });
1782
+ var MultipleChoiceQuestionZodSchema = import_genkit7.z.object({
1783
+ id: import_genkit7.z.string(),
1784
+ questionType: import_genkit7.z.literal("multiple_choice"),
1785
+ prompt: import_genkit7.z.string(),
1786
+ options: import_genkit7.z.array(import_genkit7.z.object({ id: import_genkit7.z.string(), text: import_genkit7.z.string() })),
1787
+ correctAnswerId: import_genkit7.z.string(),
1788
+ points: import_genkit7.z.number().optional(),
1789
+ explanation: import_genkit7.z.string().optional(),
1790
+ learningObjective: import_genkit7.z.string().optional(),
1791
+ glossary: import_genkit7.z.array(import_genkit7.z.string()).optional(),
1792
+ bloomLevel: import_genkit7.z.string().optional(),
1793
+ difficulty: import_genkit7.z.enum(["easy", "medium", "hard"]).optional(),
1794
+ contextCode: import_genkit7.z.string().optional(),
1795
+ gradeBand: import_genkit7.z.string().optional(),
1796
+ course: import_genkit7.z.string().optional(),
1797
+ category: import_genkit7.z.string().optional(),
1798
+ topic: import_genkit7.z.string().optional()
1799
+ });
1800
+ var GenerateMCQQuestionOutputSchema = import_genkit7.z.object({
1801
+ question: MultipleChoiceQuestionZodSchema.optional().describe("The generated Multiple Choice question.")
1802
+ });
1803
+ async function generateMCQQuestion(input) {
1804
+ return generateMCQQuestionFlow(input);
1805
+ }
1806
+ var mcqAIPrompt = ai.definePrompt({
1807
+ name: "mcqQuestionGeneratorPrompt",
1808
+ input: { schema: GenerateMCQQuestionInputSchema },
1809
+ output: { schema: AIMCQOutputFieldsSchema },
1810
+ prompt: `You are an expert quiz question writer.
1811
+ Generate a single Multiple Choice question based on the following inputs.
1812
+ Provide the question statement (prompt), an array of options (each with a unique temporary ID like 'A', 'B', 'C' or 'option_1', 'option_2' and its text), the temporary ID of the correct option, an optional explanation, optional points (default 10), and optionally refine the topic and difficulty.
1813
+ Ensure there are exactly {{{numberOfOptions}}} options. The temporary IDs for options must be unique within the 'options' array and one of them must match 'correctTempOptionId'.
1814
+
1815
+ Topic: {{{topic}}}
1816
+ {{#if contextDescription}}
1817
+ Context: {{{contextDescription}}}
1818
+ {{/if}}
1819
+ Difficulty: {{{difficulty}}}
1820
+ Number of Options: {{{numberOfOptions}}}
1821
+
1822
+ Ensure your output strictly matches the requested JSON schema.
1823
+ `
1824
+ });
1825
+ var generateMCQQuestionFlow = ai.defineFlow(
1826
+ {
1827
+ name: "generateMCQQuestionFlow",
1828
+ inputSchema: GenerateMCQQuestionInputSchema,
1829
+ outputSchema: GenerateMCQQuestionOutputSchema
1830
+ },
1831
+ async (input) => {
1832
+ try {
1833
+ const { output: aiGeneratedContent } = await mcqAIPrompt(input);
1834
+ if (aiGeneratedContent) {
1835
+ const finalOptions = [];
1836
+ const tempIdToFinalIdMap = {};
1837
+ aiGeneratedContent.options.forEach((aiOption) => {
1838
+ const finalId = generateUniqueId("opt_");
1839
+ finalOptions.push({ id: finalId, text: aiOption.text });
1840
+ tempIdToFinalIdMap[aiOption.tempId] = finalId;
1841
+ });
1842
+ const finalCorrectAnswerId = tempIdToFinalIdMap[aiGeneratedContent.correctTempOptionId];
1843
+ if (!finalCorrectAnswerId) {
1844
+ const correctAiOption = aiGeneratedContent.options.find((o) => o.tempId === aiGeneratedContent.correctTempOptionId);
1845
+ if (correctAiOption) {
1846
+ } else {
1847
+ const index = parseInt(aiGeneratedContent.correctTempOptionId);
1848
+ if (!isNaN(index) && index >= 0 && index < finalOptions.length && finalOptions[index].id) {
1849
+ } else {
1850
+ throw new Error(`Correct option ID '${aiGeneratedContent.correctTempOptionId}' is invalid or does not match any generated option tempId.`);
1851
+ }
1852
+ }
1853
+ if (!finalCorrectAnswerId) {
1854
+ throw new Error(`Correct option ID '${aiGeneratedContent.correctTempOptionId}' is invalid or does not match any generated option tempId.`);
1855
+ }
1856
+ }
1857
+ const completeQuestion = {
1858
+ id: generateUniqueId("mcq_ai_"),
1859
+ questionType: "multiple_choice",
1860
+ prompt: aiGeneratedContent.prompt,
1861
+ options: finalOptions,
1862
+ correctAnswerId: finalCorrectAnswerId,
1863
+ explanation: aiGeneratedContent.explanation,
1864
+ points: aiGeneratedContent.points,
1865
+ topic: aiGeneratedContent.topic || input.topic,
1866
+ difficulty: aiGeneratedContent.difficulty || input.difficulty,
1867
+ learningObjective: void 0,
1868
+ glossary: void 0,
1869
+ bloomLevel: void 0,
1870
+ contextCode: input.contextDescription ? input.selectedContextId : void 0,
1871
+ gradeBand: void 0,
1872
+ course: void 0,
1873
+ category: void 0
1874
+ };
1875
+ return { question: completeQuestion };
1876
+ } else {
1877
+ throw new Error("AI did not return content for the MCQ question.");
1878
+ }
1879
+ } catch (error) {
1880
+ console.error("Error generating MCQ question in flow:", error);
1881
+ throw new Error(`Failed to generate MCQ question: ${error.message}`);
1882
+ }
1883
+ }
1884
+ );
1885
+
1886
+ // src/ai/flows/generate-mrq-question.ts
1887
+ var import_genkit9 = require("genkit");
1888
+ var GenerateMRQQuestionInputSchema = import_genkit9.z.object({
1889
+ topic: import_genkit9.z.string().describe("The topic for the question."),
1890
+ difficulty: import_genkit9.z.enum(["easy", "medium", "hard"]).optional().default("medium"),
1891
+ numberOfOptions: import_genkit9.z.number().int().min(2).max(8).optional().default(5).describe("Number of answer options to generate (2-8)."),
1892
+ minCorrectAnswers: import_genkit9.z.number().int().min(1).optional().default(2).describe("Minimum number of correct answers among the options."),
1893
+ maxCorrectAnswers: import_genkit9.z.number().int().min(1).optional().default(3).describe("Maximum number of correct answers (must be <= numberOfOptions)."),
1894
+ contextDescription: import_genkit9.z.string().optional().describe("A specific context or scenario for the question, complementing the main topic."),
1895
+ selectedContextId: import_genkit9.z.string().optional().describe("The ID of the selected context, if any.")
1896
+ });
1897
+ var AIMRQOutputFieldsSchema = import_genkit9.z.object({
1898
+ prompt: import_genkit9.z.string().describe("The question statement itself."),
1899
+ options: import_genkit9.z.array(
1900
+ import_genkit9.z.object({
1901
+ tempId: import_genkit9.z.string().describe("A temporary, unique identifier for this option (e.g., 'A', 'B')."),
1902
+ text: import_genkit9.z.string().describe("The text content of this answer option.")
1903
+ })
1904
+ ).min(2).max(8).describe("An array of answer choices."),
1905
+ correctTempOptionIds: import_genkit9.z.array(import_genkit9.z.string()).min(1).describe("An array of temporary IDs of the correct options from the generated options array."),
1906
+ explanation: import_genkit9.z.string().optional().describe("A brief explanation of why the answers are correct."),
1907
+ points: import_genkit9.z.number().optional().default(10).describe("Points for a correct answer."),
1908
+ difficulty: import_genkit9.z.enum(["easy", "medium", "hard"]).optional().describe("Assessed difficulty."),
1909
+ topic: import_genkit9.z.string().optional().describe("Refined topic.")
1910
+ });
1911
+ var MultipleResponseQuestionZodSchema = import_genkit9.z.object({
1912
+ id: import_genkit9.z.string(),
1913
+ questionType: import_genkit9.z.literal("multiple_response"),
1914
+ prompt: import_genkit9.z.string(),
1915
+ options: import_genkit9.z.array(import_genkit9.z.object({ id: import_genkit9.z.string(), text: import_genkit9.z.string() })),
1916
+ correctAnswerIds: import_genkit9.z.array(import_genkit9.z.string()),
1917
+ points: import_genkit9.z.number().optional(),
1918
+ explanation: import_genkit9.z.string().optional(),
1919
+ learningObjective: import_genkit9.z.string().optional(),
1920
+ glossary: import_genkit9.z.array(import_genkit9.z.string()).optional(),
1921
+ bloomLevel: import_genkit9.z.string().optional(),
1922
+ difficulty: import_genkit9.z.enum(["easy", "medium", "hard"]).optional(),
1923
+ contextCode: import_genkit9.z.string().optional(),
1924
+ gradeBand: import_genkit9.z.string().optional(),
1925
+ course: import_genkit9.z.string().optional(),
1926
+ category: import_genkit9.z.string().optional(),
1927
+ topic: import_genkit9.z.string().optional()
1928
+ });
1929
+ var GenerateMRQQuestionOutputSchema = import_genkit9.z.object({
1930
+ question: MultipleResponseQuestionZodSchema.optional().describe("The generated Multiple Response question.")
1931
+ });
1932
+ async function generateMRQQuestion(input) {
1933
+ if (input.minCorrectAnswers > input.maxCorrectAnswers) {
1934
+ throw new Error("Minimum correct answers cannot exceed maximum correct answers.");
1935
+ }
1936
+ if (input.maxCorrectAnswers > input.numberOfOptions) {
1937
+ throw new Error("Maximum correct answers cannot exceed the total number of options.");
1938
+ }
1939
+ return generateMRQQuestionFlow(input);
1940
+ }
1941
+ var mrqAIPrompt = ai.definePrompt({
1942
+ name: "mrqQuestionGeneratorPrompt",
1943
+ input: { schema: GenerateMRQQuestionInputSchema },
1944
+ output: { schema: AIMRQOutputFieldsSchema },
1945
+ prompt: `You are an expert quiz question writer.
1946
+ Generate a single Multiple Response question based on the following inputs.
1947
+ Provide the question statement (prompt), an array of options (each with a unique temporary ID and its text), an array of the temporary IDs of the correct options, an optional explanation, optional points (default 10), and optionally refine the topic and difficulty.
1948
+ Ensure there are exactly {{{numberOfOptions}}} options.
1949
+ Ensure there are between {{{minCorrectAnswers}}} and {{{maxCorrectAnswers}}} correct options.
1950
+ The temporary IDs for options must be unique within the 'options' array and all IDs in 'correctTempOptionIds' must match one of them.
1951
+
1952
+ Topic: {{{topic}}}
1953
+ {{#if contextDescription}}
1954
+ Context: {{{contextDescription}}}
1955
+ {{/if}}
1956
+ Difficulty: {{{difficulty}}}
1957
+ Number of Options: {{{numberOfOptions}}}
1958
+ Min Correct Answers: {{{minCorrectAnswers}}}
1959
+ Max Correct Answers: {{{maxCorrectAnswers}}}
1960
+
1961
+ Ensure your output strictly matches the requested JSON schema.
1962
+ `
1963
+ });
1964
+ var generateMRQQuestionFlow = ai.defineFlow(
1965
+ {
1966
+ name: "generateMRQQuestionFlow",
1967
+ inputSchema: GenerateMRQQuestionInputSchema,
1968
+ outputSchema: GenerateMRQQuestionOutputSchema
1969
+ },
1970
+ async (input) => {
1971
+ try {
1972
+ const { output: aiGeneratedContent } = await mrqAIPrompt(input);
1973
+ if (aiGeneratedContent) {
1974
+ const finalOptions = [];
1975
+ const tempIdToFinalIdMap = {};
1976
+ aiGeneratedContent.options.forEach((aiOption) => {
1977
+ const finalId = generateUniqueId("opt_mr_");
1978
+ finalOptions.push({ id: finalId, text: aiOption.text });
1979
+ tempIdToFinalIdMap[aiOption.tempId] = finalId;
1980
+ });
1981
+ const finalCorrectAnswerIds = aiGeneratedContent.correctTempOptionIds.map((tempId) => {
1982
+ const finalId = tempIdToFinalIdMap[tempId];
1983
+ if (!finalId) {
1984
+ throw new Error(`AI provided an invalid correctTempOptionId ('${tempId}') that does not map to any generated option.`);
1985
+ }
1986
+ return finalId;
1987
+ });
1988
+ if (finalCorrectAnswerIds.length < input.minCorrectAnswers || finalCorrectAnswerIds.length > input.maxCorrectAnswers) {
1989
+ throw new Error(`AI generated ${finalCorrectAnswerIds.length} correct answers, which is outside the requested range of ${input.minCorrectAnswers}-${input.maxCorrectAnswers}.`);
1990
+ }
1991
+ if (finalOptions.length !== input.numberOfOptions) {
1992
+ throw new Error(`AI generated ${finalOptions.length} options, but ${input.numberOfOptions} were requested.`);
1993
+ }
1994
+ const completeQuestion = {
1995
+ id: generateUniqueId("mrq_ai_"),
1996
+ questionType: "multiple_response",
1997
+ prompt: aiGeneratedContent.prompt,
1998
+ options: finalOptions,
1999
+ correctAnswerIds: finalCorrectAnswerIds,
2000
+ explanation: aiGeneratedContent.explanation,
2001
+ points: aiGeneratedContent.points,
2002
+ topic: aiGeneratedContent.topic || input.topic,
2003
+ difficulty: aiGeneratedContent.difficulty || input.difficulty,
2004
+ learningObjective: void 0,
2005
+ glossary: void 0,
2006
+ bloomLevel: void 0,
2007
+ contextCode: input.contextDescription ? input.selectedContextId : void 0,
2008
+ gradeBand: void 0,
2009
+ course: void 0,
2010
+ category: void 0
2011
+ };
2012
+ return { question: completeQuestion };
2013
+ } else {
2014
+ throw new Error("AI did not return content for the MRQ question.");
2015
+ }
2016
+ } catch (error) {
2017
+ console.error("Error generating MRQ question in flow:", error);
2018
+ throw new Error(`Failed to generate MRQ question: ${error.message}`);
2019
+ }
2020
+ }
2021
+ );
2022
+
2023
+ // src/ai/flows/generate-numeric-question.ts
2024
+ var import_genkit11 = require("genkit");
2025
+ var GenerateNumericQuestionInputSchema = import_genkit11.z.object({
2026
+ topic: import_genkit11.z.string().describe("The topic for the question."),
2027
+ difficulty: import_genkit11.z.enum(["easy", "medium", "hard"]).optional().default("medium"),
2028
+ allowDecimals: import_genkit11.z.boolean().optional().default(true).describe("Whether the answer can be a decimal."),
2029
+ minRange: import_genkit11.z.number().optional().describe("Optional minimum value for the answer."),
2030
+ maxRange: import_genkit11.z.number().optional().describe("Optional maximum value for the answer."),
2031
+ contextDescription: import_genkit11.z.string().optional().describe("A specific context or scenario for the question, complementing the main topic."),
2032
+ selectedContextId: import_genkit11.z.string().optional().describe("The ID of the selected context, if any.")
2033
+ });
2034
+ var AINumericOutputFieldsSchema = import_genkit11.z.object({
2035
+ prompt: import_genkit11.z.string().describe("The question statement that expects a numerical answer."),
2036
+ answer: import_genkit11.z.number().describe("The precise numerical correct answer."),
2037
+ tolerance: import_genkit11.z.number().optional().default(0).describe("The acceptable range of error (plus or minus). E.g., if answer is 10 and tolerance is 0.5, answers between 9.5 and 10.5 are correct. Default is 0 for exact match."),
2038
+ explanation: import_genkit11.z.string().optional().describe("Explanation for the correct answer."),
2039
+ points: import_genkit11.z.number().optional().default(10),
2040
+ difficulty: import_genkit11.z.enum(["easy", "medium", "hard"]).optional(),
2041
+ topic: import_genkit11.z.string().optional()
2042
+ });
2043
+ var NumericQuestionZodSchema = import_genkit11.z.object({
2044
+ id: import_genkit11.z.string(),
2045
+ questionType: import_genkit11.z.literal("numeric"),
2046
+ prompt: import_genkit11.z.string(),
2047
+ answer: import_genkit11.z.number(),
2048
+ tolerance: import_genkit11.z.number().optional(),
2049
+ points: import_genkit11.z.number().optional(),
2050
+ explanation: import_genkit11.z.string().optional(),
2051
+ learningObjective: import_genkit11.z.string().optional(),
2052
+ glossary: import_genkit11.z.array(import_genkit11.z.string()).optional(),
2053
+ bloomLevel: import_genkit11.z.string().optional(),
2054
+ difficulty: import_genkit11.z.enum(["easy", "medium", "hard"]).optional(),
2055
+ contextCode: import_genkit11.z.string().optional(),
2056
+ gradeBand: import_genkit11.z.string().optional(),
2057
+ course: import_genkit11.z.string().optional(),
2058
+ category: import_genkit11.z.string().optional(),
2059
+ topic: import_genkit11.z.string().optional()
2060
+ });
2061
+ var GenerateNumericQuestionOutputSchema = import_genkit11.z.object({
2062
+ question: NumericQuestionZodSchema.optional().describe("The generated Numeric question.")
2063
+ });
2064
+ async function generateNumericQuestion(input) {
2065
+ return generateNumericQuestionFlow(input);
2066
+ }
2067
+ var numericAIPrompt = ai.definePrompt({
2068
+ name: "numericQuestionGeneratorPrompt",
2069
+ input: { schema: GenerateNumericQuestionInputSchema },
2070
+ output: { schema: AINumericOutputFieldsSchema },
2071
+ prompt: `You are an expert quiz question writer.
2072
+ Generate a single Numeric question based on the topic and difficulty.
2073
+ The question should require a numerical answer.
2074
+ Provide the question prompt, the correct numerical answer, an optional tolerance (default 0 for exact match), an optional explanation, points (default 10), and optionally refine the topic/difficulty.
2075
+ {{#if minRange}}The answer should ideally be greater than or equal to {{{minRange}}}.{{/if}}
2076
+ {{#if maxRange}}The answer should ideally be less than or equal to {{{maxRange}}}.{{/if}}
2077
+ The answer should be an integer if 'allowDecimals' is false, otherwise it can be a decimal. Current 'allowDecimals': {{{allowDecimals}}}.
2078
+
2079
+ Topic: {{{topic}}}
2080
+ {{#if contextDescription}}
2081
+ Context: {{{contextDescription}}}
2082
+ {{/if}}
2083
+ Difficulty: {{{difficulty}}}
2084
+
2085
+ Ensure your output strictly matches the requested JSON schema.
2086
+ `
2087
+ });
2088
+ var generateNumericQuestionFlow = ai.defineFlow(
2089
+ {
2090
+ name: "generateNumericQuestionFlow",
2091
+ inputSchema: GenerateNumericQuestionInputSchema,
2092
+ outputSchema: GenerateNumericQuestionOutputSchema
2093
+ },
2094
+ async (input) => {
2095
+ try {
2096
+ const { output: aiGeneratedContent } = await numericAIPrompt(input);
2097
+ if (aiGeneratedContent) {
2098
+ let finalAnswer = aiGeneratedContent.answer;
2099
+ if (!input.allowDecimals) {
2100
+ finalAnswer = Math.round(finalAnswer);
2101
+ }
2102
+ if (input.minRange !== void 0 && finalAnswer < input.minRange) {
2103
+ console.warn(`AI generated answer ${finalAnswer} below minRange ${input.minRange}. Adjusting or re-prompt might be needed for stricter adherence.`);
2104
+ }
2105
+ if (input.maxRange !== void 0 && finalAnswer > input.maxRange) {
2106
+ console.warn(`AI generated answer ${finalAnswer} above maxRange ${input.maxRange}. Adjusting or re-prompt might be needed.`);
2107
+ }
2108
+ const completeQuestion = {
2109
+ id: generateUniqueId("numq_ai_"),
2110
+ questionType: "numeric",
2111
+ prompt: aiGeneratedContent.prompt,
2112
+ answer: finalAnswer,
2113
+ tolerance: aiGeneratedContent.tolerance,
2114
+ explanation: aiGeneratedContent.explanation,
2115
+ points: aiGeneratedContent.points,
2116
+ topic: aiGeneratedContent.topic || input.topic,
2117
+ difficulty: aiGeneratedContent.difficulty || input.difficulty,
2118
+ contextCode: input.contextDescription ? input.selectedContextId : void 0
2119
+ };
2120
+ return { question: completeQuestion };
2121
+ } else {
2122
+ throw new Error("AI did not return content for the Numeric question.");
2123
+ }
2124
+ } catch (error) {
2125
+ console.error("Error generating Numeric question in flow:", error);
2126
+ throw new Error(`Failed to generate Numeric question: ${error.message}`);
2127
+ }
2128
+ }
2129
+ );
2130
+
2131
+ // src/ai/flows/generate-quiz-plan-flow.ts
2132
+ var import_genkit13 = require("genkit");
2133
+ var fullQuizSupportedQuestionTypesArray = [
2134
+ "true_false",
2135
+ "multiple_choice",
2136
+ "multiple_response",
2137
+ "short_answer",
2138
+ "numeric",
2139
+ "fill_in_the_blanks",
2140
+ "sequence",
2141
+ "matching",
2142
+ "drag_and_drop"
2143
+ ];
2144
+ var BloomLevelStringsEnum = import_genkit13.z.enum(["remembering", "understanding", "applying"]);
2145
+ var GenerateQuizPlanInputSchema = import_genkit13.z.object({
2146
+ totalQuestions: import_genkit13.z.number().int().min(1).max(100).describe("Total number of questions for the quiz (1-100)."),
2147
+ topics: import_genkit13.z.array(
2148
+ import_genkit13.z.object({
2149
+ topic: import_genkit13.z.string().min(1, { message: "Topic name cannot be empty." }).describe("Name of the topic."),
2150
+ ratio: import_genkit13.z.number().min(0).max(100).describe("Percentage of questions for this topic (0-100).")
2151
+ })
2152
+ ).min(1, { message: "At least one topic is required." }).describe("List of topics and their desired percentage distribution."),
2153
+ bloomLevels: import_genkit13.z.array(
2154
+ import_genkit13.z.object({
2155
+ level: BloomLevelStringsEnum.describe("Bloom's taxonomy level."),
2156
+ ratio: import_genkit13.z.number().min(0).max(100).describe("Percentage of questions for this Bloom level (0-100).")
2157
+ })
2158
+ ).min(1, { message: "At least one Bloom level distribution is required." }).describe("Desired distribution of Bloom's levels across the quiz."),
2159
+ selectedContextIds: import_genkit13.z.array(import_genkit13.z.string()).optional().describe('Array of IDs for contexts relevant to the quiz (e.g., "THEO_ABS", "REAL_PROB"). These are hints for the AI.'),
2160
+ selectedQuestionTypes: import_genkit13.z.array(import_genkit13.z.enum(fullQuizSupportedQuestionTypesArray)).min(1, { message: "At least one question type must be selected." }).describe("Array of question types to be used in the quiz. Must not include Hotspot or Blockly types.")
2161
+ });
2162
+ var PlannedQuestionSchema = import_genkit13.z.object({
2163
+ plannedTopic: import_genkit13.z.string().describe("The specific topic for this question, derived from the input topics and ratios."),
2164
+ plannedQuestionType: import_genkit13.z.enum(fullQuizSupportedQuestionTypesArray).describe("The specific question type chosen for this question from the allowed types."),
2165
+ plannedBloomLevel: BloomLevelStringsEnum.describe("The Bloom's level assigned to this question based on overall distribution.")
2166
+ });
2167
+ var GenerateQuizPlanOutputSchema = import_genkit13.z.object({
2168
+ quizPlan: import_genkit13.z.array(PlannedQuestionSchema).describe("A detailed plan for each question in the quiz, specifying topic, type, and Bloom level.")
2169
+ });
2170
+ async function generateQuizPlan(input) {
2171
+ const totalTopicRatio = input.topics.reduce((sum, t) => sum + t.ratio, 0);
2172
+ if (Math.abs(totalTopicRatio - 100) > 0.1 && input.topics.length > 0) {
2173
+ throw new Error(`Total topic ratio must be 100%. Current sum: ${totalTopicRatio.toFixed(1)}%`);
2174
+ }
2175
+ const totalBloomRatio = input.bloomLevels.reduce((sum, b) => sum + b.ratio, 0);
2176
+ if (Math.abs(totalBloomRatio - 100) > 0.1) {
2177
+ throw new Error(`Total Bloom level ratio must be 100%. Current sum: ${totalBloomRatio.toFixed(1)}%`);
2178
+ }
2179
+ if (input.totalQuestions <= 0 || input.totalQuestions > 100) {
2180
+ throw new Error("Total questions must be between 1 and 100.");
2181
+ }
2182
+ if (input.selectedQuestionTypes.length === 0) {
2183
+ throw new Error("At least one question type must be selected.");
2184
+ }
2185
+ if (input.selectedQuestionTypes.some((qt) => qt === "hotspot" || qt === "blockly_programming" || qt === "scratch_programming")) {
2186
+ throw new Error("Selected question types must not include Hotspot, Blockly Programming, or Scratch Programming for this flow.");
2187
+ }
2188
+ return generateQuizPlanFlow(input);
2189
+ }
2190
+ var quizPlannerAIPrompt = ai.definePrompt({
2191
+ name: "quizPlannerAIPrompt",
2192
+ input: { schema: GenerateQuizPlanInputSchema },
2193
+ output: { schema: GenerateQuizPlanOutputSchema },
2194
+ prompt: `You are an expert educational content planner specializing in creating balanced and effective quiz blueprints.
2195
+ Your task is to generate a detailed plan for a quiz consisting of exactly {{{totalQuestions}}} questions.
2196
+ The plan should be an array of objects, where each object represents one question and specifies its 'plannedTopic', 'plannedQuestionType', and 'plannedBloomLevel'.
2197
+
2198
+ Constraints and Guidelines:
2199
+ 1. **Total Questions**: The output 'quizPlan' array must contain exactly {{{totalQuestions}}} elements.
2200
+ 2. **Topic Distribution**: Distribute the questions across the following topics according to their specified ratios. Aim to match these ratios as closely as possible.
2201
+ {{#each topics}}
2202
+ - Topic: "{{this.topic}}", Ratio: {{this.ratio}}%
2203
+ {{/each}}
2204
+ 3. **Bloom Level Distribution**: Distribute the questions across the following Bloom's Taxonomy levels according to their specified ratios. This distribution applies to the entire quiz.
2205
+ {{#each bloomLevels}}
2206
+ - Level: "{{this.level}}", Ratio: {{this.ratio}}%
2207
+ {{/each}}
2208
+ 4. **Question Types**: For each planned question, select a 'plannedQuestionType' from the following allowed types: {{#each selectedQuestionTypes}}{{{this}}}{{#unless @last}}, {{/unless}}{{/each}}. Try to use a variety of these selected types throughout the quiz, if appropriate for the topics and Bloom levels. The available types are: ${fullQuizSupportedQuestionTypesArray.map((q) => `'${q}'`).join(", ")}.
2209
+ 5. **Contexts (Informational)**: The user has indicated the following general contexts are relevant to the quiz: {{#if selectedContextIds}}{{#each selectedContextIds}}{{{this}}}{{#unless @last}}, {{/unless}}{{/each}}{{else}}None specified{{/if}}. You don't need to explicitly assign a context ID to each planned question in your output, but keep these in mind when deciding on topic nuances or type suitability, if applicable. The actual detailed question generation later will handle context.
2210
+ 6. **Output Format**: Ensure your output is a JSON object containing a single key "quizPlan", which is an array of question plan objects. Each question plan object must have "plannedTopic" (string), "plannedQuestionType" (one of the allowed enum values specified in guideline 4), and "plannedBloomLevel" (one of the allowed enum values: 'remembering', 'understanding', 'applying').
2211
+
2212
+ Example of a single element in the 'quizPlan' array:
2213
+ {
2214
+ "plannedTopic": "Cellular Respiration Stages",
2215
+ "plannedQuestionType": "multiple_choice",
2216
+ "plannedBloomLevel": "understanding"
2217
+ }
2218
+
2219
+ Carefully calculate the number of questions for each topic and Bloom level based on the total number of questions and the provided ratios. Strive for a balanced and logical distribution.
2220
+ If ratios lead to fractional questions, round to the nearest whole number in a way that maintains the total number of questions.
2221
+ The 'plannedTopic' for each question should be specific and directly related to one of the user-provided topics.
2222
+ The final 'quizPlan' array must have exactly {{{totalQuestions}}} elements.
2223
+ `
2224
+ });
2225
+ var generateQuizPlanFlow = ai.defineFlow(
2226
+ {
2227
+ name: "generateQuizPlanFlow",
2228
+ inputSchema: GenerateQuizPlanInputSchema,
2229
+ outputSchema: GenerateQuizPlanOutputSchema
2230
+ },
2231
+ async (input) => {
2232
+ try {
2233
+ const { output } = await quizPlannerAIPrompt(input);
2234
+ if (!output || !output.quizPlan) {
2235
+ throw new Error("AI did not return a quiz plan.");
2236
+ }
2237
+ if (output.quizPlan.length !== input.totalQuestions) {
2238
+ console.warn(`AI generated a plan for ${output.quizPlan.length} questions, but ${input.totalQuestions} were requested. This is an error in AI adherence.`);
2239
+ throw new Error(`AI planned for ${output.quizPlan.length} questions, but ${input.totalQuestions} were requested. The plan must match the total number of questions.`);
2240
+ }
2241
+ output.quizPlan.forEach((item, index) => {
2242
+ if (!input.selectedQuestionTypes.includes(item.plannedQuestionType)) {
2243
+ throw new Error(`AI planned question ${index + 1} with an invalid or disallowed question type: ${item.plannedQuestionType}`);
2244
+ }
2245
+ const validBloomLevels = ["remembering", "understanding", "applying"];
2246
+ if (!validBloomLevels.includes(item.plannedBloomLevel)) {
2247
+ throw new Error(`AI planned question ${index + 1} with an invalid Bloom level: ${item.plannedBloomLevel}`);
2248
+ }
2249
+ if (!input.topics.some((t) => t.topic === item.plannedTopic)) {
2250
+ console.warn(`AI planned question ${index + 1} with topic "${item.plannedTopic}" which was not in the input topics. This might be an AI interpretation or error.`);
2251
+ }
2252
+ });
2253
+ return output;
2254
+ } catch (error) {
2255
+ console.error("Error generating Quiz Plan in flow:", error);
2256
+ throw new Error(`Failed to generate Quiz Plan: ${error.message}`);
2257
+ }
2258
+ }
2259
+ );
2260
+
2261
+ // src/ai/flows/generate-sequence-question.ts
2262
+ var import_genkit15 = require("genkit");
2263
+ var GenerateSequenceQuestionInputSchema = import_genkit15.z.object({
2264
+ topic: import_genkit15.z.string().describe("The topic for the question."),
2265
+ difficulty: import_genkit15.z.enum(["easy", "medium", "hard"]).optional().default("medium"),
2266
+ numberOfItems: import_genkit15.z.number().int().min(2).max(10).optional().default(4).describe("Number of items to sequence (2-10)."),
2267
+ contextDescription: import_genkit15.z.string().optional().describe("A specific context or scenario for the question, complementing the main topic."),
2268
+ selectedContextId: import_genkit15.z.string().optional().describe("The ID of the selected context, if any.")
2269
+ });
2270
+ var AISequenceOutputFieldsSchema = import_genkit15.z.object({
2271
+ prompt: import_genkit15.z.string().describe("The instruction for sequencing (e.g., 'Arrange the following steps in chronological order.')."),
2272
+ itemsContent: import_genkit15.z.array(import_genkit15.z.string()).min(2).describe("An array of strings, where each string is the content of an item to be sequenced. The order here can be random or pre-sorted by AI, it doesn't matter for this field."),
2273
+ correctOrderContent: import_genkit15.z.array(import_genkit15.z.string()).min(2).describe("An array of strings representing the content of the items in the correct sequence. Each string here MUST match one of the strings in 'itemsContent'."),
2274
+ explanation: import_genkit15.z.string().optional().describe("Explanation for the correct sequence."),
2275
+ points: import_genkit15.z.number().optional().default(10),
2276
+ difficulty: import_genkit15.z.enum(["easy", "medium", "hard"]).optional(),
2277
+ topic: import_genkit15.z.string().optional()
2278
+ });
2279
+ var SequenceQuestionZodSchema = import_genkit15.z.object({
2280
+ id: import_genkit15.z.string(),
2281
+ questionType: import_genkit15.z.literal("sequence"),
2282
+ prompt: import_genkit15.z.string(),
2283
+ items: import_genkit15.z.array(import_genkit15.z.object({ id: import_genkit15.z.string(), content: import_genkit15.z.string() })),
2284
+ correctOrder: import_genkit15.z.array(import_genkit15.z.string()),
2285
+ // Array of item IDs
2286
+ points: import_genkit15.z.number().optional(),
2287
+ explanation: import_genkit15.z.string().optional(),
2288
+ learningObjective: import_genkit15.z.string().optional(),
2289
+ glossary: import_genkit15.z.array(import_genkit15.z.string()).optional(),
2290
+ bloomLevel: import_genkit15.z.string().optional(),
2291
+ difficulty: import_genkit15.z.enum(["easy", "medium", "hard"]).optional(),
2292
+ contextCode: import_genkit15.z.string().optional(),
2293
+ gradeBand: import_genkit15.z.string().optional(),
2294
+ course: import_genkit15.z.string().optional(),
2295
+ category: import_genkit15.z.string().optional(),
2296
+ topic: import_genkit15.z.string().optional()
2297
+ });
2298
+ var GenerateSequenceQuestionOutputSchema = import_genkit15.z.object({
2299
+ question: SequenceQuestionZodSchema.optional().describe("The generated Sequence question.")
2300
+ });
2301
+ async function generateSequenceQuestion(input) {
2302
+ return generateSequenceQuestionFlow(input);
2303
+ }
2304
+ var sequenceAIPrompt = ai.definePrompt({
2305
+ name: "sequenceQuestionGeneratorPrompt",
2306
+ input: { schema: GenerateSequenceQuestionInputSchema },
2307
+ output: { schema: AISequenceOutputFieldsSchema },
2308
+ prompt: `You are an expert quiz question writer.
2309
+ Generate a single Sequence question with exactly {{{numberOfItems}}} items to be ordered.
2310
+ Provide:
2311
+ 1. A 'prompt' or instruction.
2312
+ 2. An 'itemsContent' array: strings for each item (e.g., ["Event A", "Event B", "Event C"]). The order here doesn't matter yet.
2313
+ 3. A 'correctOrderContent' array: strings from 'itemsContent' but in the correct sequence.
2314
+ 4. Optional 'explanation', 'points' (default 10), refined 'topic', and 'difficulty'.
2315
+
2316
+ Topic: {{{topic}}}
2317
+ {{#if contextDescription}}
2318
+ Context: {{{contextDescription}}}
2319
+ {{/if}}
2320
+ Difficulty: {{{difficulty}}}
2321
+ Number of Items: {{{numberOfItems}}}
2322
+
2323
+ Ensure 'itemsContent' and 'correctOrderContent' contain the same set of strings, and 'correctOrderContent' has exactly {{{numberOfItems}}} elements.
2324
+ Ensure your output strictly matches the requested JSON schema.
2325
+ `
2326
+ });
2327
+ var generateSequenceQuestionFlow = ai.defineFlow(
2328
+ {
2329
+ name: "generateSequenceQuestionFlow",
2330
+ inputSchema: GenerateSequenceQuestionInputSchema,
2331
+ outputSchema: GenerateSequenceQuestionOutputSchema
2332
+ },
2333
+ async (input) => {
2334
+ try {
2335
+ const { output: aiGeneratedContent } = await sequenceAIPrompt(input);
2336
+ if (aiGeneratedContent) {
2337
+ if (aiGeneratedContent.itemsContent.length !== input.numberOfItems || aiGeneratedContent.correctOrderContent.length !== input.numberOfItems) {
2338
+ throw new Error(`AI generated ${aiGeneratedContent.itemsContent.length} itemsContent and ${aiGeneratedContent.correctOrderContent.length} correctOrderContent, but ${input.numberOfItems} were requested.`);
2339
+ }
2340
+ const contentToIdMap = {};
2341
+ const finalItems = aiGeneratedContent.itemsContent.map((content) => {
2342
+ const id = generateUniqueId("seqi_");
2343
+ contentToIdMap[content] = id;
2344
+ return { id, content };
2345
+ });
2346
+ const finalCorrectOrder = aiGeneratedContent.correctOrderContent.map((content) => {
2347
+ const id = contentToIdMap[content];
2348
+ if (!id) {
2349
+ throw new Error(`Content "${content}" in 'correctOrderContent' does not match any content in 'itemsContent'.`);
2350
+ }
2351
+ return id;
2352
+ });
2353
+ if (new Set(finalCorrectOrder).size !== finalItems.length) {
2354
+ throw new Error("Correct order does not contain all items from itemsContent uniquely or items are missing/duplicated.");
2355
+ }
2356
+ const completeQuestion = {
2357
+ id: generateUniqueId("seq_ai_"),
2358
+ questionType: "sequence",
2359
+ prompt: aiGeneratedContent.prompt,
2360
+ items: finalItems,
2361
+ correctOrder: finalCorrectOrder,
2362
+ explanation: aiGeneratedContent.explanation,
2363
+ points: aiGeneratedContent.points,
2364
+ topic: aiGeneratedContent.topic || input.topic,
2365
+ difficulty: aiGeneratedContent.difficulty || input.difficulty,
2366
+ contextCode: input.contextDescription ? input.selectedContextId : void 0
2367
+ };
2368
+ return { question: completeQuestion };
2369
+ } else {
2370
+ throw new Error("AI did not return content for the Sequence question.");
2371
+ }
2372
+ } catch (error) {
2373
+ console.error("Error generating Sequence question in flow:", error);
2374
+ throw new Error(`Failed to generate Sequence question: ${error.message}`);
2375
+ }
2376
+ }
2377
+ );
2378
+
2379
+ // src/ai/flows/generate-short-answer-question.ts
2380
+ var import_genkit17 = require("genkit");
2381
+ var GenerateShortAnswerQuestionInputSchema = import_genkit17.z.object({
2382
+ topic: import_genkit17.z.string().describe("The topic for the question."),
2383
+ difficulty: import_genkit17.z.enum(["easy", "medium", "hard"]).optional().default("medium"),
2384
+ isCaseSensitive: import_genkit17.z.boolean().optional().default(false).describe("Whether the answer should be case-sensitive."),
2385
+ contextDescription: import_genkit17.z.string().optional().describe("A specific context or scenario for the question, complementing the main topic."),
2386
+ selectedContextId: import_genkit17.z.string().optional().describe("The ID of the selected context, if any.")
2387
+ });
2388
+ var AIShortAnswerOutputFieldsSchema = import_genkit17.z.object({
2389
+ prompt: import_genkit17.z.string().describe("The question statement."),
2390
+ acceptedAnswers: import_genkit17.z.array(import_genkit17.z.string()).min(1).describe("An array of acceptable short answers. Provide variations if appropriate."),
2391
+ isCaseSensitive: import_genkit17.z.boolean().optional().describe("Should the answer evaluation be case sensitive? Defaults to input or false."),
2392
+ explanation: import_genkit17.z.string().optional().describe("Explanation for the correct answer(s)."),
2393
+ points: import_genkit17.z.number().optional().default(10),
2394
+ difficulty: import_genkit17.z.enum(["easy", "medium", "hard"]).optional(),
2395
+ topic: import_genkit17.z.string().optional()
2396
+ });
2397
+ var ShortAnswerQuestionZodSchema = import_genkit17.z.object({
2398
+ id: import_genkit17.z.string(),
2399
+ questionType: import_genkit17.z.literal("short_answer"),
2400
+ prompt: import_genkit17.z.string(),
2401
+ acceptedAnswers: import_genkit17.z.array(import_genkit17.z.string()),
2402
+ isCaseSensitive: import_genkit17.z.boolean().optional(),
2403
+ points: import_genkit17.z.number().optional(),
2404
+ explanation: import_genkit17.z.string().optional(),
2405
+ learningObjective: import_genkit17.z.string().optional(),
2406
+ glossary: import_genkit17.z.array(import_genkit17.z.string()).optional(),
2407
+ bloomLevel: import_genkit17.z.string().optional(),
2408
+ difficulty: import_genkit17.z.enum(["easy", "medium", "hard"]).optional(),
2409
+ contextCode: import_genkit17.z.string().optional(),
2410
+ gradeBand: import_genkit17.z.string().optional(),
2411
+ course: import_genkit17.z.string().optional(),
2412
+ category: import_genkit17.z.string().optional(),
2413
+ topic: import_genkit17.z.string().optional()
2414
+ });
2415
+ var GenerateShortAnswerQuestionOutputSchema = import_genkit17.z.object({
2416
+ question: ShortAnswerQuestionZodSchema.optional().describe("The generated Short Answer question.")
2417
+ });
2418
+ async function generateShortAnswerQuestion(input) {
2419
+ return generateShortAnswerQuestionFlow(input);
2420
+ }
2421
+ var shortAnswerAIPrompt = ai.definePrompt({
2422
+ name: "shortAnswerQuestionGeneratorPrompt",
2423
+ input: { schema: GenerateShortAnswerQuestionInputSchema },
2424
+ output: { schema: AIShortAnswerOutputFieldsSchema },
2425
+ prompt: `You are an expert quiz question writer.
2426
+ Generate a single Short Answer question based on the following inputs.
2427
+ Provide the question prompt, an array of accepted answer strings, and specify if case sensitivity is important (default to {{{isCaseSensitive}}}).
2428
+ Also include an optional explanation, points (default 10), and optionally refine the topic/difficulty.
2429
+
2430
+ Topic: {{{topic}}}
2431
+ {{#if contextDescription}}
2432
+ Context: {{{contextDescription}}}
2433
+ {{/if}}
2434
+ Difficulty: {{{difficulty}}}
2435
+ Case Sensitive: {{{isCaseSensitive}}}
2436
+
2437
+ Ensure your output strictly matches the requested JSON schema.
2438
+ `
2439
+ });
2440
+ var generateShortAnswerQuestionFlow = ai.defineFlow(
2441
+ {
2442
+ name: "generateShortAnswerQuestionFlow",
2443
+ inputSchema: GenerateShortAnswerQuestionInputSchema,
2444
+ outputSchema: GenerateShortAnswerQuestionOutputSchema
2445
+ },
2446
+ async (input) => {
2447
+ try {
2448
+ const { output: aiGeneratedContent } = await shortAnswerAIPrompt(input);
2449
+ if (aiGeneratedContent) {
2450
+ const completeQuestion = {
2451
+ id: generateUniqueId("saq_ai_"),
2452
+ questionType: "short_answer",
2453
+ prompt: aiGeneratedContent.prompt,
2454
+ acceptedAnswers: aiGeneratedContent.acceptedAnswers,
2455
+ isCaseSensitive: aiGeneratedContent.isCaseSensitive === void 0 ? input.isCaseSensitive : aiGeneratedContent.isCaseSensitive,
2456
+ explanation: aiGeneratedContent.explanation,
2457
+ points: aiGeneratedContent.points,
2458
+ topic: aiGeneratedContent.topic || input.topic,
2459
+ difficulty: aiGeneratedContent.difficulty || input.difficulty,
2460
+ contextCode: input.contextDescription ? input.selectedContextId : void 0
2461
+ };
2462
+ return { question: completeQuestion };
2463
+ } else {
2464
+ throw new Error("AI did not return content for the Short Answer question.");
2465
+ }
2466
+ } catch (error) {
2467
+ console.error("Error generating Short Answer question in flow:", error);
2468
+ throw new Error(`Failed to generate Short Answer question: ${error.message}`);
2469
+ }
2470
+ }
2471
+ );
2472
+
2473
+ // src/ai/flows/generate-true-false-question.ts
2474
+ var import_genkit19 = require("genkit");
2475
+ var GenerateTrueFalseQuestionInputSchema = import_genkit19.z.object({
2476
+ topic: import_genkit19.z.string().describe("The topic for which to generate a True/False question."),
2477
+ difficulty: import_genkit19.z.enum(["easy", "medium", "hard"]).optional().default("medium").describe("The difficulty level of the question (optional)."),
2478
+ contextDescription: import_genkit19.z.string().optional().describe("A specific context or scenario for the question, complementing the main topic."),
2479
+ selectedContextId: import_genkit19.z.string().optional().describe("The ID of the selected context, if any.")
2480
+ });
2481
+ var AIQuestionOutputFieldsSchema = import_genkit19.z.object({
2482
+ prompt: import_genkit19.z.string().describe("The question text itself. This is the statement to be evaluated as true or false."),
2483
+ correctAnswer: import_genkit19.z.boolean().describe("The correct answer for the statement (true if the statement is true, false if it is false)."),
2484
+ explanation: import_genkit19.z.string().optional().describe("A brief explanation of why the answer is correct."),
2485
+ points: import_genkit19.z.number().optional().default(10).describe("Points awarded for a correct answer. Defaults to 10."),
2486
+ difficulty: import_genkit19.z.enum(["easy", "medium", "hard"]).optional().describe("The assessed difficulty of the generated question."),
2487
+ topic: import_genkit19.z.string().optional().describe("The specific topic of the generated question, potentially refined from the input topic.")
2488
+ });
2489
+ var TrueFalseQuestionZodSchema = import_genkit19.z.object({
2490
+ id: import_genkit19.z.string(),
2491
+ questionType: import_genkit19.z.literal("true_false"),
2492
+ prompt: import_genkit19.z.string(),
2493
+ correctAnswer: import_genkit19.z.boolean(),
2494
+ points: import_genkit19.z.number().optional(),
2495
+ explanation: import_genkit19.z.string().optional(),
2496
+ learningObjective: import_genkit19.z.string().optional(),
2497
+ glossary: import_genkit19.z.array(import_genkit19.z.string()).optional(),
2498
+ bloomLevel: import_genkit19.z.string().optional(),
2499
+ difficulty: import_genkit19.z.enum(["easy", "medium", "hard"]).optional(),
2500
+ contextCode: import_genkit19.z.string().optional(),
2501
+ gradeBand: import_genkit19.z.string().optional(),
2502
+ course: import_genkit19.z.string().optional(),
2503
+ category: import_genkit19.z.string().optional(),
2504
+ topic: import_genkit19.z.string().optional()
2505
+ });
2506
+ var GenerateTrueFalseQuestionOutputSchema = import_genkit19.z.object({
2507
+ question: TrueFalseQuestionZodSchema.optional().describe("The generated True/False question.")
2508
+ });
2509
+ async function generateTrueFalseQuestion(input) {
2510
+ return generateTrueFalseQuestionFlow(input);
2511
+ }
2512
+ var trueFalseAIPrompt = ai.definePrompt({
2513
+ name: "trueFalseQuestionGeneratorPrompt",
2514
+ input: { schema: GenerateTrueFalseQuestionInputSchema },
2515
+ output: { schema: AIQuestionOutputFieldsSchema },
2516
+ prompt: `You are an expert quiz question writer.
2517
+ Generate a single True/False question based on the following inputs.
2518
+ The question should be a statement that can be clearly evaluated as true or false.
2519
+ Provide the question statement (prompt), the correct answer (true or false), an optional explanation, optional points (default to 10), and optionally refine the topic and difficulty.
2520
+
2521
+ Topic: {{{topic}}}
2522
+ {{#if contextDescription}}
2523
+ Context: {{{contextDescription}}}
2524
+ {{/if}}
2525
+ Difficulty: {{{difficulty}}}
2526
+
2527
+ Ensure your output strictly matches the requested JSON schema.
2528
+ `
2529
+ });
2530
+ var generateTrueFalseQuestionFlow = ai.defineFlow(
2531
+ {
2532
+ name: "generateTrueFalseQuestionFlow",
2533
+ inputSchema: GenerateTrueFalseQuestionInputSchema,
2534
+ outputSchema: GenerateTrueFalseQuestionOutputSchema
2535
+ },
2536
+ async (input) => {
2537
+ try {
2538
+ const { output: aiGeneratedContent } = await trueFalseAIPrompt(input);
2539
+ if (aiGeneratedContent) {
2540
+ const completeQuestion = {
2541
+ prompt: aiGeneratedContent.prompt,
2542
+ correctAnswer: aiGeneratedContent.correctAnswer,
2543
+ explanation: aiGeneratedContent.explanation,
2544
+ points: aiGeneratedContent.points,
2545
+ topic: aiGeneratedContent.topic || input.topic,
2546
+ difficulty: aiGeneratedContent.difficulty || input.difficulty,
2547
+ id: generateUniqueId("tf_ai_"),
2548
+ questionType: "true_false",
2549
+ learningObjective: void 0,
2550
+ glossary: void 0,
2551
+ bloomLevel: void 0,
2552
+ contextCode: input.contextDescription ? input.selectedContextId : void 0,
2553
+ gradeBand: void 0,
2554
+ course: void 0,
2555
+ category: void 0
2556
+ };
2557
+ return { question: completeQuestion };
2558
+ } else {
2559
+ throw new Error("AI did not return content for the question.");
2560
+ }
2561
+ } catch (error) {
2562
+ console.error("Error generating True/False question in flow:", error);
2563
+ throw new Error(`Failed to generate True/False question: ${error.message}`);
2564
+ }
2565
+ }
2566
+ );
2567
+
2568
+ // src/ai/flows/generateQuestionsFromQuizPlanFlow.ts
2569
+ var import_genkit21 = require("genkit");
2570
+ var internalContextOptions = [
2571
+ { contextId: "THEO_ABS", contextDescription: "L\xFD thuy\u1EBFt/Tr\u1EEBu t\u01B0\u1EE3ng" },
2572
+ { contextId: "SPEC_CASE", contextDescription: "V\xED d\u1EE5 C\u1EE5 th\u1EC3/Tr\u01B0\u1EDDng h\u1EE3p Ri\xEAng" },
2573
+ { contextId: "NAT_OBS", contextDescription: "Hi\u1EC7n t\u01B0\u1EE3ng T\u1EF1 nhi\xEAn/Quan s\xE1t" },
2574
+ { contextId: "TECH_ENG", contextDescription: "\u1EE8ng d\u1EE5ng C\xF4ng ngh\u1EC7/K\u1EF9 thu\u1EADt" },
2575
+ { contextId: "EXP_INV", contextDescription: "Th\xED nghi\u1EC7m/\u0110i\u1EC1u tra Khoa h\u1ECDc" },
2576
+ { contextId: "REAL_PROB", contextDescription: "V\u1EA5n \u0111\u1EC1 Th\u1EF1c t\u1EBF/X\xE3 h\u1ED9i/M\xF4i tr\u01B0\u1EDDng" },
2577
+ { contextId: "DATA_MOD", contextDescription: "Di\u1EC5n gi\u1EA3i D\u1EEF li\u1EC7u/M\xF4 h\xECnh h\xF3a" },
2578
+ { contextId: "HIST_SCI", contextDescription: "L\u1ECBch s\u1EED/Ph\xE1t tri\u1EC3n Khoa h\u1ECDc" },
2579
+ { contextId: "INTERDISC", contextDescription: "Li\xEAn ng\xE0nh (Interdisciplinary)" },
2580
+ { contextId: "HYPO_COMP", contextDescription: "Gi\u1EA3 \u0111\u1ECBnh/So s\xE1nh T\xECnh hu\u1ED1ng" }
2581
+ ];
2582
+ var LocalBloomLevelStringsEnum = import_genkit21.z.enum(["remembering", "understanding", "applying"]);
2583
+ var fullQuizSupportedQuestionTypesArrayForSchema = [
2584
+ "true_false",
2585
+ "multiple_choice",
2586
+ "multiple_response",
2587
+ "short_answer",
2588
+ "numeric",
2589
+ "fill_in_the_blanks",
2590
+ "sequence",
2591
+ "matching",
2592
+ "drag_and_drop"
2593
+ ];
2594
+ var LocalPlannedQuestionSchema = import_genkit21.z.object({
2595
+ plannedTopic: import_genkit21.z.string().describe("The specific topic for this question, derived from the input topics and ratios."),
2596
+ plannedQuestionType: import_genkit21.z.enum(fullQuizSupportedQuestionTypesArrayForSchema).describe("The specific question type chosen for this question from the allowed types."),
2597
+ plannedBloomLevel: LocalBloomLevelStringsEnum.describe("The Bloom's level assigned to this question based on overall distribution.")
2598
+ });
2599
+ var GenerateQuestionsFromQuizPlanInputSchema = import_genkit21.z.object({
2600
+ quizPlan: import_genkit21.z.array(LocalPlannedQuestionSchema).describe("The plan for each question, from Stage 1."),
2601
+ selectedContextIds: import_genkit21.z.array(import_genkit21.z.string()).optional().describe("Array of IDs for contexts relevant to the overall quiz."),
2602
+ customContextInput: import_genkit21.z.string().optional().describe("Custom context description if provided by the user.")
2603
+ });
2604
+ var GenerationErrorSchema = import_genkit21.z.object({
2605
+ plannedQuestionIndex: import_genkit21.z.number().describe("Index of the question in the plan that failed."),
2606
+ plannedTopic: import_genkit21.z.string(),
2607
+ plannedQuestionType: import_genkit21.z.string(),
2608
+ error: import_genkit21.z.string().describe("Error message for this specific question generation.")
2609
+ });
2610
+ var GenerateQuestionsFromQuizPlanOutputSchema = import_genkit21.z.object({
2611
+ generatedQuestions: import_genkit21.z.array(import_genkit21.z.custom((val) => typeof val === "object" && val !== null && "id" in val && "questionType" in val)).describe("Array of successfully generated QuizQuestion objects."),
2612
+ errors: import_genkit21.z.array(GenerationErrorSchema).optional().describe("Array of errors encountered during generation for specific planned questions.")
2613
+ });
2614
+ var calculateCombinedDifficulty = (contextId, bloomLevel, qType, generalCustomContextInput) => {
2615
+ let contextScore = 1;
2616
+ const selectedContext = contextId ? internalContextOptions.find((c) => c.contextId === contextId) : void 0;
2617
+ if (selectedContext) {
2618
+ if (["THEO_ABS", "HIST_SCI"].includes(selectedContext.contextId)) contextScore = 1;
2619
+ else if (["SPEC_CASE", "NAT_OBS", "DATA_MOD", "INTERDISC", "HYPO_COMP"].includes(selectedContext.contextId)) contextScore = 2;
2620
+ else if (["TECH_ENG", "EXP_INV", "REAL_PROB"].includes(selectedContext.contextId)) contextScore = 3;
2621
+ } else if (generalCustomContextInput && generalCustomContextInput.trim()) {
2622
+ contextScore = 2;
2623
+ }
2624
+ let bloomScore = 1;
2625
+ if (bloomLevel === "understanding") bloomScore = 2;
2626
+ else if (bloomLevel === "applying") bloomScore = 3;
2627
+ let questionTypeScore = 1;
2628
+ switch (qType) {
2629
+ case "true_false":
2630
+ case "multiple_choice":
2631
+ case "short_answer":
2632
+ questionTypeScore = 1;
2633
+ break;
2634
+ case "matching":
2635
+ case "fill_in_the_blanks":
2636
+ case "numeric":
2637
+ questionTypeScore = 2;
2638
+ break;
2639
+ case "sequence":
2640
+ case "multiple_response":
2641
+ case "drag_and_drop":
2642
+ questionTypeScore = 3;
2643
+ break;
2644
+ default:
2645
+ questionTypeScore = 1;
2646
+ }
2647
+ const totalScore = bloomScore + contextScore + questionTypeScore;
2648
+ if (totalScore <= 4) return "easy";
2649
+ if (totalScore <= 6) return "medium";
2650
+ return "hard";
2651
+ };
2652
+ async function generateQuestionsFromQuizPlan(input) {
2653
+ return generateQuestionsFromQuizPlanFlow(input);
2654
+ }
2655
+ var generateQuestionsFromQuizPlanFlow = ai.defineFlow(
2656
+ {
2657
+ name: "generateQuestionsFromQuizPlanFlow",
2658
+ inputSchema: GenerateQuestionsFromQuizPlanInputSchema,
2659
+ outputSchema: GenerateQuestionsFromQuizPlanOutputSchema
2660
+ },
2661
+ async ({ quizPlan, selectedContextIds, customContextInput }) => {
2662
+ var _a, _b;
2663
+ const generatedQuestions = [];
2664
+ const errors = [];
2665
+ for (let i = 0; i < quizPlan.length; i++) {
2666
+ const plannedQ = quizPlan[i];
2667
+ let question = void 0;
2668
+ let generationError = null;
2669
+ let contextDescriptionForAI = void 0;
2670
+ let contextIdForDifficultyCalc = plannedQ.plannedContextId;
2671
+ if (plannedQ.plannedContextId && plannedQ.plannedContextId !== "__custom__") {
2672
+ contextDescriptionForAI = (_a = internalContextOptions.find((c) => c.contextId === plannedQ.plannedContextId)) == null ? void 0 : _a.contextDescription;
2673
+ } else if (selectedContextIds && selectedContextIds.length > 0 && selectedContextIds[0] !== "__custom__") {
2674
+ contextDescriptionForAI = (_b = internalContextOptions.find((c) => c.contextId === selectedContextIds[0])) == null ? void 0 : _b.contextDescription;
2675
+ if (!contextIdForDifficultyCalc) contextIdForDifficultyCalc = selectedContextIds[0];
2676
+ } else if (customContextInput && customContextInput.trim()) {
2677
+ contextDescriptionForAI = customContextInput.trim();
2678
+ if (!contextIdForDifficultyCalc) contextIdForDifficultyCalc = "__custom__";
2679
+ }
2680
+ const difficultyForAI = calculateCombinedDifficulty(
2681
+ contextIdForDifficultyCalc,
2682
+ plannedQ.plannedBloomLevel,
2683
+ plannedQ.plannedQuestionType,
2684
+ contextDescriptionForAI
2685
+ );
2686
+ const baseQuestionInput = {
2687
+ topic: plannedQ.plannedTopic,
2688
+ difficulty: difficultyForAI,
2689
+ contextDescription: contextDescriptionForAI,
2690
+ selectedContextId: plannedQ.plannedContextId
2691
+ };
2692
+ try {
2693
+ switch (plannedQ.plannedQuestionType) {
2694
+ case "true_false":
2695
+ ({ question } = await generateTrueFalseQuestion(baseQuestionInput));
2696
+ break;
2697
+ case "multiple_choice":
2698
+ ({ question } = await generateMCQQuestion(__spreadProps(__spreadValues({}, baseQuestionInput), { numberOfOptions: 4 })));
2699
+ break;
2700
+ case "multiple_response":
2701
+ ({ question } = await generateMRQQuestion(__spreadProps(__spreadValues({}, baseQuestionInput), { numberOfOptions: 5, minCorrectAnswers: 2, maxCorrectAnswers: 3 })));
2702
+ break;
2703
+ case "short_answer":
2704
+ ({ question } = await generateShortAnswerQuestion(__spreadProps(__spreadValues({}, baseQuestionInput), { isCaseSensitive: false })));
2705
+ break;
2706
+ case "numeric":
2707
+ ({ question } = await generateNumericQuestion(__spreadProps(__spreadValues({}, baseQuestionInput), { allowDecimals: true })));
2708
+ break;
2709
+ case "fill_in_the_blanks":
2710
+ ({ question } = await generateFillInTheBlanksQuestion(__spreadProps(__spreadValues({}, baseQuestionInput), { numberOfBlanks: 2, isCaseSensitive: false })));
2711
+ break;
2712
+ case "sequence":
2713
+ ({ question } = await generateSequenceQuestion(__spreadProps(__spreadValues({}, baseQuestionInput), { numberOfItems: 4 })));
2714
+ break;
2715
+ case "matching":
2716
+ ({ question } = await generateMatchingQuestion(__spreadProps(__spreadValues({}, baseQuestionInput), { numberOfPairs: 4 })));
2717
+ break;
2718
+ case "drag_and_drop":
2719
+ generationError = `Question type "drag_and_drop" is planned but generation is not yet supported.`;
2720
+ console.warn(`Skipping Drag and Drop question generation for topic: ${plannedQ.plannedTopic}. Not implemented.`);
2721
+ break;
2722
+ default:
2723
+ generationError = `Question type "${plannedQ.plannedQuestionType}" is not supported for automated generation in this flow.`;
2724
+ }
2725
+ if (question) {
2726
+ question.topic = plannedQ.plannedTopic;
2727
+ question.bloomLevel = plannedQ.plannedBloomLevel;
2728
+ question.difficulty = difficultyForAI;
2729
+ question.contextCode = plannedQ.plannedContextId || (contextDescriptionForAI ? (selectedContextIds == null ? void 0 : selectedContextIds[0]) || "__custom__" : void 0);
2730
+ if (question.points === void 0) question.points = 10;
2731
+ generatedQuestions.push(question);
2732
+ } else if (!generationError) {
2733
+ generationError = `AI did not return a question object for ${plannedQ.plannedQuestionType}.`;
2734
+ }
2735
+ } catch (e) {
2736
+ generationError = e.message || `Unknown error generating ${plannedQ.plannedQuestionType} question for topic ${plannedQ.plannedTopic}.`;
2737
+ }
2738
+ if (generationError) {
2739
+ console.error(`Error during Stage 2 generation for planned question index ${i}: ${generationError}`);
2740
+ errors.push({
2741
+ plannedQuestionIndex: i,
2742
+ plannedTopic: plannedQ.plannedTopic,
2743
+ plannedQuestionType: plannedQ.plannedQuestionType,
2744
+ error: generationError
2745
+ });
2746
+ }
2747
+ }
2748
+ return { generatedQuestions, errors: errors.length > 0 ? errors : void 0 };
2749
+ }
2750
+ );
2751
+
2752
+ // src/utils/utils.ts
2753
+ var import_clsx = require("clsx");
2754
+ var import_tailwind_merge = require("tailwind-merge");
2755
+ function cn(...inputs) {
2756
+ return (0, import_tailwind_merge.twMerge)((0, import_clsx.clsx)(inputs));
2757
+ }
2758
+ // Annotate the CommonJS export names for ESM import in node:
2759
+ 0 && (module.exports = {
2760
+ QuizEngine,
2761
+ SCORMService,
2762
+ cn,
2763
+ emptyQuiz,
2764
+ exportQuizAsSCORMZip,
2765
+ generateFillInTheBlanksQuestion,
2766
+ generateLauncherHTML,
2767
+ generateMCQQuestion,
2768
+ generateMRQQuestion,
2769
+ generateMatchingQuestion,
2770
+ generateNumericQuestion,
2771
+ generateQuestionsFromQuizPlan,
2772
+ generateQuizPlan,
2773
+ generateSCORMManifest,
2774
+ generateSequenceQuestion,
2775
+ generateShortAnswerQuestion,
2776
+ generateTrueFalseQuestion,
2777
+ generateUniqueId,
2778
+ sampleQuiz
2779
+ });