@learnosity/lib-qti-converter 0.12.5 → 0.12.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/package.json +3 -2
  2. package/packages/cli/dist/batchProcessors-DU1HwpHY.js +3753 -0
  3. package/packages/cli/dist/batchProcessors-DU1HwpHY.js.map +1 -0
  4. package/packages/cli/dist/batchWorker.js +1 -1
  5. package/packages/cli/dist/{learnosityToQti-D3Xxswaf.js → learnosityToQti-BSbH3jyx.js} +4 -4
  6. package/packages/cli/dist/{learnosityToQti-D3Xxswaf.js.map → learnosityToQti-BSbH3jyx.js.map} +1 -1
  7. package/packages/cli/dist/{learnosityToQtiPackage-D-hlZ9yI.js → learnosityToQtiPackage-B0xRzYmy.js} +4 -5
  8. package/packages/cli/dist/{learnosityToQtiPackage-D-hlZ9yI.js.map → learnosityToQtiPackage-B0xRzYmy.js.map} +1 -1
  9. package/packages/cli/dist/main.js +6 -6
  10. package/packages/cli/dist/main.js.map +1 -1
  11. package/packages/cli/dist/nodeFileAccess-BkzSHCOh.js +291 -0
  12. package/packages/cli/dist/nodeFileAccess-BkzSHCOh.js.map +1 -0
  13. package/packages/cli/dist/{pathUtils-CwZnJ55s.js → pathUtils-B9yPTlVF.js} +3 -148
  14. package/packages/cli/dist/pathUtils-B9yPTlVF.js.map +1 -0
  15. package/packages/cli/dist/{qtiPackageToLearnosity-CHDga9lI.js → qtiPackageToLearnosity-C7JaaUDU.js} +5 -5
  16. package/packages/cli/dist/{qtiPackageToLearnosity-CHDga9lI.js.map → qtiPackageToLearnosity-C7JaaUDU.js.map} +1 -1
  17. package/packages/cli/dist/{qtiToLearnosity-BkYlsuH0.js → qtiToLearnosity-CYoG2aIX.js} +5 -5
  18. package/packages/cli/dist/{qtiToLearnosity-BkYlsuH0.js.map → qtiToLearnosity-CYoG2aIX.js.map} +1 -1
  19. package/packages/cli/dist/resolveOptions-CW80R2EQ.js +2879 -0
  20. package/packages/cli/dist/resolveOptions-CW80R2EQ.js.map +1 -0
  21. package/packages/cli/dist/{resolveOptions-CZ4dw2gp.js → table-DjOn2Tsk.js} +2450 -2823
  22. package/packages/cli/dist/table-DjOn2Tsk.js.map +1 -0
  23. package/packages/core/dist/index.d.ts +24 -0
  24. package/packages/core/dist/index.js +54 -9
  25. package/packages/core/dist/node.d.ts +24 -0
  26. package/packages/core/dist/node.js +246 -13
  27. package/packages/cli/dist/batchProcessors-C8k2v0o_.js +0 -217
  28. package/packages/cli/dist/batchProcessors-C8k2v0o_.js.map +0 -1
  29. package/packages/cli/dist/pathUtils-CwZnJ55s.js.map +0 -1
  30. package/packages/cli/dist/resolveOptions-CZ4dw2gp.js.map +0 -1
  31. package/packages/cli/dist/table-DYcNeyJ_.js +0 -2306
  32. package/packages/cli/dist/table-DYcNeyJ_.js.map +0 -1
@@ -0,0 +1,3753 @@
1
+ import { _ as mapLearnosityToAst, b as parseLearnosityItem, c as transformForwardAssetUrlsInXml, d as generateItemReference, f as md5hex, g as downgradeAssessmentTestToQti21, h as escapeXml$3, l as convertQtiAssessmentItemToLearnosity, m as serializeAssessmentItem, n as formatDiagnosticsSummaryTable, p as require_saxes, s as writeDiagnostics, u as parseMetadataTags, v as normalizeXhtmlVoidElements, x as DiagnosticCode, y as sanitizeHtmlContent } from "./table-DjOn2Tsk.js";
2
+ import { t as nodeFileAccess } from "./nodeFileAccess-BkzSHCOh.js";
3
+ import * as path$1 from "node:path";
4
+ import { join, relative, sep } from "node:path";
5
+ import * as fs$1 from "node:fs";
6
+ import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
7
+ import * as crypto from "node:crypto";
8
+ import { createRequire } from "module";
9
+ import { mkdir, writeFile } from "node:fs/promises";
10
+ //#region ../core/src/qti-package/pathSafety.ts
11
+ var import_saxes = require_saxes();
12
+ /**
13
+ * ZIP entry path safety validation (zip-slip protection)
14
+ */
15
+ /**
16
+ * Validates that a ZIP entry path is safe to extract
17
+ *
18
+ * Rejects:
19
+ * - Absolute paths (starting with / or drive letter)
20
+ * - Path traversal attempts (..)
21
+ * - Backslashes (normalizes to forward slashes)
22
+ *
23
+ * @param entryPath Raw path from ZIP entry
24
+ * @returns Normalized safe path, or null if unsafe
25
+ */
26
+ function validateZipEntryPath(entryPath) {
27
+ if (entryPath.startsWith("/")) return null;
28
+ if (/^[a-zA-Z]:/.test(entryPath)) return null;
29
+ const normalized = entryPath.replace(/\\/g, "/");
30
+ if (normalized.includes("..")) return null;
31
+ return normalized;
32
+ }
33
+ //#endregion
34
+ //#region ../core/src/qti-package/parseManifest.ts
35
+ /**
36
+ * IMS manifest XML parsing using saxes
37
+ */
38
+ /**
39
+ * Helper to build an opening XML tag string from tag name and attributes
40
+ */
41
+ function buildOpeningTag(name, attributes) {
42
+ const attrs = Object.entries(attributes).map(([k, v]) => `${k}="${escapeXmlAttribute(v)}"`).join(" ");
43
+ return attrs ? `<${name} ${attrs}>` : `<${name}>`;
44
+ }
45
+ /**
46
+ * Escape XML attribute value
47
+ */
48
+ function escapeXmlAttribute(value) {
49
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
50
+ }
51
+ /**
52
+ * Sanitize malformed XML by fixing common encoding issues
53
+ * This handles cases where content creators didn't properly escape special characters
54
+ */
55
+ function sanitizeXml$1(xml) {
56
+ return xml.replace(/&(?![a-zA-Z]+;|#[0-9]+;|#x[0-9a-fA-F]+;)/g, "&amp;");
57
+ }
58
+ /**
59
+ * Parses an imsmanifest.xml file to extract resources
60
+ *
61
+ * Extracts:
62
+ * - Resource identifier, type, href
63
+ * - Associated file references
64
+ * - Metadata XML blocks (for LOM metadata extraction)
65
+ *
66
+ * @param manifestXml XML content of imsmanifest.xml
67
+ * @param zipPath Path to ZIP (for diagnostics)
68
+ * @returns Parsed resources and diagnostics
69
+ */
70
+ function parseManifest(manifestXml, zipPath) {
71
+ const diagnostics = [];
72
+ const resources = [];
73
+ try {
74
+ const sanitizedXml = sanitizeXml$1(manifestXml);
75
+ const parser = new import_saxes.SaxesParser();
76
+ let currentResource = null;
77
+ let currentFiles = [];
78
+ let currentDependencies = [];
79
+ let inResources = false;
80
+ let inMetadata = false;
81
+ let metadataDepth = 0;
82
+ const metadataBuffer = [];
83
+ parser.on("opentag", (tag) => {
84
+ if (inMetadata) {
85
+ metadataBuffer.push(buildOpeningTag(tag.name, tag.attributes));
86
+ metadataDepth++;
87
+ return;
88
+ }
89
+ if (tag.name === "resources") {
90
+ inResources = true;
91
+ return;
92
+ }
93
+ if (!inResources) return;
94
+ if (tag.name === "resource") {
95
+ currentResource = {
96
+ identifier: tag.attributes.identifier || "",
97
+ type: tag.attributes.type || "",
98
+ href: tag.attributes.href || ""
99
+ };
100
+ currentFiles = [];
101
+ currentDependencies = [];
102
+ } else if (tag.name === "metadata" && currentResource) {
103
+ inMetadata = true;
104
+ metadataDepth = 0;
105
+ metadataBuffer.length = 0;
106
+ } else if (tag.name === "file" && currentResource) {
107
+ const href = tag.attributes.href;
108
+ if (href) currentFiles.push(href);
109
+ } else if (tag.name === "dependency" && currentResource) {
110
+ const identifierref = tag.attributes.identifierref;
111
+ if (identifierref) currentDependencies.push({ identifierref });
112
+ }
113
+ });
114
+ parser.on("text", (text) => {
115
+ if (inMetadata) metadataBuffer.push(text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"));
116
+ });
117
+ parser.on("closetag", (tag) => {
118
+ if (inMetadata) {
119
+ if (tag.name === "metadata" && metadataDepth === 0) {
120
+ if (currentResource) {
121
+ const metadataContent = metadataBuffer.join("").trim();
122
+ if (metadataContent) currentResource.metadataXml = metadataContent;
123
+ }
124
+ inMetadata = false;
125
+ metadataBuffer.length = 0;
126
+ } else {
127
+ metadataBuffer.push(`</${tag.name}>`);
128
+ metadataDepth--;
129
+ }
130
+ return;
131
+ }
132
+ if (tag.name === "resources") inResources = false;
133
+ else if (tag.name === "resource" && currentResource) {
134
+ if (currentResource.identifier && currentResource.type && currentResource.href) resources.push({
135
+ identifier: currentResource.identifier,
136
+ type: currentResource.type,
137
+ href: currentResource.href,
138
+ files: currentFiles.length > 0 ? currentFiles : void 0,
139
+ dependencies: currentDependencies.length > 0 ? currentDependencies : void 0,
140
+ metadataXml: currentResource.metadataXml
141
+ });
142
+ currentResource = null;
143
+ currentFiles = [];
144
+ currentDependencies = [];
145
+ }
146
+ });
147
+ parser.write(sanitizedXml).close();
148
+ } catch (error) {
149
+ diagnostics.push({
150
+ level: "error",
151
+ code: DiagnosticCode.PACKAGE_MANIFEST_INVALID_XML,
152
+ message: `Failed to parse manifest XML: ${error instanceof Error ? error.message : String(error)}`,
153
+ file: zipPath,
154
+ context: { manifest: "imsmanifest.xml" }
155
+ });
156
+ }
157
+ return {
158
+ resources,
159
+ diagnostics
160
+ };
161
+ }
162
+ //#endregion
163
+ //#region ../core/src/qti-package/uuid.ts
164
+ /**
165
+ * Dependency-free RFC 4122 version-4 UUID generator.
166
+ *
167
+ * Uses the Web Crypto RNG (`globalThis.crypto.getRandomValues`), which is
168
+ * available in browsers and in Node.js (>= 18) without importing `node:crypto`,
169
+ * so the package stays bundler/browser friendly.
170
+ */
171
+ const HEX = Array.from({ length: 256 }, (_, i) => (i + 256).toString(16).slice(1));
172
+ /** Generate a random (version 4) UUID string. */
173
+ function uuidv4() {
174
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
175
+ globalThis.crypto.getRandomValues(bytes);
176
+ bytes[6] = bytes[6] & 15 | 64;
177
+ bytes[8] = bytes[8] & 63 | 128;
178
+ return HEX[bytes[0]] + HEX[bytes[1]] + HEX[bytes[2]] + HEX[bytes[3]] + "-" + HEX[bytes[4]] + HEX[bytes[5]] + "-" + HEX[bytes[6]] + HEX[bytes[7]] + "-" + HEX[bytes[8]] + HEX[bytes[9]] + "-" + HEX[bytes[10]] + HEX[bytes[11]] + HEX[bytes[12]] + HEX[bytes[13]] + HEX[bytes[14]] + HEX[bytes[15]];
179
+ }
180
+ //#endregion
181
+ //#region ../core/src/qti-package/buildManifest.ts
182
+ /**
183
+ * IMS manifest XML generation
184
+ */
185
+ /**
186
+ * Generates a minimal valid imsmanifest.xml from resources
187
+ *
188
+ * Creates IMS Content Packaging 1.2 compliant manifest with:
189
+ * - Standard namespace declarations
190
+ * - Organization structure (empty)
191
+ * - Resources section with provided resources
192
+ *
193
+ * The QTI metadata namespace and schema location are version-aware so the
194
+ * manifest references the QTI 2.1 or QTI 2.2 metadata schema matching the
195
+ * resource types in the package.
196
+ *
197
+ * @param resources Array of resources to include
198
+ * @param version QTI version of the package ('2.1' or '2.2'). Defaults to '2.2'.
199
+ * @returns XML string for imsmanifest.xml
200
+ */
201
+ function buildManifest(resources, version = "2.2") {
202
+ const lines = [];
203
+ const qtiVersionTag = version === "2.1" ? "v2p1" : "v2p2";
204
+ const qtiMetadataNs = `http://www.imsglobal.org/xsd/imsqti_metadata_${qtiVersionTag}`;
205
+ const qtiMetadataXsd = `http://www.imsglobal.org/xsd/qti/qti${qtiVersionTag}/imsqti_metadata_${qtiVersionTag}.xsd`;
206
+ lines.push("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
207
+ const manifestId = `MANIFEST-${uuidv4()}`;
208
+ lines.push("<manifest");
209
+ lines.push(` identifier="${manifestId}"`);
210
+ lines.push(" xmlns=\"http://www.imsglobal.org/xsd/imscp_v1p1\"");
211
+ lines.push(" xmlns:imsmd=\"http://www.imsglobal.org/xsd/imsmd_v1p2\"");
212
+ lines.push(` xmlns:imsqti="${qtiMetadataNs}"`);
213
+ lines.push(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
214
+ lines.push(" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/imscp_v1p1 http://www.imsglobal.org/xsd/imscp_v1p1.xsd");
215
+ lines.push(" http://www.imsglobal.org/xsd/imsmd_v1p2 http://www.imsglobal.org/xsd/imsmd_v1p2p2.xsd");
216
+ lines.push(` ${qtiMetadataNs} ${qtiMetadataXsd}">`);
217
+ lines.push(" <metadata>");
218
+ lines.push(` <schema>QTIv${version} Package</schema>`);
219
+ lines.push(" <schemaversion>1.0.0</schemaversion>");
220
+ lines.push(" </metadata>");
221
+ lines.push(" <organizations/>");
222
+ lines.push(" <resources>");
223
+ for (const resource of resources) {
224
+ lines.push(` <resource identifier="${escapeXml$2(resource.identifier)}" type="${escapeXml$2(resource.type)}" href="${escapeXml$2(resource.href)}">`);
225
+ if (resource.files && resource.files.length > 0) for (const file of resource.files) lines.push(` <file href="${escapeXml$2(file)}"/>`);
226
+ if (resource.dependencies && resource.dependencies.length > 0) for (const dep of resource.dependencies) lines.push(` <dependency identifierref="${escapeXml$2(dep.identifierref)}"/>`);
227
+ lines.push(" </resource>");
228
+ }
229
+ lines.push(" </resources>");
230
+ lines.push("</manifest>");
231
+ return lines.join("\n");
232
+ }
233
+ /**
234
+ * Escapes XML special characters
235
+ */
236
+ function escapeXml$2(str) {
237
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
238
+ }
239
+ //#endregion
240
+ //#region ../core/src/qti-package/testDependencies.ts
241
+ /**
242
+ * Extract item and stimulus dependencies from QTI assessmentTest XML,
243
+ * and map hrefs to manifest resource identifiers.
244
+ */
245
+ /**
246
+ * Extract assessmentItemRef and assessmentStimulusRef hrefs from test XML
247
+ */
248
+ function extractTestDependencies(testXml) {
249
+ const itemHrefs = [];
250
+ const stimulusHrefs = [];
251
+ const parser = new import_saxes.SaxesParser({ xmlns: true });
252
+ parser.on("opentag", (tag) => {
253
+ const localName = tag.local ?? tag.name;
254
+ if (localName === "assessmentItemRef") {
255
+ const href = getAttr$1(tag, "href");
256
+ if (href) itemHrefs.push(href);
257
+ } else if (localName === "assessmentStimulusRef") {
258
+ const href = getAttr$1(tag, "href");
259
+ if (href) stimulusHrefs.push(href);
260
+ }
261
+ });
262
+ try {
263
+ parser.write(testXml).close();
264
+ } catch {
265
+ return {
266
+ itemHrefs: [],
267
+ stimulusHrefs: []
268
+ };
269
+ }
270
+ return {
271
+ itemHrefs,
272
+ stimulusHrefs
273
+ };
274
+ }
275
+ /**
276
+ * Helper to get attribute value from saxes tag
277
+ */
278
+ function getAttr$1(tag, name) {
279
+ const attr = tag.attributes[name];
280
+ if (!attr) return;
281
+ if (typeof attr === "string") return attr;
282
+ return attr.value;
283
+ }
284
+ /**
285
+ * Map href to manifest resource identifier
286
+ *
287
+ * Examples:
288
+ * - "items/abc123.xml" -> "item_abc123"
289
+ * - "stimuli/stimulus_xyz789.xml" -> "stimulus_xyz789"
290
+ * - "../../items/abc123.xml" -> "item_abc123"
291
+ */
292
+ function mapHrefToResourceId(href) {
293
+ const cleanHref = href.replace(/^(\.\.\/)+/, "");
294
+ const itemMatch = cleanHref.match(/^items\/(.+)\.xml$/);
295
+ if (itemMatch) return `item_${itemMatch[1]}`;
296
+ const stimulusMatch = cleanHref.match(/^stimuli\/(.+)\.xml$/);
297
+ if (stimulusMatch) {
298
+ const stimulusId = stimulusMatch[1];
299
+ return stimulusId.startsWith("stimulus_") ? stimulusId : `stimulus_${stimulusId}`;
300
+ }
301
+ return null;
302
+ }
303
+ //#endregion
304
+ //#region ../core/src/learnosity-mapper/mapActivityToTest.ts
305
+ /**
306
+ * Maps Learnosity Activity to QTI 2.2 assessmentTest AST (TASK 005)
307
+ */
308
+ /**
309
+ * Maps a Learnosity Activity to QTI assessmentTest AST
310
+ *
311
+ * Supports two activity formats:
312
+ * 1. Flat activities with itemRefs array - creates single section
313
+ * 2. Section-based activities with sections array - creates multiple sections
314
+ *
315
+ * For section-based activities:
316
+ * - Each Learnosity section maps to a QTI assessmentSection
317
+ * - Section navigation.allowBackward determines testPart navigationMode
318
+ * - Section time.maxTime maps to section-level timeLimits
319
+ * - Section shuffleItems maps to section shuffle attribute
320
+ *
321
+ * @param activity - Activity data with reference and item list or sections
322
+ * @returns { test?, diagnostics[] }
323
+ */
324
+ function mapActivityToTest(activity) {
325
+ const diagnostics = [];
326
+ const hasSections = activity.sections && activity.sections.length > 0;
327
+ const hasItems = activity.itemRefs && activity.itemRefs.length > 0;
328
+ if (!hasSections && !hasItems) {
329
+ diagnostics.push({
330
+ code: DiagnosticCode.LRN_ACTIVITY_NO_ITEMS,
331
+ level: "error",
332
+ message: `Activity has no items: ${activity.reference}`,
333
+ file: activity.reference
334
+ });
335
+ return { diagnostics };
336
+ }
337
+ let sections;
338
+ let navigationMode = "nonlinear";
339
+ if (hasSections) {
340
+ const result = mapSectionsToQti(activity.sections, activity.title, diagnostics);
341
+ sections = result.sections;
342
+ navigationMode = result.navigationMode;
343
+ } else {
344
+ const itemRefs = activity.itemRefs.map((itemRef) => ({
345
+ identifier: itemRef,
346
+ href: `items/${itemRef}.xml`
347
+ }));
348
+ sections = [{
349
+ identifier: "section_1",
350
+ title: activity.title ?? "Section 1",
351
+ visible: true,
352
+ itemRefs
353
+ }];
354
+ }
355
+ const testPart = {
356
+ identifier: "testPart_1",
357
+ navigationMode,
358
+ submissionMode: "simultaneous",
359
+ sections
360
+ };
361
+ const test = {
362
+ identifier: activity.reference,
363
+ title: activity.title ?? activity.reference,
364
+ testParts: [testPart]
365
+ };
366
+ if (!hasSections && activity.maxTime !== void 0 && activity.maxTime > 0) test.timeLimits = {
367
+ maxTime: activity.maxTime,
368
+ allowLateSubmission: true
369
+ };
370
+ return {
371
+ test,
372
+ diagnostics
373
+ };
374
+ }
375
+ /**
376
+ * Map Learnosity sections to QTI assessmentSections
377
+ *
378
+ * @param learnositySections - Array of Learnosity sections
379
+ * @param activityTitle - Optional activity title for section naming
380
+ * @param diagnostics - Diagnostic array to append to
381
+ * @returns { sections, navigationMode }
382
+ */
383
+ function mapSectionsToQti(learnositySections, activityTitle, diagnostics) {
384
+ const sections = [];
385
+ let hasLinearSection = false;
386
+ for (let i = 0; i < learnositySections.length; i++) {
387
+ const lrnSection = learnositySections[i];
388
+ const sectionIndex = i + 1;
389
+ if (!lrnSection.items || lrnSection.items.length === 0) {
390
+ diagnostics.push({
391
+ code: DiagnosticCode.LRN_ACTIVITY_NO_ITEMS,
392
+ level: "warning",
393
+ message: `Section ${sectionIndex} has no items`,
394
+ file: `section_${sectionIndex}`
395
+ });
396
+ continue;
397
+ }
398
+ const itemRefs = lrnSection.items.map((itemRef) => ({
399
+ identifier: itemRef,
400
+ href: `items/${itemRef}.xml`
401
+ }));
402
+ const section = {
403
+ identifier: `section_${sectionIndex}`,
404
+ title: `${activityTitle ?? "Activity"} - Section ${sectionIndex}`,
405
+ visible: true,
406
+ itemRefs
407
+ };
408
+ if (lrnSection.config?.navigation?.allowBackward === false) hasLinearSection = true;
409
+ if (lrnSection.config?.shuffleItems === true) section.shuffle = true;
410
+ if (lrnSection.config?.time?.maxTime !== void 0 && lrnSection.config.time.maxTime > 0) section.timeLimits = {
411
+ maxTime: lrnSection.config.time.maxTime,
412
+ allowLateSubmission: lrnSection.config.time.limitType !== "hard"
413
+ };
414
+ sections.push(section);
415
+ }
416
+ return {
417
+ sections,
418
+ navigationMode: hasLinearSection ? "linear" : "nonlinear"
419
+ };
420
+ }
421
+ //#endregion
422
+ //#region ../core/src/learnosity-mapper/mapStimulusToAst.ts
423
+ /**
424
+ * Convert Learnosity sharedpassage to QTI assessmentStimulus
425
+ */
426
+ function mapSharedpassageToStimulus(reference, data, diagnostics) {
427
+ const contentResult = sanitizeHtmlContent(data.content, `features[${reference}].content`);
428
+ diagnostics.push(...contentResult.diagnostics);
429
+ let stimulusBody = contentResult.content;
430
+ stimulusBody = convertMediaSpansToObjects(stimulusBody, diagnostics);
431
+ if (data.heading) {
432
+ const headingResult = sanitizeHtmlContent(data.heading, `features[${reference}].heading`);
433
+ diagnostics.push(...headingResult.diagnostics);
434
+ stimulusBody = `<h2 class="lrn-hdg">${headingResult.content}</h2>` + stimulusBody;
435
+ }
436
+ stimulusBody = `<div class="lrn-stimulus">${stimulusBody}</div>`;
437
+ const instructorStimulus = data.instructor_stimulus && data.instructor_stimulus.trim() !== "" ? data.instructor_stimulus : void 0;
438
+ const stimulus = {
439
+ identifier: sanitizeIdentifier(reference),
440
+ title: data.heading,
441
+ instructorStimulus,
442
+ stimulusBody
443
+ };
444
+ diagnostics.push({
445
+ level: "info",
446
+ code: DiagnosticCode.QTI_STIMULUS_CREATED,
447
+ message: `Created stimulus resource for sharedpassage: ${reference}`,
448
+ file: `features[${reference}]`
449
+ });
450
+ return stimulus;
451
+ }
452
+ /**
453
+ * Convert Learnosity media feature spans to QTI <object> elements
454
+ *
455
+ * Input patterns:
456
+ * - <span class="learnosity-feature" data-type="audioplayer" data-src="URL"></span>
457
+ * - <span class="learnosity-feature" data-type="videoplayer" data-src="URL"></span>
458
+ */
459
+ function convertMediaSpansToObjects(html, diagnostics) {
460
+ const mediaPattern = /<span[^>]+class="[^"]*learnosity-feature[^"]*"[^>]+data-type="(audioplayer|videoplayer)"[^>]+data-src="([^"]+)"[^>]*><\/span>/g;
461
+ let result = html;
462
+ const matches = [...html.matchAll(mediaPattern)];
463
+ for (const match of matches) {
464
+ const mediaType = match[1];
465
+ const src = match[2];
466
+ const fullMatch = match[0];
467
+ const mimeType = getMimeType(src, mediaType);
468
+ if (isRemoteUrl(src)) diagnostics.push({
469
+ level: "warning",
470
+ code: DiagnosticCode.CONTENT_REMOTE_ASSET_NOT_PACKAGED,
471
+ message: `Remote ${mediaType === "audioplayer" ? "audio" : "video"} file not packaged: ${src}`,
472
+ file: "content"
473
+ });
474
+ const mediaClass = mediaType === "audioplayer" ? "lrn-media-audio" : "lrn-media-video";
475
+ const downloadText = mediaType === "audioplayer" ? "Download audio" : "Download video";
476
+ const objectHtml = `<div class="lrn-media ${mediaClass}">
477
+ <object data="${escapeXml$1(src)}" type="${mimeType}"></object>
478
+ <p><a href="${escapeXml$1(src)}">${downloadText}</a></p>
479
+ </div>`;
480
+ result = result.replace(fullMatch, objectHtml);
481
+ }
482
+ return result;
483
+ }
484
+ /**
485
+ * Determine MIME type from URL and media type
486
+ */
487
+ function getMimeType(url, mediaType) {
488
+ const ext = url.split(".").pop()?.toLowerCase();
489
+ if (mediaType === "audioplayer") switch (ext) {
490
+ case "mp3": return "audio/mpeg";
491
+ case "ogg": return "audio/ogg";
492
+ case "wav": return "audio/wav";
493
+ case "m4a": return "audio/mp4";
494
+ default: return "audio/mpeg";
495
+ }
496
+ else switch (ext) {
497
+ case "mp4": return "video/mp4";
498
+ case "webm": return "video/webm";
499
+ case "ogg": return "video/ogg";
500
+ default: return "video/mp4";
501
+ }
502
+ }
503
+ /**
504
+ * Check if URL is remote (http/https)
505
+ */
506
+ function isRemoteUrl(url) {
507
+ return url.startsWith("http://") || url.startsWith("https://");
508
+ }
509
+ /**
510
+ * Sanitize identifier for QTI NCName compliance
511
+ */
512
+ function sanitizeIdentifier(ref) {
513
+ let id = ref;
514
+ id = id.replace(/[^a-zA-Z0-9_.-]/g, "_");
515
+ return id;
516
+ }
517
+ /**
518
+ * Escape XML special characters
519
+ */
520
+ function escapeXml$1(text) {
521
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
522
+ }
523
+ //#endregion
524
+ //#region ../core/src/qti-serializer/serializeAssessmentStimulus.ts
525
+ /**
526
+ * Serialize QtiAssessmentStimulus to HTML (for embedding via object element)
527
+ * Returns just the stimulus body HTML without QTI XML wrapper
528
+ */
529
+ function serializeAssessmentStimulusAsHtml(stimulus) {
530
+ const normalized = normalizeXhtmlVoidElements(stimulus.stimulusBody, "stimulus.stimulusBody");
531
+ let bodyContent = "";
532
+ if (stimulus.instructorStimulus && stimulus.instructorStimulus.trim() !== "") {
533
+ const instructorNormalized = normalizeXhtmlVoidElements(stimulus.instructorStimulus, "stimulus.instructorStimulus");
534
+ bodyContent += `<div class="rubricBlock" data-view="author proctor scorer testConstructor tutor">\n${instructorNormalized.content}\n</div>\n`;
535
+ }
536
+ bodyContent += normalized.content;
537
+ return `<!DOCTYPE html>
538
+ <html lang="en">
539
+ <head>
540
+ <meta charset="UTF-8">
541
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
542
+ <title>${escapeXml(stimulus.title ?? "Stimulus")}</title>
543
+ </head>
544
+ <body>
545
+ ${bodyContent}
546
+ </body>
547
+ </html>`;
548
+ }
549
+ /**
550
+ * Escape XML special characters
551
+ */
552
+ function escapeXml(text) {
553
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
554
+ }
555
+ //#endregion
556
+ //#region ../core/src/qti-serializer/serializeAssessmentTest.ts
557
+ /**
558
+ * Serializes QTI 2.2/2.1 assessmentTest AST to XML (TASK 005, TASK 008)
559
+ */
560
+ /**
561
+ * Serialize a QTI assessmentTest to XML string
562
+ *
563
+ * @param test - QTI assessmentTest AST (in 2.2 format)
564
+ * @param options - Serialization options
565
+ * @returns { xml?, diagnostics[] }
566
+ */
567
+ function serializeAssessmentTest(test, options = {}) {
568
+ const diagnostics = [];
569
+ const pretty = options.pretty ?? false;
570
+ const version = options.version ?? "2.2";
571
+ let workingTest = test;
572
+ if (version === "2.1") {
573
+ const downgradeResult = downgradeAssessmentTestToQti21(test);
574
+ workingTest = downgradeResult.ast;
575
+ diagnostics.push(...downgradeResult.diagnostics);
576
+ diagnostics.push({
577
+ code: DiagnosticCode.QTI_DOWNGRADE_NAMESPACE,
578
+ level: "info",
579
+ file: "assessmentTest",
580
+ message: "Downgraded to QTI 2.1"
581
+ });
582
+ }
583
+ return {
584
+ xml: buildAssessmentTestXml(workingTest, pretty, version),
585
+ diagnostics
586
+ };
587
+ }
588
+ /**
589
+ * Build complete assessmentTest XML structure
590
+ */
591
+ function buildAssessmentTestXml(test, pretty, version) {
592
+ const indent = pretty ? " " : "";
593
+ const indent2 = pretty ? " " : "";
594
+ const indent3 = pretty ? " " : "";
595
+ const parts = [];
596
+ parts.push("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
597
+ if (pretty) parts.push("\n");
598
+ const namespace = version === "2.1" ? "http://www.imsglobal.org/xsd/imsqti_v2p1" : "http://www.imsglobal.org/xsd/imsqti_v2p2";
599
+ const schemaLocation = version === "2.1" ? "http://www.imsglobal.org/xsd/imsqti_v2p1 http://www.imsglobal.org/xsd/qti/qtiv2p1/imsqti_v2p1.xsd" : "http://www.imsglobal.org/xsd/imsqti_v2p2 http://www.imsglobal.org/xsd/qti/qtiv2p2/imsqti_v2p2.xsd";
600
+ parts.push(`<assessmentTest xmlns="${namespace}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="${schemaLocation}" identifier="${escapeXml$3(test.identifier)}" title="${escapeXml$3(test.title)}">`);
601
+ if (pretty) parts.push("\n");
602
+ if (test.timeLimits) {
603
+ parts.push(`${indent}<timeLimits maxTime="${test.timeLimits.maxTime}" allowLateSubmission="${test.timeLimits.allowLateSubmission}"/>`);
604
+ if (pretty) parts.push("\n");
605
+ }
606
+ for (const testPart of test.testParts) {
607
+ parts.push(`${indent}<testPart identifier="${escapeXml$3(testPart.identifier)}" navigationMode="${testPart.navigationMode}" submissionMode="${testPart.submissionMode}">`);
608
+ if (pretty) parts.push("\n");
609
+ for (const section of testPart.sections) {
610
+ let sectionAttrs = `identifier="${escapeXml$3(section.identifier)}" title="${escapeXml$3(section.title)}" visible="${section.visible}"`;
611
+ if (section.shuffle !== void 0) sectionAttrs += ` shuffle="${section.shuffle}"`;
612
+ parts.push(`${indent2}<assessmentSection ${sectionAttrs}>`);
613
+ if (pretty) parts.push("\n");
614
+ if (section.timeLimits) {
615
+ parts.push(`${indent3}<timeLimits maxTime="${section.timeLimits.maxTime}" allowLateSubmission="${section.timeLimits.allowLateSubmission}"/>`);
616
+ if (pretty) parts.push("\n");
617
+ }
618
+ if (section.selection) {
619
+ let selectionAttrs = `select="${section.selection.select}"`;
620
+ if (section.selection.withReplacement !== void 0) selectionAttrs += ` withReplacement="${section.selection.withReplacement}"`;
621
+ parts.push(`${indent3}<selection ${selectionAttrs}/>`);
622
+ if (pretty) parts.push("\n");
623
+ }
624
+ for (const itemRef of section.itemRefs) {
625
+ parts.push(`${indent3}<assessmentItemRef identifier="${escapeXml$3(itemRef.identifier)}" href="${escapeXml$3(itemRef.href)}"/>`);
626
+ if (pretty) parts.push("\n");
627
+ }
628
+ parts.push(`${indent2}</assessmentSection>`);
629
+ if (pretty) parts.push("\n");
630
+ }
631
+ parts.push(`${indent}</testPart>`);
632
+ if (pretty) parts.push("\n");
633
+ }
634
+ parts.push("</assessmentTest>");
635
+ if (pretty) parts.push("\n");
636
+ return parts.join("");
637
+ }
638
+ //#endregion
639
+ //#region ../core/src/learnosity-mapper/convertActivity.ts
640
+ /**
641
+ * Convert Learnosity Activity to QTI (TASK 005, TASK 008, TASK 023)
642
+ *
643
+ * Orchestrates the conversion pipeline:
644
+ * - Activity → assessmentTest
645
+ * - Items → assessmentItems
646
+ * - Sharedpassages → assessmentStimulus resources
647
+ */
648
+ /**
649
+ * Convert a Learnosity Activity to QTI 2.2/2.1 assessmentTest + items
650
+ *
651
+ * @param bundle - Loaded Learnosity bundle
652
+ * @param activityRef - Activity reference to convert
653
+ * @param options - Conversion options
654
+ * @returns { testXml?, test?, items[], diagnostics[] }
655
+ */
656
+ function convertActivity(bundle, activityRef, options = {}) {
657
+ const diagnostics = [];
658
+ const items = [];
659
+ const stimuli = [];
660
+ const stimuliByRef = /* @__PURE__ */ new Map();
661
+ const pretty = options.pretty ?? false;
662
+ const version = options.version ?? "2.2";
663
+ const customAssetUrl = options.customAssetUrl;
664
+ const itemRefs = bundle.activityItemRefs.get(activityRef);
665
+ if (!itemRefs) {
666
+ diagnostics.push({
667
+ code: DiagnosticCode.LRN_ACTIVITY_FILE_MISSING,
668
+ level: "error",
669
+ message: `Activity not found in bundle: ${activityRef}`,
670
+ file: activityRef
671
+ });
672
+ return {
673
+ items,
674
+ stimuli,
675
+ diagnostics
676
+ };
677
+ }
678
+ for (const itemRef of itemRefs) {
679
+ const itemJson = bundle.itemsJsonByRef.get(itemRef);
680
+ const itemFilename = bundle.itemRefToFilename.get(itemRef) ?? `items/${md5hex(itemRef)}.json`;
681
+ if (!itemJson) {
682
+ diagnostics.push({
683
+ code: DiagnosticCode.LRN_ITEM_FILE_MISSING,
684
+ level: "error",
685
+ message: `Item not found in bundle: ${itemRef}`,
686
+ file: itemFilename
687
+ });
688
+ continue;
689
+ }
690
+ const parseResult = parseLearnosityItem(itemJson);
691
+ const itemDiagnostics = parseResult.diagnostics.map((d) => ({
692
+ ...d,
693
+ file: itemFilename
694
+ }));
695
+ diagnostics.push(...itemDiagnostics);
696
+ if (parseResult.diagnostics.some((d) => d.code === DiagnosticCode.LRN_UNSUPPORTED_QUESTION_TYPE)) continue;
697
+ if (!parseResult.model) continue;
698
+ collectStimuliFromFeatures(parseResult.model.features, stimuliByRef, stimuli, diagnostics, customAssetUrl);
699
+ const mapResult = mapLearnosityToAst(parseResult.model);
700
+ const mapDiagnostics = mapResult.diagnostics.map((d) => ({
701
+ ...d,
702
+ file: itemFilename
703
+ }));
704
+ diagnostics.push(...mapDiagnostics);
705
+ if (!mapResult.ast) continue;
706
+ const serializeResult = serializeAssessmentItem(mapResult.ast, {
707
+ pretty,
708
+ version
709
+ });
710
+ const serializeDiagnostics = serializeResult.diagnostics.filter((d) => d.level === "error" || d.code !== DiagnosticCode.QTI_NO_CORRECT_RESPONSE).map((d) => ({
711
+ ...d,
712
+ file: itemFilename
713
+ }));
714
+ diagnostics.push(...serializeDiagnostics);
715
+ if (serializeResult.xml) items.push({
716
+ reference: itemRef,
717
+ xml: transformForwardAssetUrlsInXml(serializeResult.xml, customAssetUrl),
718
+ ast: mapResult.ast,
719
+ diagnostics: [
720
+ ...parseResult.diagnostics,
721
+ ...mapResult.diagnostics,
722
+ ...serializeResult.diagnostics
723
+ ]
724
+ });
725
+ }
726
+ const successfulItemRefs = new Set(items.map((i) => i.reference));
727
+ for (const itemRef of itemRefs) if (!successfulItemRefs.has(itemRef)) {
728
+ const itemFilename = bundle.itemRefToFilename.get(itemRef) ?? `items/${md5hex(itemRef)}.json`;
729
+ if (!diagnostics.some((d) => d.level === "error" && d.file === itemFilename)) diagnostics.push({
730
+ code: DiagnosticCode.LRN_ITEM_CONVERSION_FAILED,
731
+ level: "error",
732
+ message: `Item failed to convert: ${itemRef}`,
733
+ file: itemFilename
734
+ });
735
+ }
736
+ if (items.length === 0) {
737
+ diagnostics.push({
738
+ code: DiagnosticCode.LRN_ACTIVITY_NO_ITEMS,
739
+ level: "error",
740
+ message: `No items successfully converted for activity: ${activityRef}`,
741
+ file: activityRef
742
+ });
743
+ return {
744
+ items,
745
+ stimuli,
746
+ diagnostics
747
+ };
748
+ }
749
+ const { activityTitle, maxTime, sections } = extractActivityConfig(bundle, activityRef, items);
750
+ const activityData = {
751
+ reference: activityRef,
752
+ title: activityTitle ?? activityRef
753
+ };
754
+ if (sections && sections.length > 0) activityData.sections = sections;
755
+ else {
756
+ activityData.itemRefs = items.map((item) => item.reference);
757
+ activityData.maxTime = maxTime;
758
+ }
759
+ const testResult = mapActivityToTest(activityData);
760
+ diagnostics.push(...testResult.diagnostics);
761
+ if (!testResult.test) return {
762
+ items,
763
+ stimuli,
764
+ diagnostics
765
+ };
766
+ const testXmlResult = serializeAssessmentTest(testResult.test, {
767
+ pretty,
768
+ version
769
+ });
770
+ diagnostics.push(...testXmlResult.diagnostics);
771
+ return {
772
+ testXml: testXmlResult.xml,
773
+ test: testResult.test,
774
+ items,
775
+ stimuli,
776
+ diagnostics
777
+ };
778
+ }
779
+ /**
780
+ * Collect sharedpassage features and convert them to stimulus entries (deduplicated)
781
+ */
782
+ function collectStimuliFromFeatures(features, stimuliByRef, stimuli, diagnostics, customAssetUrl) {
783
+ for (const feature of features) {
784
+ if (feature.type !== "sharedpassage" || !feature.data || typeof feature.data !== "object" || !("type" in feature.data)) continue;
785
+ if (stimuliByRef.has(feature.reference)) continue;
786
+ const stimulusAst = mapSharedpassageToStimulus(feature.reference, feature.data, diagnostics);
787
+ if (stimulusAst) {
788
+ const stimulusEntry = {
789
+ reference: feature.reference,
790
+ xml: transformForwardAssetUrlsInXml(serializeAssessmentStimulusAsHtml(stimulusAst), customAssetUrl)
791
+ };
792
+ stimuliByRef.set(feature.reference, stimulusEntry);
793
+ stimuli.push(stimulusEntry);
794
+ }
795
+ }
796
+ }
797
+ /**
798
+ * Extract activity config (title, max_time, sections) from bundle activity JSON
799
+ */
800
+ function extractActivityConfig(bundle, activityRef, items) {
801
+ const activityJson = bundle.activitiesJsonByRef.get(activityRef);
802
+ if (!activityJson || typeof activityJson !== "object" || !("data" in activityJson)) return {};
803
+ const data = activityJson.data;
804
+ if (!data || typeof data !== "object") return {};
805
+ let sections;
806
+ if ("sections" in data && Array.isArray(data.sections) && data.sections.length > 0) sections = extractSections(data.sections, items);
807
+ let activityTitle;
808
+ let maxTime;
809
+ if ("config" in data && data.config && typeof data.config === "object") {
810
+ const config = data.config;
811
+ if ("title" in config && typeof config.title === "string") activityTitle = config.title;
812
+ if ("time" in config && config.time && typeof config.time === "object" && "max_time" in config.time) {
813
+ const maxTimeValue = config.time.max_time;
814
+ if (typeof maxTimeValue === "number" && maxTimeValue > 0) maxTime = maxTimeValue;
815
+ }
816
+ }
817
+ return {
818
+ activityTitle,
819
+ maxTime,
820
+ sections
821
+ };
822
+ }
823
+ /**
824
+ * Extract filtered item references from raw items array
825
+ */
826
+ function extractSectionItems(rawItems, convertedItemRefs) {
827
+ return rawItems.filter((item) => {
828
+ const ref = typeof item === "string" ? item : item?.reference ?? item?.id;
829
+ return ref && convertedItemRefs.has(ref);
830
+ }).map((item) => typeof item === "string" ? item : item?.reference ?? item?.id);
831
+ }
832
+ /**
833
+ * Extract navigation config from raw section config
834
+ */
835
+ function extractNavigationConfig(rawConfig) {
836
+ if (!rawConfig.navigation || typeof rawConfig.navigation !== "object") return;
837
+ if ("allow_backward" in rawConfig.navigation) return { allowBackward: rawConfig.navigation.allow_backward === true };
838
+ }
839
+ /**
840
+ * Extract time config from raw section config
841
+ */
842
+ function extractTimeConfig(rawConfig) {
843
+ if (!rawConfig.time || typeof rawConfig.time !== "object") return;
844
+ const time = rawConfig.time;
845
+ if (!("max_time" in time) || typeof time.max_time !== "number" || time.max_time <= 0) return;
846
+ const result = { maxTime: time.max_time };
847
+ if (time.limit_type === "hard" || time.limit_type === "soft") result.limitType = time.limit_type;
848
+ return result;
849
+ }
850
+ /**
851
+ * Extract section config from raw config object
852
+ */
853
+ function extractSectionConfig(rawConfig) {
854
+ if (!rawConfig || typeof rawConfig !== "object") return;
855
+ const config = {};
856
+ const navigation = extractNavigationConfig(rawConfig);
857
+ if (navigation) config.navigation = navigation;
858
+ const time = extractTimeConfig(rawConfig);
859
+ if (time) config.time = time;
860
+ if (rawConfig.configuration && typeof rawConfig.configuration === "object" && rawConfig.configuration.shuffle_items === true) config.shuffleItems = true;
861
+ return Object.keys(config).length > 0 ? config : void 0;
862
+ }
863
+ /**
864
+ * Extract sections from Learnosity activity data
865
+ *
866
+ * Maps Learnosity section format to LearnositySection interface:
867
+ * - items array
868
+ * - config.navigation.allow_backward → config.navigation.allowBackward
869
+ * - config.time.max_time → config.time.maxTime
870
+ * - config.time.limit_type → config.time.limitType
871
+ * - config.configuration.shuffle_items → config.shuffleItems
872
+ *
873
+ * @param rawSections - Raw sections array from activity JSON
874
+ * @param convertedItems - List of successfully converted items (to filter out unconverted items)
875
+ * @returns Array of LearnositySection objects
876
+ */
877
+ function extractSections(rawSections, convertedItems) {
878
+ const sections = [];
879
+ const convertedItemRefs = new Set(convertedItems.map((item) => item.reference));
880
+ for (const rawSection of rawSections) {
881
+ if (!rawSection || typeof rawSection !== "object") continue;
882
+ if (!Array.isArray(rawSection.items)) continue;
883
+ const items = extractSectionItems(rawSection.items, convertedItemRefs);
884
+ if (items.length === 0) continue;
885
+ const section = { items };
886
+ const config = extractSectionConfig(rawSection.config);
887
+ if (config) section.config = config;
888
+ sections.push(section);
889
+ }
890
+ return sections;
891
+ }
892
+ //#endregion
893
+ //#region ../core/src/learnosity-mapper/sanitizeFolderName.ts
894
+ /**
895
+ * Sanitize activity reference for use as folder name
896
+ */
897
+ /**
898
+ * Sanitize a string for use as a folder name
899
+ *
900
+ * Rules:
901
+ * - Trim whitespace
902
+ * - Replace path separators (/ \) with _
903
+ * - Replace any characters not in [A-Za-z0-9._-] with _
904
+ * - Collapse multiple _ to single _
905
+ * - If empty after sanitization, use fallback
906
+ *
907
+ * @param input - Raw string to sanitize
908
+ * @param fallback - Fallback value if sanitization produces empty string
909
+ * @returns Sanitized folder name
910
+ */
911
+ function sanitizeFolderName(input, fallback = "activity") {
912
+ let result = input.trim();
913
+ result = result.replace(/[/\\]/g, "_");
914
+ result = result.replace(/[^A-Za-z0-9._-]/g, "_");
915
+ result = result.replace(/_+/g, "_");
916
+ result = result.replace(/^_+|_+$/g, "");
917
+ if (!result) result = fallback;
918
+ return result;
919
+ }
920
+ /**
921
+ * Ensure folder name uniqueness by tracking used names
922
+ *
923
+ * @param desiredName - Desired folder name
924
+ * @param usedNames - Set of already-used folder names
925
+ * @returns Unique folder name (may have suffix like _2, _3)
926
+ */
927
+ function ensureUniqueFolderName(desiredName, usedNames) {
928
+ let uniqueName = desiredName;
929
+ let counter = 2;
930
+ while (usedNames.has(uniqueName)) {
931
+ uniqueName = `${desiredName}_${counter}`;
932
+ counter++;
933
+ }
934
+ usedNames.add(uniqueName);
935
+ return uniqueName;
936
+ }
937
+ //#endregion
938
+ //#region ../core/src/learnosity-mapper/mergeActivityPackage.ts
939
+ /**
940
+ * Rewrite item/stimulus/asset hrefs inside an assessmentTest that has been moved
941
+ * into tests/<folderName>/ (two levels deep) so they resolve against the package root.
942
+ */
943
+ function rewriteTestHrefs(testXml) {
944
+ testXml = testXml.replace(/(<assessmentItemRef[^>]*href=")items\//g, "$1../../items/");
945
+ testXml = testXml.replace(/(<assessmentStimulusRef[^>]*href=")stimuli\//g, "$1../../stimuli/");
946
+ testXml = testXml.replace(/(<stylesheet[^>]*href=")assets\//g, "$1../../assets/");
947
+ return testXml;
948
+ }
949
+ /**
950
+ * Merge one activity's package (`packageResult`) into the combined `pkg`.
951
+ *
952
+ * The activity's assessmentTest is relocated to tests/<folderName>/assessmentTest.xml,
953
+ * its hrefs rewritten, and the test resource is given ordered dependencies
954
+ * (normalize CSS first, then stimulus then item resources). Item resources gain a
955
+ * dependency on the normalize CSS. Duplicate resources (by identifier) are skipped.
956
+ */
957
+ function mergeActivityPackage(pkg, folderName, packageResult, addedResourceIds) {
958
+ const actPackage = packageResult.package;
959
+ if (!actPackage) return;
960
+ const testFileName = `tests/${folderName}/assessmentTest.xml`;
961
+ const testEntry = actPackage.entries.get("assessmentTest.xml");
962
+ if (testEntry) {
963
+ const testXml = rewriteTestHrefs(testEntry.data.toString("utf-8"));
964
+ pkg.entries.set(testFileName, {
965
+ ...testEntry,
966
+ file: testFileName,
967
+ data: Buffer.from(testXml, "utf-8"),
968
+ size: Buffer.byteLength(testXml, "utf-8")
969
+ });
970
+ }
971
+ const testResource = actPackage.resources.find((r) => r.type.includes("test"));
972
+ if (testResource) {
973
+ const entry = pkg.entries.get(testFileName);
974
+ const dependencies = [{ identifierref: "asset_lrn_normalize_css" }];
975
+ if (entry) {
976
+ const { itemHrefs, stimulusHrefs } = extractTestDependencies(entry.data.toString("utf-8"));
977
+ const stimulusIds = stimulusHrefs.map((href) => mapHrefToResourceId(href)).filter((id) => id !== null).sort();
978
+ const itemIds = itemHrefs.map((href) => mapHrefToResourceId(href)).filter((id) => id !== null).sort();
979
+ for (const stimulusId of stimulusIds) dependencies.push({ identifierref: stimulusId });
980
+ for (const itemId of itemIds) dependencies.push({ identifierref: itemId });
981
+ }
982
+ pkg.resources.push({
983
+ ...testResource,
984
+ href: testFileName,
985
+ files: [testFileName],
986
+ dependencies
987
+ });
988
+ }
989
+ for (const [key, entry] of actPackage.entries) if (key !== "assessmentTest.xml") pkg.entries.set(key, entry);
990
+ for (const resource of actPackage.resources) {
991
+ if (resource.type.includes("test") || addedResourceIds.has(resource.identifier)) continue;
992
+ if (resource.type.includes("item")) pkg.resources.push({
993
+ ...resource,
994
+ dependencies: [{ identifierref: "asset_lrn_normalize_css" }]
995
+ });
996
+ else pkg.resources.push(resource);
997
+ addedResourceIds.add(resource.identifier);
998
+ }
999
+ pkg.items.push(...actPackage.items);
1000
+ for (const asset of actPackage.assets) if (!pkg.assets.some((a) => a.identifier === asset.identifier)) pkg.assets.push(asset);
1001
+ }
1002
+ //#endregion
1003
+ //#region ../core/src/qti-to-learnosity/convertAssessmentTestToActivity.ts
1004
+ /**
1005
+ * QTI assessmentTest → Learnosity Activity converter (streaming-safe, v1)
1006
+ * TASK 013
1007
+ *
1008
+ * Notes:
1009
+ * - Never throws for user input problems; always returns diagnostics.
1010
+ * - Rejects DOCTYPE / ENTITY declarations up-front (DTD not allowed).
1011
+ * - Uses saxes streaming parser; no DOM tree built.
1012
+ * - Supports simple linear tests only (v1).
1013
+ * - Preserves item reference order deterministically.
1014
+ */
1015
+ /**
1016
+ * Helper to get attribute value from saxes tag
1017
+ */
1018
+ function getAttr(tag, name) {
1019
+ const attr = tag.attributes[name];
1020
+ if (!attr) return;
1021
+ if (typeof attr === "string") return attr;
1022
+ return attr.value;
1023
+ }
1024
+ /**
1025
+ * Extract basename from href without extension
1026
+ */
1027
+ function extractBasename(href) {
1028
+ return (href.split("/").pop() ?? href).replace(/\.[^.]*$/, "");
1029
+ }
1030
+ function rejectDoctype(xml, diagnostics) {
1031
+ if (/<!doctype/i.test(xml) || /<!entity/i.test(xml)) {
1032
+ diagnostics.push({
1033
+ code: DiagnosticCode.QTI_DTD_NOT_ALLOWED,
1034
+ level: "error",
1035
+ file: "root",
1036
+ message: "DOCTYPE/ENTITY is not allowed in QTI XML input."
1037
+ });
1038
+ return true;
1039
+ }
1040
+ return false;
1041
+ }
1042
+ /**
1043
+ * Sanitize malformed XML by fixing common encoding issues
1044
+ * This handles cases where content creators didn't properly escape special characters
1045
+ */
1046
+ function sanitizeXml(xml) {
1047
+ return xml.replace(/&(?![a-zA-Z]+;|#[0-9]+;|#x[0-9a-fA-F]+;)/g, "&amp;");
1048
+ }
1049
+ /**
1050
+ * Convert QTI assessmentTest XML to Learnosity Activity JSON
1051
+ * Supports simple linear tests only (v1)
1052
+ */
1053
+ function convertAssessmentTestToLearnosityActivity(inputXml) {
1054
+ const diagnostics = [];
1055
+ try {
1056
+ if (rejectDoctype(inputXml, diagnostics)) return { diagnostics };
1057
+ const sanitizedXml = sanitizeXml(inputXml);
1058
+ const items = [];
1059
+ let foundAssessmentTest = false;
1060
+ let itemRefIndex = 0;
1061
+ const parser = new import_saxes.SaxesParser({ xmlns: true });
1062
+ parser.on("opentag", (tag) => {
1063
+ const localName = tag.local ?? tag.name;
1064
+ if (localName === "assessmentTest") foundAssessmentTest = true;
1065
+ else if (localName === "assessmentItemRef") {
1066
+ const identifier = getAttr(tag, "identifier");
1067
+ const href = getAttr(tag, "href");
1068
+ let itemRef;
1069
+ if (identifier) itemRef = identifier;
1070
+ else if (href) itemRef = extractBasename(href);
1071
+ else {
1072
+ diagnostics.push({
1073
+ code: DiagnosticCode.QTI_TEST_ITEMREF_MISSING_ID,
1074
+ level: "error",
1075
+ file: `assessmentTest.assessmentItemRef[${itemRefIndex}]`,
1076
+ message: "assessmentItemRef lacks both identifier and href attributes"
1077
+ });
1078
+ itemRefIndex++;
1079
+ return;
1080
+ }
1081
+ items.push({
1082
+ id: itemRef,
1083
+ reference: itemRef
1084
+ });
1085
+ itemRefIndex++;
1086
+ }
1087
+ });
1088
+ parser.on("error", (error) => {
1089
+ diagnostics.push({
1090
+ code: DiagnosticCode.LRN_SCHEMA_INVALID,
1091
+ level: "error",
1092
+ file: "root",
1093
+ message: `XML parsing error: ${error.message}`
1094
+ });
1095
+ });
1096
+ try {
1097
+ parser.write(sanitizedXml).close();
1098
+ } catch (error) {
1099
+ diagnostics.push({
1100
+ code: DiagnosticCode.LRN_SCHEMA_INVALID,
1101
+ level: "error",
1102
+ file: "root",
1103
+ message: `Failed to parse XML: ${error instanceof Error ? error.message : "Unknown error"}`
1104
+ });
1105
+ return { diagnostics };
1106
+ }
1107
+ if (!foundAssessmentTest) diagnostics.push({
1108
+ code: DiagnosticCode.QTI_TEST_ROOT_MISSING,
1109
+ level: "error",
1110
+ file: "root",
1111
+ message: "Invalid QTI XML: assessmentTest root element not found"
1112
+ });
1113
+ if (items.length === 0 && foundAssessmentTest) diagnostics.push({
1114
+ code: DiagnosticCode.QTI_TEST_NO_ITEM_REFS,
1115
+ level: "error",
1116
+ file: "assessmentTest",
1117
+ message: "No assessmentItemRef elements found in test"
1118
+ });
1119
+ if (diagnostics.some((d) => d.level === "error")) return { diagnostics };
1120
+ return {
1121
+ activity: {
1122
+ rendering_type: "assess",
1123
+ items,
1124
+ config: {
1125
+ configuration: {},
1126
+ navigation: {},
1127
+ regions: "main",
1128
+ title: null,
1129
+ subtitle: null
1130
+ }
1131
+ },
1132
+ diagnostics
1133
+ };
1134
+ } catch (error) {
1135
+ diagnostics.push({
1136
+ code: DiagnosticCode.LRN_SCHEMA_INVALID,
1137
+ level: "error",
1138
+ file: "root",
1139
+ message: `Failed to convert assessmentTest: ${error instanceof Error ? error.message : "Unknown error"}`
1140
+ });
1141
+ return { diagnostics };
1142
+ }
1143
+ }
1144
+ //#endregion
1145
+ //#region ../../node_modules/.pnpm/fflate@0.8.3/node_modules/fflate/esm/index.mjs
1146
+ var require = createRequire("/");
1147
+ var _a;
1148
+ try {
1149
+ _a = require("worker_threads"), _a.Worker, _a.isMarkedAsUntransferable;
1150
+ } catch (e) {}
1151
+ var u8 = Uint8Array;
1152
+ var u16 = Uint16Array;
1153
+ var i32 = Int32Array;
1154
+ var fleb = new u8([
1155
+ 0,
1156
+ 0,
1157
+ 0,
1158
+ 0,
1159
+ 0,
1160
+ 0,
1161
+ 0,
1162
+ 0,
1163
+ 1,
1164
+ 1,
1165
+ 1,
1166
+ 1,
1167
+ 2,
1168
+ 2,
1169
+ 2,
1170
+ 2,
1171
+ 3,
1172
+ 3,
1173
+ 3,
1174
+ 3,
1175
+ 4,
1176
+ 4,
1177
+ 4,
1178
+ 4,
1179
+ 5,
1180
+ 5,
1181
+ 5,
1182
+ 5,
1183
+ 0,
1184
+ 0,
1185
+ 0,
1186
+ 0
1187
+ ]);
1188
+ var fdeb = new u8([
1189
+ 0,
1190
+ 0,
1191
+ 0,
1192
+ 0,
1193
+ 1,
1194
+ 1,
1195
+ 2,
1196
+ 2,
1197
+ 3,
1198
+ 3,
1199
+ 4,
1200
+ 4,
1201
+ 5,
1202
+ 5,
1203
+ 6,
1204
+ 6,
1205
+ 7,
1206
+ 7,
1207
+ 8,
1208
+ 8,
1209
+ 9,
1210
+ 9,
1211
+ 10,
1212
+ 10,
1213
+ 11,
1214
+ 11,
1215
+ 12,
1216
+ 12,
1217
+ 13,
1218
+ 13,
1219
+ 0,
1220
+ 0
1221
+ ]);
1222
+ var clim = new u8([
1223
+ 16,
1224
+ 17,
1225
+ 18,
1226
+ 0,
1227
+ 8,
1228
+ 7,
1229
+ 9,
1230
+ 6,
1231
+ 10,
1232
+ 5,
1233
+ 11,
1234
+ 4,
1235
+ 12,
1236
+ 3,
1237
+ 13,
1238
+ 2,
1239
+ 14,
1240
+ 1,
1241
+ 15
1242
+ ]);
1243
+ var freb = function(eb, start) {
1244
+ var b = new u16(31);
1245
+ for (var i = 0; i < 31; ++i) b[i] = start += 1 << eb[i - 1];
1246
+ var r = new i32(b[30]);
1247
+ for (var i = 1; i < 30; ++i) for (var j = b[i]; j < b[i + 1]; ++j) r[j] = j - b[i] << 5 | i;
1248
+ return {
1249
+ b,
1250
+ r
1251
+ };
1252
+ };
1253
+ var _a = freb(fleb, 2);
1254
+ var fl = _a.b;
1255
+ var revfl = _a.r;
1256
+ fl[28] = 258, revfl[258] = 28;
1257
+ var _b = freb(fdeb, 0);
1258
+ var fd = _b.b;
1259
+ var revfd = _b.r;
1260
+ var rev = new u16(32768);
1261
+ for (var i = 0; i < 32768; ++i) {
1262
+ var x = (i & 43690) >> 1 | (i & 21845) << 1;
1263
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
1264
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
1265
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
1266
+ }
1267
+ var hMap = (function(cd, mb, r) {
1268
+ var s = cd.length;
1269
+ var i = 0;
1270
+ var l = new u16(mb);
1271
+ for (; i < s; ++i) if (cd[i]) ++l[cd[i] - 1];
1272
+ var le = new u16(mb);
1273
+ for (i = 1; i < mb; ++i) le[i] = le[i - 1] + l[i - 1] << 1;
1274
+ var co;
1275
+ if (r) {
1276
+ co = new u16(1 << mb);
1277
+ var rvb = 15 - mb;
1278
+ for (i = 0; i < s; ++i) if (cd[i]) {
1279
+ var sv = i << 4 | cd[i];
1280
+ var r_1 = mb - cd[i];
1281
+ var v = le[cd[i] - 1]++ << r_1;
1282
+ for (var m = v | (1 << r_1) - 1; v <= m; ++v) co[rev[v] >> rvb] = sv;
1283
+ }
1284
+ } else {
1285
+ co = new u16(s);
1286
+ for (i = 0; i < s; ++i) if (cd[i]) co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
1287
+ }
1288
+ return co;
1289
+ });
1290
+ var flt = new u8(288);
1291
+ for (var i = 0; i < 144; ++i) flt[i] = 8;
1292
+ for (var i = 144; i < 256; ++i) flt[i] = 9;
1293
+ for (var i = 256; i < 280; ++i) flt[i] = 7;
1294
+ for (var i = 280; i < 288; ++i) flt[i] = 8;
1295
+ var fdt = new u8(32);
1296
+ for (var i = 0; i < 32; ++i) fdt[i] = 5;
1297
+ var flm = /*#__PURE__*/ hMap(flt, 9, 0);
1298
+ var flrm = /*#__PURE__*/ hMap(flt, 9, 1);
1299
+ var fdm = /*#__PURE__*/ hMap(fdt, 5, 0);
1300
+ var fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
1301
+ var max = function(a) {
1302
+ var m = a[0];
1303
+ for (var i = 1; i < a.length; ++i) if (a[i] > m) m = a[i];
1304
+ return m;
1305
+ };
1306
+ var bits = function(d, p, m) {
1307
+ var o = p / 8 | 0;
1308
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
1309
+ };
1310
+ var bits16 = function(d, p) {
1311
+ var o = p / 8 | 0;
1312
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
1313
+ };
1314
+ var shft = function(p) {
1315
+ return (p + 7) / 8 | 0;
1316
+ };
1317
+ var slc = function(v, s, e) {
1318
+ if (s == null || s < 0) s = 0;
1319
+ if (e == null || e > v.length) e = v.length;
1320
+ return new u8(v.subarray(s, e));
1321
+ };
1322
+ var ec = [
1323
+ "unexpected EOF",
1324
+ "invalid block type",
1325
+ "invalid length/literal",
1326
+ "invalid distance",
1327
+ "stream finished",
1328
+ "no stream handler",
1329
+ ,
1330
+ "no callback",
1331
+ "invalid UTF-8 data",
1332
+ "extra field too long",
1333
+ "date not in range 1980-2099",
1334
+ "filename too long",
1335
+ "stream finishing",
1336
+ "invalid zip data"
1337
+ ];
1338
+ var err = function(ind, msg, nt) {
1339
+ var e = new Error(msg || ec[ind]);
1340
+ e.code = ind;
1341
+ if (Error.captureStackTrace) Error.captureStackTrace(e, err);
1342
+ if (!nt) throw e;
1343
+ return e;
1344
+ };
1345
+ var inflt = function(dat, st, buf, dict) {
1346
+ var sl = dat.length, dl = dict ? dict.length : 0;
1347
+ if (!sl || st.f && !st.l) return buf || new u8(0);
1348
+ var noBuf = !buf;
1349
+ var resize = noBuf || st.i != 2;
1350
+ var noSt = st.i;
1351
+ if (noBuf) buf = new u8(sl * 3);
1352
+ var cbuf = function(l) {
1353
+ var bl = buf.length;
1354
+ if (l > bl) {
1355
+ var nbuf = new u8(Math.max(bl * 2, l));
1356
+ nbuf.set(buf);
1357
+ buf = nbuf;
1358
+ }
1359
+ };
1360
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
1361
+ var tbts = sl * 8;
1362
+ do {
1363
+ if (!lm) {
1364
+ final = bits(dat, pos, 1);
1365
+ var type = bits(dat, pos + 1, 3);
1366
+ pos += 3;
1367
+ if (!type) {
1368
+ var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
1369
+ if (t > sl) {
1370
+ if (noSt) err(0);
1371
+ break;
1372
+ }
1373
+ if (resize) cbuf(bt + l);
1374
+ buf.set(dat.subarray(s, t), bt);
1375
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
1376
+ continue;
1377
+ } else if (type == 1) lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
1378
+ else if (type == 2) {
1379
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
1380
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
1381
+ pos += 14;
1382
+ var ldt = new u8(tl);
1383
+ var clt = new u8(19);
1384
+ for (var i = 0; i < hcLen; ++i) clt[clim[i]] = bits(dat, pos + i * 3, 7);
1385
+ pos += hcLen * 3;
1386
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
1387
+ var clm = hMap(clt, clb, 1);
1388
+ for (var i = 0; i < tl;) {
1389
+ var r = clm[bits(dat, pos, clbmsk)];
1390
+ pos += r & 15;
1391
+ var s = r >> 4;
1392
+ if (s < 16) ldt[i++] = s;
1393
+ else {
1394
+ var c = 0, n = 0;
1395
+ if (s == 16) n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
1396
+ else if (s == 17) n = 3 + bits(dat, pos, 7), pos += 3;
1397
+ else if (s == 18) n = 11 + bits(dat, pos, 127), pos += 7;
1398
+ while (n--) ldt[i++] = c;
1399
+ }
1400
+ }
1401
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
1402
+ lbt = max(lt);
1403
+ dbt = max(dt);
1404
+ lm = hMap(lt, lbt, 1);
1405
+ dm = hMap(dt, dbt, 1);
1406
+ } else err(1);
1407
+ if (pos > tbts) {
1408
+ if (noSt) err(0);
1409
+ break;
1410
+ }
1411
+ }
1412
+ if (resize) cbuf(bt + 131072);
1413
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
1414
+ var lpos = pos;
1415
+ for (;; lpos = pos) {
1416
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
1417
+ pos += c & 15;
1418
+ if (pos > tbts) {
1419
+ if (noSt) err(0);
1420
+ break;
1421
+ }
1422
+ if (!c) err(2);
1423
+ if (sym < 256) buf[bt++] = sym;
1424
+ else if (sym == 256) {
1425
+ lpos = pos, lm = null;
1426
+ break;
1427
+ } else {
1428
+ var add = sym - 254;
1429
+ if (sym > 264) {
1430
+ var i = sym - 257, b = fleb[i];
1431
+ add = bits(dat, pos, (1 << b) - 1) + fl[i];
1432
+ pos += b;
1433
+ }
1434
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
1435
+ if (!d) err(3);
1436
+ pos += d & 15;
1437
+ var dt = fd[dsym];
1438
+ if (dsym > 3) {
1439
+ var b = fdeb[dsym];
1440
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
1441
+ }
1442
+ if (pos > tbts) {
1443
+ if (noSt) err(0);
1444
+ break;
1445
+ }
1446
+ if (resize) cbuf(bt + 131072);
1447
+ var end = bt + add;
1448
+ if (bt < dt) {
1449
+ var shift = dl - dt, dend = Math.min(dt, end);
1450
+ if (shift + bt < 0) err(3);
1451
+ for (; bt < dend; ++bt) buf[bt] = dict[shift + bt];
1452
+ }
1453
+ for (; bt < end; ++bt) buf[bt] = buf[bt - dt];
1454
+ }
1455
+ }
1456
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
1457
+ if (lm) final = 1, st.m = lbt, st.d = dm, st.n = dbt;
1458
+ } while (!final);
1459
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
1460
+ };
1461
+ var wbits = function(d, p, v) {
1462
+ v <<= p & 7;
1463
+ var o = p / 8 | 0;
1464
+ d[o] |= v;
1465
+ d[o + 1] |= v >> 8;
1466
+ };
1467
+ var wbits16 = function(d, p, v) {
1468
+ v <<= p & 7;
1469
+ var o = p / 8 | 0;
1470
+ d[o] |= v;
1471
+ d[o + 1] |= v >> 8;
1472
+ d[o + 2] |= v >> 16;
1473
+ };
1474
+ var hTree = function(d, mb) {
1475
+ var t = [];
1476
+ for (var i = 0; i < d.length; ++i) if (d[i]) t.push({
1477
+ s: i,
1478
+ f: d[i]
1479
+ });
1480
+ var s = t.length;
1481
+ var t2 = t.slice();
1482
+ if (!s) return {
1483
+ t: et,
1484
+ l: 0
1485
+ };
1486
+ if (s == 1) {
1487
+ var v = new u8(t[0].s + 1);
1488
+ v[t[0].s] = 1;
1489
+ return {
1490
+ t: v,
1491
+ l: 1
1492
+ };
1493
+ }
1494
+ t.sort(function(a, b) {
1495
+ return a.f - b.f;
1496
+ });
1497
+ t.push({
1498
+ s: -1,
1499
+ f: 25001
1500
+ });
1501
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
1502
+ t[0] = {
1503
+ s: -1,
1504
+ f: l.f + r.f,
1505
+ l,
1506
+ r
1507
+ };
1508
+ while (i1 != s - 1) {
1509
+ l = t[t[i0].f < t[i2].f ? i0++ : i2++];
1510
+ r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
1511
+ t[i1++] = {
1512
+ s: -1,
1513
+ f: l.f + r.f,
1514
+ l,
1515
+ r
1516
+ };
1517
+ }
1518
+ var maxSym = t2[0].s;
1519
+ for (var i = 1; i < s; ++i) if (t2[i].s > maxSym) maxSym = t2[i].s;
1520
+ var tr = new u16(maxSym + 1);
1521
+ var mbt = ln(t[i1 - 1], tr, 0);
1522
+ if (mbt > mb) {
1523
+ var i = 0, dt = 0;
1524
+ var lft = mbt - mb, cst = 1 << lft;
1525
+ t2.sort(function(a, b) {
1526
+ return tr[b.s] - tr[a.s] || a.f - b.f;
1527
+ });
1528
+ for (; i < s; ++i) {
1529
+ var i2_1 = t2[i].s;
1530
+ if (tr[i2_1] > mb) {
1531
+ dt += cst - (1 << mbt - tr[i2_1]);
1532
+ tr[i2_1] = mb;
1533
+ } else break;
1534
+ }
1535
+ dt >>= lft;
1536
+ while (dt > 0) {
1537
+ var i2_2 = t2[i].s;
1538
+ if (tr[i2_2] < mb) dt -= 1 << mb - tr[i2_2]++ - 1;
1539
+ else ++i;
1540
+ }
1541
+ for (; i >= 0 && dt; --i) {
1542
+ var i2_3 = t2[i].s;
1543
+ if (tr[i2_3] == mb) {
1544
+ --tr[i2_3];
1545
+ ++dt;
1546
+ }
1547
+ }
1548
+ mbt = mb;
1549
+ }
1550
+ return {
1551
+ t: new u8(tr),
1552
+ l: mbt
1553
+ };
1554
+ };
1555
+ var ln = function(n, l, d) {
1556
+ return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
1557
+ };
1558
+ var lc = function(c) {
1559
+ var s = c.length;
1560
+ while (s && !c[--s]);
1561
+ var cl = new u16(++s);
1562
+ var cli = 0, cln = c[0], cls = 1;
1563
+ var w = function(v) {
1564
+ cl[cli++] = v;
1565
+ };
1566
+ for (var i = 1; i <= s; ++i) if (c[i] == cln && i != s) ++cls;
1567
+ else {
1568
+ if (!cln && cls > 2) {
1569
+ for (; cls > 138; cls -= 138) w(32754);
1570
+ if (cls > 2) {
1571
+ w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
1572
+ cls = 0;
1573
+ }
1574
+ } else if (cls > 3) {
1575
+ w(cln), --cls;
1576
+ for (; cls > 6; cls -= 6) w(8304);
1577
+ if (cls > 2) w(cls - 3 << 5 | 8208), cls = 0;
1578
+ }
1579
+ while (cls--) w(cln);
1580
+ cls = 1;
1581
+ cln = c[i];
1582
+ }
1583
+ return {
1584
+ c: cl.subarray(0, cli),
1585
+ n: s
1586
+ };
1587
+ };
1588
+ var clen = function(cf, cl) {
1589
+ var l = 0;
1590
+ for (var i = 0; i < cl.length; ++i) l += cf[i] * cl[i];
1591
+ return l;
1592
+ };
1593
+ var wfblk = function(out, pos, dat) {
1594
+ var s = dat.length;
1595
+ var o = shft(pos + 2);
1596
+ out[o] = s & 255;
1597
+ out[o + 1] = s >> 8;
1598
+ out[o + 2] = out[o] ^ 255;
1599
+ out[o + 3] = out[o + 1] ^ 255;
1600
+ for (var i = 0; i < s; ++i) out[o + i + 4] = dat[i];
1601
+ return (o + 4 + s) * 8;
1602
+ };
1603
+ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
1604
+ wbits(out, p++, final);
1605
+ ++lf[256];
1606
+ var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;
1607
+ var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;
1608
+ var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
1609
+ var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
1610
+ var lcfreq = new u16(19);
1611
+ for (var i = 0; i < lclt.length; ++i) ++lcfreq[lclt[i] & 31];
1612
+ for (var i = 0; i < lcdt.length; ++i) ++lcfreq[lcdt[i] & 31];
1613
+ var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
1614
+ var nlcc = 19;
1615
+ for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc);
1616
+ var flen = bl + 5 << 3;
1617
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
1618
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
1619
+ if (bs >= 0 && flen <= ftlen && flen <= dtlen) return wfblk(out, p, dat.subarray(bs, bs + bl));
1620
+ var lm, ll, dm, dl;
1621
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
1622
+ if (dtlen < ftlen) {
1623
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
1624
+ var llm = hMap(lct, mlcb, 0);
1625
+ wbits(out, p, nlc - 257);
1626
+ wbits(out, p + 5, ndc - 1);
1627
+ wbits(out, p + 10, nlcc - 4);
1628
+ p += 14;
1629
+ for (var i = 0; i < nlcc; ++i) wbits(out, p + 3 * i, lct[clim[i]]);
1630
+ p += 3 * nlcc;
1631
+ var lcts = [lclt, lcdt];
1632
+ for (var it = 0; it < 2; ++it) {
1633
+ var clct = lcts[it];
1634
+ for (var i = 0; i < clct.length; ++i) {
1635
+ var len = clct[i] & 31;
1636
+ wbits(out, p, llm[len]), p += lct[len];
1637
+ if (len > 15) wbits(out, p, clct[i] >> 5 & 127), p += clct[i] >> 12;
1638
+ }
1639
+ }
1640
+ } else lm = flm, ll = flt, dm = fdm, dl = fdt;
1641
+ for (var i = 0; i < li; ++i) {
1642
+ var sym = syms[i];
1643
+ if (sym > 255) {
1644
+ var len = sym >> 18 & 31;
1645
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
1646
+ if (len > 7) wbits(out, p, sym >> 23 & 31), p += fleb[len];
1647
+ var dst = sym & 31;
1648
+ wbits16(out, p, dm[dst]), p += dl[dst];
1649
+ if (dst > 3) wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
1650
+ } else wbits16(out, p, lm[sym]), p += ll[sym];
1651
+ }
1652
+ wbits16(out, p, lm[256]);
1653
+ return p + ll[256];
1654
+ };
1655
+ var deo = /*#__PURE__*/ new i32([
1656
+ 65540,
1657
+ 131080,
1658
+ 131088,
1659
+ 131104,
1660
+ 262176,
1661
+ 1048704,
1662
+ 1048832,
1663
+ 2114560,
1664
+ 2117632
1665
+ ]);
1666
+ var et = /*#__PURE__*/ new u8(0);
1667
+ var dflt = function(dat, lvl, plvl, pre, post, st) {
1668
+ var s = st.z || dat.length;
1669
+ var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7e3)) + post);
1670
+ var w = o.subarray(pre, o.length - post);
1671
+ var lst = st.l;
1672
+ var pos = (st.r || 0) & 7;
1673
+ if (lvl) {
1674
+ if (pos) w[0] = st.r >> 3;
1675
+ var opt = deo[lvl - 1];
1676
+ var n = opt >> 13, c = opt & 8191;
1677
+ var msk_1 = (1 << plvl) - 1;
1678
+ var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
1679
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
1680
+ var hsh = function(i) {
1681
+ return (dat[i] ^ dat[i + 1] << bs1_1 ^ dat[i + 2] << bs2_1) & msk_1;
1682
+ };
1683
+ var syms = new i32(25e3);
1684
+ var lf = new u16(288), df = new u16(32);
1685
+ var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
1686
+ for (; i + 2 < s; ++i) {
1687
+ var hv = hsh(i);
1688
+ var imod = i & 32767, pimod = head[hv];
1689
+ prev[imod] = pimod;
1690
+ head[hv] = imod;
1691
+ if (wi <= i) {
1692
+ var rem = s - i;
1693
+ if ((lc_1 > 7e3 || li > 24576) && (rem > 423 || !lst)) {
1694
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
1695
+ li = lc_1 = eb = 0, bs = i;
1696
+ for (var j = 0; j < 286; ++j) lf[j] = 0;
1697
+ for (var j = 0; j < 30; ++j) df[j] = 0;
1698
+ }
1699
+ var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
1700
+ if (rem > 2 && hv == hsh(i - dif)) {
1701
+ var maxn = Math.min(n, rem) - 1;
1702
+ var maxd = Math.min(32767, i);
1703
+ var ml = Math.min(258, rem);
1704
+ while (dif <= maxd && --ch_1 && imod != pimod) {
1705
+ if (dat[i + l] == dat[i + l - dif]) {
1706
+ var nl = 0;
1707
+ for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl);
1708
+ if (nl > l) {
1709
+ l = nl, d = dif;
1710
+ if (nl > maxn) break;
1711
+ var mmd = Math.min(dif, nl - 2);
1712
+ var md = 0;
1713
+ for (var j = 0; j < mmd; ++j) {
1714
+ var ti = i - dif + j & 32767;
1715
+ var cd = ti - prev[ti] & 32767;
1716
+ if (cd > md) md = cd, pimod = ti;
1717
+ }
1718
+ }
1719
+ }
1720
+ imod = pimod, pimod = prev[imod];
1721
+ dif += imod - pimod & 32767;
1722
+ }
1723
+ }
1724
+ if (d) {
1725
+ syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
1726
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
1727
+ eb += fleb[lin] + fdeb[din];
1728
+ ++lf[257 + lin];
1729
+ ++df[din];
1730
+ wi = i + l;
1731
+ ++lc_1;
1732
+ } else {
1733
+ syms[li++] = dat[i];
1734
+ ++lf[dat[i]];
1735
+ }
1736
+ }
1737
+ }
1738
+ for (i = Math.max(i, wi); i < s; ++i) {
1739
+ syms[li++] = dat[i];
1740
+ ++lf[dat[i]];
1741
+ }
1742
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
1743
+ if (!lst) {
1744
+ st.r = pos & 7 | w[pos / 8 | 0] << 3;
1745
+ pos -= 7;
1746
+ st.h = head, st.p = prev, st.i = i, st.w = wi;
1747
+ }
1748
+ } else {
1749
+ for (var i = st.w || 0; i < s + lst; i += 65535) {
1750
+ var e = i + 65535;
1751
+ if (e >= s) {
1752
+ w[pos / 8 | 0] = lst;
1753
+ e = s;
1754
+ }
1755
+ pos = wfblk(w, pos + 1, dat.subarray(i, e));
1756
+ }
1757
+ st.i = s;
1758
+ }
1759
+ return slc(o, 0, pre + shft(pos) + post);
1760
+ };
1761
+ var crct = /*#__PURE__*/ (function() {
1762
+ var t = /* @__PURE__ */ new Int32Array(256);
1763
+ for (var i = 0; i < 256; ++i) {
1764
+ var c = i, k = 9;
1765
+ while (--k) c = (c & 1 && -306674912) ^ c >>> 1;
1766
+ t[i] = c;
1767
+ }
1768
+ return t;
1769
+ })();
1770
+ var crc = function() {
1771
+ var c = -1;
1772
+ return {
1773
+ p: function(d) {
1774
+ var cr = c;
1775
+ for (var i = 0; i < d.length; ++i) cr = crct[cr & 255 ^ d[i]] ^ cr >>> 8;
1776
+ c = cr;
1777
+ },
1778
+ d: function() {
1779
+ return ~c;
1780
+ }
1781
+ };
1782
+ };
1783
+ var dopt = function(dat, opt, pre, post, st) {
1784
+ if (!st) {
1785
+ st = { l: 1 };
1786
+ if (opt.dictionary) {
1787
+ var dict = opt.dictionary.subarray(-32768);
1788
+ var newDat = new u8(dict.length + dat.length);
1789
+ newDat.set(dict);
1790
+ newDat.set(dat, dict.length);
1791
+ dat = newDat;
1792
+ st.w = dict.length;
1793
+ }
1794
+ }
1795
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
1796
+ };
1797
+ var mrg = function(a, b) {
1798
+ var o = {};
1799
+ for (var k in a) o[k] = a[k];
1800
+ for (var k in b) o[k] = b[k];
1801
+ return o;
1802
+ };
1803
+ var b2 = function(d, b) {
1804
+ return d[b] | d[b + 1] << 8;
1805
+ };
1806
+ var b4 = function(d, b) {
1807
+ return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
1808
+ };
1809
+ var b8 = function(d, b) {
1810
+ return b4(d, b) + b4(d, b + 4) * 4294967296;
1811
+ };
1812
+ var wbytes = function(d, b, v) {
1813
+ for (; v; ++b) d[b] = v, v >>>= 8;
1814
+ };
1815
+ /**
1816
+ * Compresses data with DEFLATE without any wrapper
1817
+ * @param data The data to compress
1818
+ * @param opts The compression options
1819
+ * @returns The deflated version of the data
1820
+ */
1821
+ function deflateSync(data, opts) {
1822
+ return dopt(data, opts || {}, 0, 0);
1823
+ }
1824
+ function inflateSync(data, opts) {
1825
+ return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
1826
+ }
1827
+ var fltn = function(d, p, t, o) {
1828
+ for (var k in d) {
1829
+ var val = d[k], n = p + k, op = o;
1830
+ if (Array.isArray(val)) op = mrg(o, val[1]), val = val[0];
1831
+ if (ArrayBuffer.isView(val)) t[n] = [val, op];
1832
+ else {
1833
+ t[n += "/"] = [new u8(0), op];
1834
+ fltn(val, n, t, o);
1835
+ }
1836
+ }
1837
+ };
1838
+ var te = typeof TextEncoder != "undefined" && /*#__PURE__*/ new TextEncoder();
1839
+ var td = typeof TextDecoder != "undefined" && /*#__PURE__*/ new TextDecoder();
1840
+ try {
1841
+ td.decode(et, { stream: true });
1842
+ } catch (e) {}
1843
+ var dutf8 = function(d) {
1844
+ for (var r = "", i = 0;;) {
1845
+ var c = d[i++];
1846
+ var eb = (c > 127) + (c > 223) + (c > 239);
1847
+ if (i + eb > d.length) return {
1848
+ s: r,
1849
+ r: slc(d, i - 1)
1850
+ };
1851
+ if (!eb) r += String.fromCharCode(c);
1852
+ else if (eb == 3) c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | d[i++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023);
1853
+ else if (eb & 1) r += String.fromCharCode((c & 31) << 6 | d[i++] & 63);
1854
+ else r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | d[i++] & 63);
1855
+ }
1856
+ };
1857
+ /**
1858
+ * Converts a string into a Uint8Array for use with compression/decompression methods
1859
+ * @param str The string to encode
1860
+ * @param latin1 Whether or not to interpret the data as Latin-1. This should
1861
+ * not need to be true unless decoding a binary string.
1862
+ * @returns The string encoded in UTF-8/Latin-1 binary
1863
+ */
1864
+ function strToU8(str, latin1) {
1865
+ if (latin1) {
1866
+ var ar_1 = new u8(str.length);
1867
+ for (var i = 0; i < str.length; ++i) ar_1[i] = str.charCodeAt(i);
1868
+ return ar_1;
1869
+ }
1870
+ if (te) return te.encode(str);
1871
+ var l = str.length;
1872
+ var ar = new u8(str.length + (str.length >> 1));
1873
+ var ai = 0;
1874
+ var w = function(v) {
1875
+ ar[ai++] = v;
1876
+ };
1877
+ for (var i = 0; i < l; ++i) {
1878
+ if (ai + 5 > ar.length) {
1879
+ var n = new u8(ai + 8 + (l - i << 1));
1880
+ n.set(ar);
1881
+ ar = n;
1882
+ }
1883
+ var c = str.charCodeAt(i);
1884
+ if (c < 128 || latin1) w(c);
1885
+ else if (c < 2048) w(192 | c >> 6), w(128 | c & 63);
1886
+ else if (c > 55295 && c < 57344) c = 65536 + (c & 1047552) | str.charCodeAt(++i) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63);
1887
+ else w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63);
1888
+ }
1889
+ return slc(ar, 0, ai);
1890
+ }
1891
+ /**
1892
+ * Converts a Uint8Array to a string
1893
+ * @param dat The data to decode to string
1894
+ * @param latin1 Whether or not to interpret the data as Latin-1. This should
1895
+ * not need to be true unless encoding to binary string.
1896
+ * @returns The original UTF-8/Latin-1 string
1897
+ */
1898
+ function strFromU8(dat, latin1) {
1899
+ if (latin1) {
1900
+ var r = "";
1901
+ for (var i = 0; i < dat.length; i += 16384) r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
1902
+ return r;
1903
+ } else if (td) return td.decode(dat);
1904
+ else {
1905
+ var _a = dutf8(dat), s = _a.s, r = _a.r;
1906
+ if (r.length) err(8);
1907
+ return s;
1908
+ }
1909
+ }
1910
+ var slzh = function(d, b) {
1911
+ return b + 30 + b2(d, b + 26) + b2(d, b + 28);
1912
+ };
1913
+ var zh = function(d, b, z) {
1914
+ var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;
1915
+ var _a = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a[0], su = _a[1], off = _a[2];
1916
+ return [
1917
+ b2(d, b + 10),
1918
+ sc,
1919
+ su,
1920
+ fn,
1921
+ es + efl + b2(d, b + 32),
1922
+ off
1923
+ ];
1924
+ };
1925
+ var z64hs = function(d, b, l, z, sc, su, off) {
1926
+ var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l;
1927
+ var nf = nsc + nsu + noff;
1928
+ if (z && nf) {
1929
+ for (; b + 4 < e; b += 4 + b2(d, b + 2)) if (b2(d, b) == 1) return [
1930
+ nsc ? b8(d, b + 4 + 8 * nsu) : sc,
1931
+ nsu ? b8(d, b + 4) : su,
1932
+ noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off,
1933
+ 1
1934
+ ];
1935
+ if (z < 2) err(13);
1936
+ }
1937
+ return [
1938
+ sc,
1939
+ su,
1940
+ off,
1941
+ 0
1942
+ ];
1943
+ };
1944
+ var exfl = function(ex) {
1945
+ var le = 0;
1946
+ if (ex) for (var k in ex) {
1947
+ var l = ex[k].length;
1948
+ if (l > 65535) err(9);
1949
+ le += l + 4;
1950
+ }
1951
+ return le;
1952
+ };
1953
+ var wzh = function(d, b, f, fn, u, c, ce, co) {
1954
+ var fl = fn.length, ex = f.extra, col = co && co.length;
1955
+ var exl = exfl(ex);
1956
+ wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4;
1957
+ if (ce != null) d[b++] = 20, d[b++] = f.os;
1958
+ d[b] = 20, b += 2;
1959
+ d[b++] = f.flag << 1 | (c < 0 && 8), d[b++] = u && 8;
1960
+ d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
1961
+ var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
1962
+ if (y < 0 || y > 119) err(10);
1963
+ wbytes(d, b, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b += 4;
1964
+ if (c != -1) {
1965
+ wbytes(d, b, f.crc);
1966
+ wbytes(d, b + 4, c < 0 ? -c - 2 : c);
1967
+ wbytes(d, b + 8, f.size);
1968
+ }
1969
+ wbytes(d, b + 12, fl);
1970
+ wbytes(d, b + 14, exl), b += 16;
1971
+ if (ce != null) {
1972
+ wbytes(d, b, col);
1973
+ wbytes(d, b + 6, f.attrs);
1974
+ wbytes(d, b + 10, ce), b += 14;
1975
+ }
1976
+ d.set(fn, b);
1977
+ b += fl;
1978
+ if (exl) for (var k in ex) {
1979
+ var exf = ex[k], l = exf.length;
1980
+ wbytes(d, b, +k);
1981
+ wbytes(d, b + 2, l);
1982
+ d.set(exf, b + 4), b += 4 + l;
1983
+ }
1984
+ if (col) d.set(co, b), b += col;
1985
+ return b;
1986
+ };
1987
+ var wzf = function(o, b, c, d, e) {
1988
+ wbytes(o, b, 101010256);
1989
+ wbytes(o, b + 8, c);
1990
+ wbytes(o, b + 10, c);
1991
+ wbytes(o, b + 12, d);
1992
+ wbytes(o, b + 16, e);
1993
+ };
1994
+ /**
1995
+ * Synchronously creates a ZIP file. Prefer using `zip` for better performance
1996
+ * with more than one file.
1997
+ * @param data The directory structure for the ZIP archive
1998
+ * @param opts The main options, merged with per-file options
1999
+ * @returns The generated ZIP archive
2000
+ */
2001
+ function zipSync(data, opts) {
2002
+ if (!opts) opts = {};
2003
+ var r = {};
2004
+ var files = [];
2005
+ fltn(data, "", r, opts);
2006
+ var o = 0;
2007
+ var tot = 0;
2008
+ for (var fn in r) {
2009
+ var _a = r[fn], file = _a[0], p = _a[1];
2010
+ var compression = p.level == 0 ? 0 : 8;
2011
+ var f = strToU8(fn), s = f.length;
2012
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
2013
+ var exl = exfl(p.extra);
2014
+ if (s > 65535) err(11);
2015
+ var d = compression ? deflateSync(file, p) : file, l = d.length;
2016
+ var c = crc();
2017
+ c.p(file);
2018
+ files.push(mrg(p, {
2019
+ size: file.length,
2020
+ crc: c.d(),
2021
+ c: d,
2022
+ f,
2023
+ m,
2024
+ u: s != fn.length || m && com.length != ms,
2025
+ o,
2026
+ compression
2027
+ }));
2028
+ o += 30 + s + exl + l;
2029
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
2030
+ }
2031
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
2032
+ for (var i = 0; i < files.length; ++i) {
2033
+ var f = files[i];
2034
+ wzh(out, f.o, f, f.f, f.u, f.c.length);
2035
+ var badd = 30 + f.f.length + exfl(f.extra);
2036
+ out.set(f.c, f.o + badd);
2037
+ wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
2038
+ }
2039
+ wzf(out, o, files.length, cdl, oe);
2040
+ return out;
2041
+ }
2042
+ /**
2043
+ * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better
2044
+ * performance with more than one file.
2045
+ * @param data The raw compressed ZIP file
2046
+ * @param opts The ZIP extraction options
2047
+ * @returns The decompressed files
2048
+ */
2049
+ function unzipSync(data, opts) {
2050
+ var files = {};
2051
+ var e = data.length - 22;
2052
+ for (; b4(data, e) != 101010256; --e) if (!e || data.length - e > 65558) err(13);
2053
+ var c = b2(data, e + 8);
2054
+ if (!c) return {};
2055
+ var o = b4(data, e + 16);
2056
+ var z = b4(data, e - 20) == 117853008;
2057
+ if (z) {
2058
+ var ze = b4(data, e - 12);
2059
+ z = b4(data, ze) == 101075792;
2060
+ if (z) {
2061
+ c = b4(data, ze + 32);
2062
+ o = b4(data, ze + 48);
2063
+ }
2064
+ }
2065
+ var fltr = opts && opts.filter;
2066
+ for (var i = 0; i < c; ++i) {
2067
+ var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
2068
+ o = no;
2069
+ if (!fltr || fltr({
2070
+ name: fn,
2071
+ size: sc,
2072
+ originalSize: su,
2073
+ compression: c_2
2074
+ })) {
2075
+ if (!c_2) files[fn] = slc(data, b, b + sc);
2076
+ else if (c_2 == 8) files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
2077
+ else err(14, "unknown compression type " + c_2);
2078
+ }
2079
+ }
2080
+ return files;
2081
+ }
2082
+ //#endregion
2083
+ //#region ../core/src/qti-package/zipCodec.ts
2084
+ /**
2085
+ * Pure ZIP codec backed by fflate.
2086
+ *
2087
+ * Operates entirely on byte arrays with no filesystem access and no Node
2088
+ * `Buffer` dependency, so it can run in a browser bundle. Node entry points
2089
+ * (`readZip`, `writeZip`) wrap these helpers with `fs` I/O.
2090
+ */
2091
+ /** Fixed timestamp for reproducible archives (2000-01-01 00:00:00 UTC). */
2092
+ const FIXED_MTIME = /* @__PURE__ */ new Date("2000-01-01T00:00:00Z");
2093
+ /**
2094
+ * Decode ZIP bytes into safe entries.
2095
+ *
2096
+ * Directory entries are skipped, and each path is validated against zip-slip
2097
+ * (absolute paths, `..` traversal); unsafe entries are dropped with a warning.
2098
+ *
2099
+ * @param bytes - Raw ZIP archive bytes
2100
+ * @param sourceLabel - Label used in diagnostics (e.g. the source path)
2101
+ * @param options - Optional `filter(name)` to inflate only matching entries
2102
+ * (lazy/selective decompression — non-matching entries are never inflated)
2103
+ */
2104
+ function unzipToEntries(bytes, sourceLabel, options) {
2105
+ const diagnostics = [];
2106
+ const entries = /* @__PURE__ */ new Map();
2107
+ let files;
2108
+ try {
2109
+ files = options?.filter ? unzipSync(bytes, { filter: (file) => options.filter(file.name) }) : unzipSync(bytes);
2110
+ } catch (error) {
2111
+ diagnostics.push({
2112
+ level: "error",
2113
+ code: DiagnosticCode.PACKAGE_MANIFEST_MISSING,
2114
+ message: `Failed to read ZIP file: ${error instanceof Error ? error.message : String(error)}`,
2115
+ file: sourceLabel
2116
+ });
2117
+ return {
2118
+ entries,
2119
+ diagnostics
2120
+ };
2121
+ }
2122
+ for (const [rawPath, data] of Object.entries(files)) {
2123
+ if (rawPath.endsWith("/")) continue;
2124
+ const safePath = validateZipEntryPath(rawPath);
2125
+ if (safePath === null) {
2126
+ diagnostics.push({
2127
+ level: "warning",
2128
+ code: DiagnosticCode.PACKAGE_ZIP_ENTRY_UNSAFE,
2129
+ message: `Skipping unsafe ZIP entry: ${rawPath}`,
2130
+ file: sourceLabel,
2131
+ context: { entryPath: rawPath }
2132
+ });
2133
+ continue;
2134
+ }
2135
+ entries.set(safePath, {
2136
+ file: safePath,
2137
+ size: data.length,
2138
+ data
2139
+ });
2140
+ }
2141
+ return {
2142
+ entries,
2143
+ diagnostics
2144
+ };
2145
+ }
2146
+ /**
2147
+ * Encode files into deterministic ZIP bytes.
2148
+ *
2149
+ * Entries are sorted alphabetically by path and stamped with a fixed timestamp
2150
+ * so the output is reproducible for identical input.
2151
+ */
2152
+ function zipEntriesToBytes(files) {
2153
+ const sorted = [...files].sort((a, b) => a.path.localeCompare(b.path));
2154
+ const zippable = {};
2155
+ for (const file of sorted) zippable[file.path] = [file.content, {
2156
+ mtime: FIXED_MTIME,
2157
+ level: 6
2158
+ }];
2159
+ return zipSync(zippable);
2160
+ }
2161
+ /** Encode a UTF-8 string to bytes (re-exported fflate helper). */
2162
+ function textToBytes(text) {
2163
+ return strToU8(text);
2164
+ }
2165
+ //#endregion
2166
+ //#region ../core/src/qti-to-learnosity/convertQtiPackageToLearnosityBundle.ts
2167
+ /**
2168
+ * QTI Content Package → Learnosity Bundle converter (v1)
2169
+ * TASK 014
2170
+ *
2171
+ * Notes:
2172
+ * - Reuses existing IMS CP loader
2173
+ * - Streaming parsing only for XML reads
2174
+ * - Uses convertAssessmentTestToLearnosityActivity for tests → activity
2175
+ * - Uses convertQtiAssessmentItemToLearnosity for items
2176
+ * - Does not write outputs if any error diagnostics exist
2177
+ * - Deterministic ordering and stable JSON serialization
2178
+ */
2179
+ const utf8Decoder = new TextDecoder();
2180
+ /** Decode entry bytes as UTF-8 (works for both Uint8Array and Node Buffer). */
2181
+ function decodeUtf8(data) {
2182
+ return utf8Decoder.decode(data);
2183
+ }
2184
+ /** Join a base directory and a relative href using forward slashes (no fs). */
2185
+ function posixJoin(dir, rel) {
2186
+ return `${dir.replace(/\/+$/, "")}/${rel.replace(/^\.?\//, "")}`;
2187
+ }
2188
+ /**
2189
+ * Guarantee that a failed item conversion is represented by at least one
2190
+ * error-level diagnostic keyed to the item's href.
2191
+ *
2192
+ * Some converters can return without an item AND without pushing an error
2193
+ * (silent early-returns), which previously left the diagnostics report showing a
2194
+ * non-zero failed count with an empty errors array. When the per-item result
2195
+ * carried no error, this appends a synthetic {@link DiagnosticCode.QTI_ITEM_CONVERSION_FAILED}
2196
+ * so the failed count and the errors list can never diverge.
2197
+ *
2198
+ * @param itemDiagnostics - diagnostics produced for the single failed item
2199
+ * @param href - the item's manifest href (used as the diagnostic `file`)
2200
+ * @returns the diagnostics to append (either empty, when a real error already
2201
+ * exists, or a one-element array with the synthetic fallback)
2202
+ */
2203
+ function ensureFailedItemDiagnostic(itemDiagnostics, href) {
2204
+ if (itemDiagnostics.some((d) => d.level === "error")) return [];
2205
+ return [{
2206
+ code: DiagnosticCode.QTI_ITEM_CONVERSION_FAILED,
2207
+ level: "error",
2208
+ file: href,
2209
+ message: `Item conversion failed for "${href}" but produced no specific error diagnostic. The item may use an unsupported interaction or be missing required data.`
2210
+ }];
2211
+ }
2212
+ /**
2213
+ * Normalize a forward-slash relative path (collapse `.`/`//`, resolve `..`).
2214
+ * Pure replacement for `node:path`'s `normalize(...).split(sep).join('/')` on
2215
+ * the forward-slash paths used as entry keys.
2216
+ */
2217
+ function normalizePosix(p) {
2218
+ const parts = [];
2219
+ for (const seg of p.split("/")) {
2220
+ if (seg === "" || seg === ".") continue;
2221
+ if (seg === "..") {
2222
+ parts.pop();
2223
+ continue;
2224
+ }
2225
+ parts.push(seg);
2226
+ }
2227
+ return parts.join("/");
2228
+ }
2229
+ /**
2230
+ * Normalize href path by removing leading ./ sequences
2231
+ * This ensures manifest hrefs like "./items/foo.xml" match entries stored as "items/foo.xml"
2232
+ */
2233
+ function normalizeHref(href) {
2234
+ return href.replace(/^(\.\/)+/, "");
2235
+ }
2236
+ /**
2237
+ * File extensions treated as copyable assets (images, audio, video, styles,
2238
+ * fonts, etc.). Undeclared files with these extensions are copied to the bundle
2239
+ * even if the manifest omits them.
2240
+ */
2241
+ const ASSET_EXTENSIONS = [
2242
+ ".png",
2243
+ ".jpg",
2244
+ ".jpeg",
2245
+ ".gif",
2246
+ ".svg",
2247
+ ".webp",
2248
+ ".bmp",
2249
+ ".ico",
2250
+ ".mp3",
2251
+ ".mp4",
2252
+ ".wav",
2253
+ ".ogg",
2254
+ ".webm",
2255
+ ".m4a",
2256
+ ".css",
2257
+ ".woff",
2258
+ ".woff2",
2259
+ ".ttf",
2260
+ ".eot",
2261
+ ".pdf",
2262
+ ".json"
2263
+ ];
2264
+ /**
2265
+ * Merge two tag objects, combining tag values for each tag type
2266
+ * Source tags are merged into base tags, avoiding duplicates
2267
+ */
2268
+ function mergeTagObjects(base, source) {
2269
+ const result = { ...base };
2270
+ for (const [tagType, tagValues] of Object.entries(source)) if (!result[tagType]) result[tagType] = [...tagValues];
2271
+ else for (const value of tagValues) if (!result[tagType].includes(value)) result[tagType].push(value);
2272
+ return result;
2273
+ }
2274
+ /**
2275
+ * Find all assessmentTest resources
2276
+ */
2277
+ function findTestResources(resources, diagnostics) {
2278
+ const testResources = resources.filter((r) => r.type === "imsqti_test_xmlv2p2" || r.type === "imsqti_test_xmlv2p1" || r.type.includes("imsqti_test"));
2279
+ if (testResources.length === 0) {
2280
+ diagnostics.push({
2281
+ code: DiagnosticCode.QTI_PACKAGE_TEST_NOT_FOUND,
2282
+ level: "info",
2283
+ file: "imsmanifest.xml",
2284
+ message: "No assessmentTest resource found in manifest"
2285
+ });
2286
+ return [];
2287
+ }
2288
+ return testResources;
2289
+ }
2290
+ /**
2291
+ * Find an item resource in the manifest using multiple matching strategies
2292
+ */
2293
+ function findItemResource(resources, itemRef) {
2294
+ return resources.find((r) => {
2295
+ if (!r.type.includes("imsqti_item")) return false;
2296
+ if (r.identifier === itemRef) return true;
2297
+ if (r.identifier === `item_${itemRef}`) return true;
2298
+ if (r.href.includes(itemRef)) return true;
2299
+ if (itemRef.startsWith("item_") && r.identifier === itemRef.replace(/^item_/, "")) return true;
2300
+ return false;
2301
+ });
2302
+ }
2303
+ /**
2304
+ * Find all assessmentItem resources
2305
+ */
2306
+ function findItemResources(resources) {
2307
+ return resources.filter((r) => r.type === "imsqti_item_xmlv2p2" || r.type === "imsqti_item_xmlv2p1" || r.type.includes("imsqti_item"));
2308
+ }
2309
+ /**
2310
+ * Convert QTI Content Package to Learnosity Bundle
2311
+ */
2312
+ function convertQtiPackageToLearnosityBundle(input, opts) {
2313
+ const diagnostics = [];
2314
+ try {
2315
+ let entries;
2316
+ if ("zipBytes" in input) {
2317
+ const label = opts?.sourceLabel ?? "package.zip";
2318
+ const manifestOnly = unzipToEntries(input.zipBytes, label, { filter: (name) => normalizeHref(name) === "imsmanifest.xml" });
2319
+ if (manifestOnly.diagnostics.some((d) => d.level === "error")) {
2320
+ diagnostics.push(...manifestOnly.diagnostics);
2321
+ return { diagnostics };
2322
+ }
2323
+ let filter;
2324
+ const manifestForFilter = manifestOnly.entries.get("imsmanifest.xml");
2325
+ if (manifestForFilter) {
2326
+ const { resources: manifestResources } = parseManifest(decodeUtf8(manifestForFilter.data), label);
2327
+ const needed = /* @__PURE__ */ new Set(["imsmanifest.xml"]);
2328
+ for (const resource of manifestResources) needed.add(normalizeHref(resource.href));
2329
+ filter = (name) => {
2330
+ const normalized = normalizeHref(name);
2331
+ if (needed.has(normalized)) return true;
2332
+ const lower = normalized.toLowerCase();
2333
+ if (lower.endsWith(".html")) return false;
2334
+ return lower.endsWith(".xml") || ASSET_EXTENSIONS.some((ext) => lower.endsWith(ext));
2335
+ };
2336
+ }
2337
+ const unzipped = unzipToEntries(input.zipBytes, label, filter ? { filter } : void 0);
2338
+ diagnostics.push(...unzipped.diagnostics);
2339
+ if (diagnostics.some((d) => d.level === "error")) return { diagnostics };
2340
+ entries = unzipped.entries;
2341
+ } else entries = input.entries;
2342
+ const sourceLabel = opts?.sourceLabel ?? opts?.sourceDir ?? "package";
2343
+ const manifestEntry = entries.get("imsmanifest.xml");
2344
+ if (!manifestEntry) {
2345
+ diagnostics.push({
2346
+ code: DiagnosticCode.QTI_PACKAGE_MANIFEST_MISSING,
2347
+ level: "error",
2348
+ file: sourceLabel,
2349
+ message: "Package missing required imsmanifest.xml"
2350
+ });
2351
+ return { diagnostics };
2352
+ }
2353
+ const { resources, diagnostics: parseDiagnostics } = parseManifest(decodeUtf8(manifestEntry.data), sourceLabel);
2354
+ diagnostics.push(...parseDiagnostics);
2355
+ if (diagnostics.some((d) => d.level === "error")) return { diagnostics };
2356
+ const testResources = findTestResources(resources, diagnostics);
2357
+ const itemResources = findItemResources(resources);
2358
+ if (testResources.length === 0 && itemResources.length === 0) {
2359
+ diagnostics.push({
2360
+ code: DiagnosticCode.QTI_PACKAGE_NO_CONTENT,
2361
+ level: "error",
2362
+ file: "imsmanifest.xml",
2363
+ message: "No assessmentTest or assessmentItem resources found in manifest"
2364
+ });
2365
+ return { diagnostics };
2366
+ }
2367
+ const items = /* @__PURE__ */ new Map();
2368
+ const itemFilenames = /* @__PURE__ */ new Map();
2369
+ const qtiRefToMd5Refs = /* @__PURE__ */ new Map();
2370
+ const convertedSourceFiles = [];
2371
+ const failedSourceFiles = [];
2372
+ const convertedActivityFiles = [];
2373
+ const itemResourcesToConvert = [];
2374
+ const seenHrefs = /* @__PURE__ */ new Set();
2375
+ if (testResources.length > 0) for (const testResource of testResources) if (testResource.dependencies && testResource.dependencies.length > 0) for (const dep of testResource.dependencies) {
2376
+ const matchingResources = resources.filter((r) => r.type.includes("imsqti_item") && r.identifier === dep.identifierref);
2377
+ if (matchingResources.length > 0) {
2378
+ for (const res of matchingResources) if (!seenHrefs.has(res.href)) {
2379
+ seenHrefs.add(res.href);
2380
+ itemResourcesToConvert.push(res);
2381
+ }
2382
+ } else {
2383
+ const singleMatch = findItemResource(resources, dep.identifierref);
2384
+ if (singleMatch && !seenHrefs.has(singleMatch.href)) {
2385
+ seenHrefs.add(singleMatch.href);
2386
+ itemResourcesToConvert.push(singleMatch);
2387
+ }
2388
+ }
2389
+ }
2390
+ else {
2391
+ const normalizedTestHref = normalizeHref(testResource.href);
2392
+ const testEntry = entries.get(normalizedTestHref);
2393
+ if (!testEntry) {
2394
+ diagnostics.push({
2395
+ code: DiagnosticCode.QTI_PACKAGE_TEST_NOT_FOUND,
2396
+ level: "error",
2397
+ file: testResource.href,
2398
+ message: `Test file not found: ${testResource.href}`
2399
+ });
2400
+ continue;
2401
+ }
2402
+ const testResult = convertAssessmentTestToLearnosityActivity(decodeUtf8(testEntry.data));
2403
+ diagnostics.push(...testResult.diagnostics);
2404
+ if (testResult.activity) for (const item of testResult.activity.items) {
2405
+ const matchingResources = resources.filter((r) => r.type.includes("imsqti_item") && r.identifier === item.reference);
2406
+ const toAdd = matchingResources.length > 0 ? matchingResources : [findItemResource(resources, item.reference)].filter(Boolean);
2407
+ for (const res of toAdd) if (!seenHrefs.has(res.href)) {
2408
+ seenHrefs.add(res.href);
2409
+ itemResourcesToConvert.push(res);
2410
+ }
2411
+ }
2412
+ }
2413
+ else for (const itemResource of itemResources) if (!seenHrefs.has(itemResource.href)) {
2414
+ seenHrefs.add(itemResource.href);
2415
+ itemResourcesToConvert.push(itemResource);
2416
+ }
2417
+ for (const itemResource of itemResourcesToConvert) {
2418
+ const normalizedItemHref = normalizeHref(itemResource.href);
2419
+ const itemEntry = entries.get(normalizedItemHref);
2420
+ if (!itemEntry) {
2421
+ diagnostics.push({
2422
+ code: DiagnosticCode.QTI_PACKAGE_ITEM_NOT_FOUND,
2423
+ level: "error",
2424
+ file: itemResource.href,
2425
+ message: `Item file not found: ${itemResource.href}`
2426
+ });
2427
+ continue;
2428
+ }
2429
+ const itemXml = decodeUtf8(itemEntry.data);
2430
+ const itemFilePath = opts?.sourceDir ? posixJoin(opts.sourceDir, itemResource.href) : itemResource.href;
2431
+ const itemResult = convertQtiAssessmentItemToLearnosity(itemXml, {
2432
+ inputPath: itemFilePath,
2433
+ sourceFile: itemFilePath,
2434
+ organisationId: opts?.organisationId,
2435
+ mediaVault: opts?.mediaVault,
2436
+ customAssetUrl: opts?.customAssetUrl,
2437
+ itemReferenceSource: opts?.itemReferenceSource,
2438
+ fileAccess: opts?.fileAccess,
2439
+ packageRoot: opts?.sourceDir
2440
+ });
2441
+ diagnostics.push(...itemResult.diagnostics);
2442
+ if (itemResult.item) {
2443
+ let md5Ref = itemResult.item.item.reference;
2444
+ if (items.has(md5Ref)) {
2445
+ const hrefParts = itemResource.href.split("/");
2446
+ const filename = hrefParts[hrefParts.length - 1].replace(/\.xml$/i, "");
2447
+ md5Ref = `${md5Ref}_${filename}`;
2448
+ itemResult.item.item.reference = md5Ref;
2449
+ for (const question of itemResult.item.questions) {
2450
+ const oldRef = question.reference;
2451
+ const newRef = md5hex(`${md5Ref}_${oldRef}`);
2452
+ question.reference = newRef;
2453
+ const widget = itemResult.item.item.definition.widgets.find((w) => w.reference === oldRef);
2454
+ if (widget) widget.reference = newRef;
2455
+ if (itemResult.item.item.content) itemResult.item.item.content = itemResult.item.item.content.replace(`question-${oldRef}`, `question-${newRef}`);
2456
+ }
2457
+ diagnostics.push({
2458
+ code: DiagnosticCode.QTI_PACKAGE_DUPLICATE_IDENTIFIER,
2459
+ level: "warning",
2460
+ file: itemResource.href,
2461
+ message: `Duplicate item reference "${itemResult.item.item.reference}" disambiguated from "${md5Ref.replace(`_${filename}`, "")}" (source: ${itemResource.href})`
2462
+ });
2463
+ }
2464
+ if (itemResource.metadataXml) try {
2465
+ const tagResult = parseMetadataTags(itemResource.metadataXml, {
2466
+ truncateTags: opts?.truncateTags,
2467
+ filePath: itemResource.href
2468
+ });
2469
+ diagnostics.push(...tagResult.diagnostics);
2470
+ const mergedTags = mergeTagObjects(itemResult.item.item.tags ?? {}, tagResult.tags);
2471
+ if (Object.keys(mergedTags).length > 0) itemResult.item.item.tags = mergedTags;
2472
+ } catch (err) {
2473
+ diagnostics.push({
2474
+ code: DiagnosticCode.QTI_METADATA_TAG_TOO_LONG,
2475
+ level: "error",
2476
+ file: itemResource.href,
2477
+ message: err instanceof Error ? err.message : String(err)
2478
+ });
2479
+ }
2480
+ items.set(md5Ref, itemResult.item);
2481
+ const filenameSource = opts?.itemFilenameSource;
2482
+ if (filenameSource && filenameSource !== (opts.itemReferenceSource ?? "sourceFilename")) {
2483
+ const qtiIdentifier = itemXml.match(/<assessmentItem[^>]+identifier="([^"]+)"/)?.[1] ?? md5Ref;
2484
+ const filename = generateItemReference(qtiIdentifier, filenameSource, itemFilePath);
2485
+ itemFilenames.set(md5Ref, filename);
2486
+ }
2487
+ if (!qtiRefToMd5Refs.has(itemResource.identifier)) qtiRefToMd5Refs.set(itemResource.identifier, []);
2488
+ qtiRefToMd5Refs.get(itemResource.identifier)?.push(md5Ref);
2489
+ convertedSourceFiles.push(itemResource.href);
2490
+ } else {
2491
+ failedSourceFiles.push(itemResource.href);
2492
+ diagnostics.push(...ensureFailedItemDiagnostic(itemResult.diagnostics, itemResource.href));
2493
+ }
2494
+ }
2495
+ if (items.size === 0 && itemResourcesToConvert.length > 0) {
2496
+ diagnostics.push({
2497
+ code: DiagnosticCode.QTI_PACKAGE_ITEM_NOT_FOUND,
2498
+ level: "error",
2499
+ file: "package",
2500
+ message: `No items could be converted from the package (${itemResourcesToConvert.length} items found but all failed conversion)`
2501
+ });
2502
+ return { diagnostics };
2503
+ }
2504
+ const activities = /* @__PURE__ */ new Map();
2505
+ const activitiesManifest = {};
2506
+ if (testResources.length > 0) for (const testResource of testResources) {
2507
+ let activityReference;
2508
+ if (opts?.itemReferenceSource === "qti") activityReference = testResource.identifier;
2509
+ else {
2510
+ const hrefParts = testResource.href.split("/");
2511
+ activityReference = hrefParts[hrefParts.length - 1].replace(/\.xml$/i, "");
2512
+ }
2513
+ const activityItems = [];
2514
+ if (testResource.dependencies && testResource.dependencies.length > 0) {
2515
+ const refCounters = /* @__PURE__ */ new Map();
2516
+ for (const dep of testResource.dependencies) {
2517
+ const qtiRef = dep.identifierref;
2518
+ const md5Refs = qtiRefToMd5Refs.get(qtiRef);
2519
+ const index = refCounters.get(qtiRef) ?? 0;
2520
+ const learnosityRef = md5Refs?.at(index) ?? md5Refs?.at(0) ?? qtiRef;
2521
+ refCounters.set(qtiRef, index + 1);
2522
+ if (items.has(learnosityRef)) activityItems.push({
2523
+ reference: learnosityRef,
2524
+ id: learnosityRef
2525
+ });
2526
+ }
2527
+ } else {
2528
+ const normalizedTestHref = normalizeHref(testResource.href);
2529
+ const testEntry = entries.get(normalizedTestHref);
2530
+ if (testEntry) {
2531
+ const testResult = convertAssessmentTestToLearnosityActivity(decodeUtf8(testEntry.data));
2532
+ if (testResult.activity) {
2533
+ const refCounters = /* @__PURE__ */ new Map();
2534
+ for (const item of testResult.activity.items) {
2535
+ const md5Refs = qtiRefToMd5Refs.get(item.reference);
2536
+ const index = refCounters.get(item.reference) ?? 0;
2537
+ const learnosityRef = md5Refs?.at(index) ?? md5Refs?.at(0) ?? item.reference;
2538
+ refCounters.set(item.reference, index + 1);
2539
+ activityItems.push({
2540
+ reference: learnosityRef,
2541
+ id: learnosityRef
2542
+ });
2543
+ }
2544
+ }
2545
+ }
2546
+ }
2547
+ let activityTags = {};
2548
+ if (testResource.metadataXml) try {
2549
+ const tagResult = parseMetadataTags(testResource.metadataXml, {
2550
+ truncateTags: opts?.truncateTags,
2551
+ filePath: testResource.href
2552
+ });
2553
+ diagnostics.push(...tagResult.diagnostics);
2554
+ activityTags = tagResult.tags;
2555
+ } catch (err) {
2556
+ diagnostics.push({
2557
+ code: DiagnosticCode.QTI_METADATA_TAG_TOO_LONG,
2558
+ level: "error",
2559
+ file: testResource.href,
2560
+ message: err instanceof Error ? err.message : String(err)
2561
+ });
2562
+ }
2563
+ const activity = {
2564
+ reference: activityReference,
2565
+ rendering_type: "assess",
2566
+ items: activityItems,
2567
+ config: {
2568
+ navigation: {
2569
+ show_intro: true,
2570
+ show_outro: true
2571
+ },
2572
+ regions: "main"
2573
+ },
2574
+ tags: Object.keys(activityTags).length > 0 ? activityTags : void 0
2575
+ };
2576
+ activities.set(activityReference, activity);
2577
+ activitiesManifest[activityReference] = { items: activityItems };
2578
+ convertedActivityFiles.push(testResource.href);
2579
+ }
2580
+ else {
2581
+ const activityId = "standalone_items_activity";
2582
+ const activityItems = Array.from(items.values()).map((item) => ({
2583
+ id: item.item.reference,
2584
+ reference: item.item.reference
2585
+ }));
2586
+ const defaultActivity = {
2587
+ reference: activityId,
2588
+ title: "Standalone Items",
2589
+ rendering_type: "assess",
2590
+ items: activityItems,
2591
+ config: { regions: "main" },
2592
+ status: "published",
2593
+ tags: {}
2594
+ };
2595
+ activities.set(activityId, defaultActivity);
2596
+ activitiesManifest[activityId] = { items: activityItems };
2597
+ }
2598
+ const assets = /* @__PURE__ */ new Map();
2599
+ const copiedPaths = /* @__PURE__ */ new Set();
2600
+ for (const resource of resources) if (resource.type === "webcontent" || resource.type.includes("associated")) {
2601
+ if (resource.href.toLowerCase().endsWith(".html")) continue;
2602
+ const assetEntry = entries.get(resource.href);
2603
+ if (assetEntry) {
2604
+ const normalizedPath = normalizePosix(resource.href);
2605
+ assets.set(normalizedPath, new Uint8Array(assetEntry.data));
2606
+ copiedPaths.add(resource.href);
2607
+ }
2608
+ }
2609
+ for (const [path, entry] of entries) {
2610
+ if (copiedPaths.has(path)) continue;
2611
+ if (path === "imsmanifest.xml" || path.endsWith(".xml")) continue;
2612
+ const lowerPath = path.toLowerCase();
2613
+ if (ASSET_EXTENSIONS.some((ext) => lowerPath.endsWith(ext))) {
2614
+ const normalizedPath = normalizePosix(path);
2615
+ assets.set(normalizedPath, new Uint8Array(entry.data));
2616
+ copiedPaths.add(path);
2617
+ }
2618
+ }
2619
+ return {
2620
+ bundle: {
2621
+ manifest: {
2622
+ diagnostics: {
2623
+ version: opts?.packageVersion ?? "unknown",
2624
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2625
+ configuration: {
2626
+ organisationId: opts?.organisationId,
2627
+ mediaVault: opts?.mediaVault ?? false,
2628
+ customAssetUrl: opts?.customAssetUrl,
2629
+ itemReferenceSource: opts?.itemReferenceSource ?? "sourceFilename"
2630
+ }
2631
+ },
2632
+ items: Array.from(items.keys()).sort(),
2633
+ activities: activitiesManifest,
2634
+ assets: { items: Object.fromEntries(Array.from(items.keys()).sort().map((itemRef) => {
2635
+ const questions = items.get(itemRef)?.questions ?? [];
2636
+ return [itemRef, { questions: Object.fromEntries(questions.map((q) => [q.reference, []])) }];
2637
+ })) }
2638
+ },
2639
+ activities,
2640
+ items,
2641
+ assets,
2642
+ itemFilenames: itemFilenames.size > 0 ? itemFilenames : void 0
2643
+ },
2644
+ diagnostics,
2645
+ convertedSourceFiles,
2646
+ failedSourceFiles,
2647
+ convertedActivityFiles
2648
+ };
2649
+ } catch (error) {
2650
+ diagnostics.push({
2651
+ code: DiagnosticCode.LRN_SCHEMA_INVALID,
2652
+ level: "error",
2653
+ file: "root",
2654
+ message: `Failed to convert package: ${error instanceof Error ? error.message : "Unknown error"}`
2655
+ });
2656
+ return { diagnostics };
2657
+ }
2658
+ }
2659
+ //#endregion
2660
+ //#region ../core/src/qti-package/writeZip.ts
2661
+ /**
2662
+ * Deterministic ZIP writing (Node.js file-path entry point).
2663
+ *
2664
+ * Normalizes content to bytes, delegates encoding to the pure `zipCodec`
2665
+ * (which sorts entries and applies a fixed timestamp for reproducibility), then
2666
+ * writes the archive to disk.
2667
+ */
2668
+ /**
2669
+ * Writes files to a ZIP archive with deterministic output
2670
+ *
2671
+ * Features:
2672
+ * - Entries sorted alphabetically by path
2673
+ * - Fixed timestamp (2000-01-01 00:00:00 UTC) for reproducibility
2674
+ * - Consistent compression settings
2675
+ *
2676
+ * @param zipPath Output ZIP file path
2677
+ * @param files Array of files to include
2678
+ */
2679
+ function writeZip(zipPath, files) {
2680
+ const entries = files.map((file) => ({
2681
+ path: file.path,
2682
+ content: typeof file.content === "string" ? textToBytes(file.content) : file.content
2683
+ }));
2684
+ writeFileSync(zipPath, zipEntriesToBytes(entries));
2685
+ }
2686
+ //#endregion
2687
+ //#region ../core/src/qti-package/savePackage.ts
2688
+ /**
2689
+ * QTI Content Package saving to ZIP or directory
2690
+ */
2691
+ /**
2692
+ * Saves a QTI Content Package to a ZIP file or directory
2693
+ *
2694
+ * Steps:
2695
+ * 1. Build imsmanifest.xml from resources
2696
+ * 2. Collect all file entries
2697
+ * 3. Write to ZIP or directory based on output path
2698
+ *
2699
+ * @param pkg Package to save
2700
+ * @param outputPath Output ZIP file path or directory path
2701
+ * @returns Diagnostics from saving
2702
+ */
2703
+ function saveQtiContentPackage(pkg, outputPath) {
2704
+ const diagnostics = [];
2705
+ const manifestXml = buildManifest(pkg.resources, pkg.version ?? "2.2");
2706
+ const files = [];
2707
+ files.push({
2708
+ path: "imsmanifest.xml",
2709
+ content: manifestXml
2710
+ });
2711
+ for (const [filePath, entry] of pkg.entries) files.push({
2712
+ path: filePath,
2713
+ content: entry.data
2714
+ });
2715
+ const isZipOutput = outputPath.toLowerCase().endsWith(".zip");
2716
+ if (isZipOutput) writeZip(outputPath, files);
2717
+ else writeDirectory(outputPath, files);
2718
+ diagnostics.push({
2719
+ level: "info",
2720
+ code: DiagnosticCode.PACKAGE_WRITTEN,
2721
+ message: `Wrote package with ${pkg.items.length} items and ${pkg.assets.length} assets to ${isZipOutput ? "ZIP" : "directory"}`,
2722
+ file: outputPath
2723
+ });
2724
+ return { diagnostics };
2725
+ }
2726
+ /**
2727
+ * Writes files to a directory
2728
+ *
2729
+ * @param dirPath Output directory path
2730
+ * @param files Array of files to write
2731
+ */
2732
+ function writeDirectory(dirPath, files) {
2733
+ if (!fs$1.existsSync(dirPath)) fs$1.mkdirSync(dirPath, { recursive: true });
2734
+ for (const file of files) {
2735
+ const fullPath = path$1.join(dirPath, file.path);
2736
+ if (file.path.endsWith("/")) {
2737
+ if (!fs$1.existsSync(fullPath)) fs$1.mkdirSync(fullPath, { recursive: true });
2738
+ continue;
2739
+ }
2740
+ const dir = path$1.dirname(fullPath);
2741
+ if (!fs$1.existsSync(dir)) fs$1.mkdirSync(dir, { recursive: true });
2742
+ const content = typeof file.content === "string" ? file.content : file.content;
2743
+ fs$1.writeFileSync(fullPath, content);
2744
+ }
2745
+ }
2746
+ //#endregion
2747
+ //#region ../core/src/learnosity-bundle/pathSafetyFs.ts
2748
+ /**
2749
+ * Path safety validation for filesystem operations
2750
+ * Part of TASK 004D - prevents directory traversal attacks similar to zip-slip protection
2751
+ */
2752
+ /**
2753
+ * Validate that a relative path is safe to use within a base directory
2754
+ *
2755
+ * Safety rules:
2756
+ * - Must be relative (no absolute paths)
2757
+ * - No ".." traversal
2758
+ * - No symlinks
2759
+ * - Normalized separators
2760
+ *
2761
+ * @param relativePath - Path to validate (relative to baseDir)
2762
+ * @param baseDir - Base directory that all paths must stay within
2763
+ * @returns true if safe, false otherwise
2764
+ */
2765
+ function isPathSafe(relativePath, baseDir) {
2766
+ if (path$1.isAbsolute(relativePath)) return false;
2767
+ const normalized = path$1.normalize(relativePath);
2768
+ if (normalized.includes("..")) return false;
2769
+ const fullPath = path$1.join(baseDir, normalized);
2770
+ const resolvedBase = path$1.resolve(baseDir);
2771
+ const resolvedFull = path$1.resolve(fullPath);
2772
+ if (!resolvedFull.startsWith(resolvedBase + path$1.sep) && resolvedFull !== resolvedBase) return false;
2773
+ return true;
2774
+ }
2775
+ /**
2776
+ * Check if a path points to a symlink
2777
+ *
2778
+ * @param fullPath - Absolute path to check
2779
+ * @returns true if symlink, false otherwise (or if path doesn't exist)
2780
+ */
2781
+ function isSymlink(fullPath) {
2782
+ try {
2783
+ return fs$1.lstatSync(fullPath).isSymbolicLink();
2784
+ } catch {
2785
+ return false;
2786
+ }
2787
+ }
2788
+ /**
2789
+ * Safely resolve a relative path within a base directory
2790
+ * Returns null if the path is unsafe or points to a symlink
2791
+ *
2792
+ * @param relativePath - Path to resolve (relative to baseDir)
2793
+ * @param baseDir - Base directory
2794
+ * @returns Absolute path if safe, null otherwise
2795
+ */
2796
+ function safeResolve(relativePath, baseDir) {
2797
+ if (!isPathSafe(relativePath, baseDir)) return null;
2798
+ const fullPath = path$1.join(baseDir, relativePath);
2799
+ if (isSymlink(fullPath)) return null;
2800
+ return fullPath;
2801
+ }
2802
+ //#endregion
2803
+ //#region ../core/src/learnosity-bundle/loadLearnosityBundle.ts
2804
+ /**
2805
+ * Learnosity bundle loader (manifest.json + activities + items + assets)
2806
+ * Part of TASK 004D
2807
+ */
2808
+ /**
2809
+ * Load a Learnosity export bundle from a directory
2810
+ *
2811
+ * @param bundleDir - Absolute path to bundle directory
2812
+ * @returns { bundle?, diagnostics[] }
2813
+ */
2814
+ function loadLearnosityBundle(bundleDir) {
2815
+ const diagnostics = [];
2816
+ if (!fs$1.existsSync(bundleDir)) {
2817
+ diagnostics.push({
2818
+ code: DiagnosticCode.LRN_BUNDLE_DIR_NOT_FOUND,
2819
+ level: "error",
2820
+ file: bundleDir,
2821
+ message: `Bundle directory not found: ${bundleDir}`
2822
+ });
2823
+ return { diagnostics };
2824
+ }
2825
+ if (!fs$1.statSync(bundleDir).isDirectory()) {
2826
+ diagnostics.push({
2827
+ code: DiagnosticCode.LRN_BUNDLE_DIR_NOT_FOUND,
2828
+ level: "error",
2829
+ file: bundleDir,
2830
+ message: `Path is not a directory: ${bundleDir}`
2831
+ });
2832
+ return { diagnostics };
2833
+ }
2834
+ const manifestPath = path$1.join(bundleDir, "manifest.json");
2835
+ if (!fs$1.existsSync(manifestPath)) {
2836
+ diagnostics.push({
2837
+ code: DiagnosticCode.LRN_MANIFEST_MISSING,
2838
+ level: "error",
2839
+ file: "manifest.json",
2840
+ message: "Manifest file not found: manifest.json"
2841
+ });
2842
+ return { diagnostics };
2843
+ }
2844
+ let manifestRaw;
2845
+ try {
2846
+ const manifestContent = fs$1.readFileSync(manifestPath, "utf-8");
2847
+ manifestRaw = JSON.parse(manifestContent);
2848
+ } catch (err) {
2849
+ diagnostics.push({
2850
+ code: DiagnosticCode.LRN_MANIFEST_INVALID_JSON,
2851
+ level: "error",
2852
+ file: "manifest.json",
2853
+ message: `Invalid JSON in manifest.json: ${err instanceof Error ? err.message : String(err)}`
2854
+ });
2855
+ return { diagnostics };
2856
+ }
2857
+ const manifest = validateManifest(manifestRaw, diagnostics);
2858
+ if (!manifest) return { diagnostics };
2859
+ const itemsDir = path$1.join(bundleDir, "items");
2860
+ const autoCreatedActivities = /* @__PURE__ */ new Set();
2861
+ if (Object.keys(manifest.activities).length === 0 && fs$1.existsSync(itemsDir) && fs$1.statSync(itemsDir).isDirectory()) {
2862
+ const itemFiles = fs$1.readdirSync(itemsDir).filter((f) => f.endsWith(".json"));
2863
+ if (itemFiles.length > 0) {
2864
+ const defaultActivityRef = "default_activity";
2865
+ const items = itemFiles.map((f) => ({ reference: f.replace(/\.json$/, "") }));
2866
+ manifest.activities[defaultActivityRef] = { items };
2867
+ autoCreatedActivities.add(defaultActivityRef);
2868
+ diagnostics.push({
2869
+ code: DiagnosticCode.LRN_BUNDLE_AUTO_ACTIVITY_CREATED,
2870
+ level: "info",
2871
+ file: "manifest.activities",
2872
+ message: `Auto-created activity '${defaultActivityRef}' with ${items.length} items from items directory`
2873
+ });
2874
+ }
2875
+ }
2876
+ const activityRefs = Object.keys(manifest.activities);
2877
+ const activityItemRefs = /* @__PURE__ */ new Map();
2878
+ const activitiesJsonByRef = /* @__PURE__ */ new Map();
2879
+ const itemsJsonByRef = /* @__PURE__ */ new Map();
2880
+ const itemRefToFilename = /* @__PURE__ */ new Map();
2881
+ const allItemRefs = /* @__PURE__ */ new Set();
2882
+ const itemRefToId = /* @__PURE__ */ new Map();
2883
+ if (manifest.items && Array.isArray(manifest.items)) {
2884
+ for (const item of manifest.items) if (item && typeof item === "object" && "reference" in item && "id" in item) {
2885
+ const itemObj = item;
2886
+ if (typeof itemObj.reference === "string" && typeof itemObj.id === "string") itemRefToId.set(itemObj.reference, itemObj.id);
2887
+ }
2888
+ }
2889
+ for (const activityRef of Object.keys(manifest.activities)) {
2890
+ const activity = manifest.activities[activityRef];
2891
+ for (const item of activity.items) if (item.id) itemRefToId.set(item.reference, item.id);
2892
+ }
2893
+ for (const activityRef of activityRefs) {
2894
+ const itemRefs = manifest.activities[activityRef].items.map((item) => item.reference);
2895
+ const seen = /* @__PURE__ */ new Set();
2896
+ for (const itemRef of itemRefs) {
2897
+ if (seen.has(itemRef)) diagnostics.push({
2898
+ code: DiagnosticCode.LRN_ACTIVITY_DUPLICATE_ITEM_REF,
2899
+ level: "warning",
2900
+ file: `manifest.activities[${activityRef}].items`,
2901
+ message: `Activity "${activityRef}" references item "${itemRef}" multiple times`
2902
+ });
2903
+ seen.add(itemRef);
2904
+ allItemRefs.add(itemRef);
2905
+ }
2906
+ activityItemRefs.set(activityRef, itemRefs);
2907
+ let activityFilePath = `activities/${activityRef}.json`;
2908
+ let activityFullPath = safeResolve(activityFilePath, bundleDir);
2909
+ if (!activityFullPath || !fs$1.existsSync(activityFullPath)) {
2910
+ activityFilePath = `activities/${`${md5Hash(activityRef)}.json`}`;
2911
+ activityFullPath = safeResolve(activityFilePath, bundleDir);
2912
+ }
2913
+ if (!activityFullPath) {
2914
+ diagnostics.push({
2915
+ code: DiagnosticCode.LRN_PATH_UNSAFE,
2916
+ level: "error",
2917
+ file: activityFilePath,
2918
+ message: `Unsafe path detected: ${activityFilePath}`
2919
+ });
2920
+ continue;
2921
+ }
2922
+ if (!fs$1.existsSync(activityFullPath)) {
2923
+ if (!autoCreatedActivities.has(activityRef)) diagnostics.push({
2924
+ code: DiagnosticCode.LRN_ACTIVITY_FILE_MISSING,
2925
+ level: "warning",
2926
+ file: activityFilePath,
2927
+ message: `Activity file not found: ${activityFilePath}`
2928
+ });
2929
+ continue;
2930
+ }
2931
+ try {
2932
+ const activityContent = fs$1.readFileSync(activityFullPath, "utf-8");
2933
+ const activityJson = JSON.parse(activityContent);
2934
+ activitiesJsonByRef.set(activityRef, activityJson);
2935
+ if (itemRefs.length === 0 && activityJson && typeof activityJson === "object" && "data" in activityJson) {
2936
+ const data = activityJson.data;
2937
+ if (data && typeof data === "object" && "sections" in data && Array.isArray(data.sections)) {
2938
+ const extractedItemRefs = [];
2939
+ for (const section of data.sections) if (section && typeof section === "object" && "items" in section && Array.isArray(section.items)) for (const item of section.items) {
2940
+ const itemRef = typeof item === "string" ? item : item?.reference ?? item?.id;
2941
+ if (itemRef && typeof itemRef === "string") {
2942
+ extractedItemRefs.push(itemRef);
2943
+ allItemRefs.add(itemRef);
2944
+ }
2945
+ }
2946
+ if (extractedItemRefs.length > 0) {
2947
+ activityItemRefs.set(activityRef, extractedItemRefs);
2948
+ diagnostics.push({
2949
+ code: DiagnosticCode.LRN_ACTIVITY_FILE_MISSING,
2950
+ level: "info",
2951
+ file: activityFilePath,
2952
+ message: `Activity has sections: extracted ${extractedItemRefs.length} item references from activity JSON`
2953
+ });
2954
+ }
2955
+ }
2956
+ }
2957
+ } catch (err) {
2958
+ diagnostics.push({
2959
+ code: DiagnosticCode.LRN_ACTIVITY_FILE_INVALID_JSON,
2960
+ level: "error",
2961
+ file: activityFilePath,
2962
+ message: `Invalid JSON in activity file: ${err instanceof Error ? err.message : String(err)}`
2963
+ });
2964
+ }
2965
+ }
2966
+ for (const itemRef of allItemRefs) {
2967
+ const originalItemFilePath = `items/${itemRef}.json`;
2968
+ let itemFilePath = originalItemFilePath;
2969
+ let itemFullPath = safeResolve(itemFilePath, bundleDir);
2970
+ if (!itemFullPath || !fs$1.existsSync(itemFullPath)) {
2971
+ itemFilePath = `items/${`${md5Hash(itemRef)}.json`}`;
2972
+ itemFullPath = safeResolve(itemFilePath, bundleDir);
2973
+ }
2974
+ if ((!itemFullPath || !fs$1.existsSync(itemFullPath)) && itemRefToId.has(itemRef)) {
2975
+ itemFilePath = `items/${`${md5Hash(itemRefToId.get(itemRef))}.json`}`;
2976
+ itemFullPath = safeResolve(itemFilePath, bundleDir);
2977
+ }
2978
+ if (!itemFullPath) {
2979
+ diagnostics.push({
2980
+ code: DiagnosticCode.LRN_PATH_UNSAFE,
2981
+ level: "error",
2982
+ file: originalItemFilePath,
2983
+ message: `Unsafe path detected: ${originalItemFilePath}`
2984
+ });
2985
+ continue;
2986
+ }
2987
+ if (!fs$1.existsSync(itemFullPath)) {
2988
+ diagnostics.push({
2989
+ code: DiagnosticCode.LRN_ITEM_FILE_MISSING,
2990
+ level: "error",
2991
+ file: originalItemFilePath,
2992
+ message: `Item file not found: ${originalItemFilePath}`
2993
+ });
2994
+ continue;
2995
+ }
2996
+ try {
2997
+ const itemContent = fs$1.readFileSync(itemFullPath, "utf-8");
2998
+ const itemJson = JSON.parse(itemContent);
2999
+ itemsJsonByRef.set(itemRef, itemJson);
3000
+ itemRefToFilename.set(itemRef, itemFilePath);
3001
+ if (itemJson && typeof itemJson === "object" && "reference" in itemJson) {
3002
+ const reference = itemJson.reference;
3003
+ if (typeof reference === "string" && reference !== itemRef) {
3004
+ itemsJsonByRef.set(reference, itemJson);
3005
+ itemRefToFilename.set(reference, itemFilePath);
3006
+ }
3007
+ }
3008
+ } catch (err) {
3009
+ diagnostics.push({
3010
+ code: DiagnosticCode.LRN_ITEM_FILE_INVALID_JSON,
3011
+ level: "error",
3012
+ file: itemFilePath,
3013
+ message: `Invalid JSON in item file: ${err instanceof Error ? err.message : String(err)}`
3014
+ });
3015
+ }
3016
+ }
3017
+ if (diagnostics.some((d) => d.level === "error")) return { diagnostics };
3018
+ return {
3019
+ bundle: {
3020
+ manifest,
3021
+ activityRefs,
3022
+ activityItemRefs,
3023
+ activitiesJsonByRef,
3024
+ itemsJsonByRef,
3025
+ itemRefToFilename
3026
+ },
3027
+ diagnostics
3028
+ };
3029
+ }
3030
+ /**
3031
+ * Validate manifest schema
3032
+ *
3033
+ * @param raw - Raw manifest JSON
3034
+ * @param diagnostics - Array to append diagnostics to
3035
+ * @returns Validated manifest or null if invalid
3036
+ */
3037
+ function validateManifest(raw, diagnostics) {
3038
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
3039
+ diagnostics.push({
3040
+ code: DiagnosticCode.LRN_MANIFEST_SCHEMA_INVALID,
3041
+ level: "error",
3042
+ file: "manifest",
3043
+ message: "Manifest root must be an object"
3044
+ });
3045
+ return null;
3046
+ }
3047
+ const obj = raw;
3048
+ let activities = {};
3049
+ if ("activities" in obj) {
3050
+ if (typeof obj.activities !== "object" || obj.activities === null || Array.isArray(obj.activities)) {
3051
+ diagnostics.push({
3052
+ code: DiagnosticCode.LRN_MANIFEST_SCHEMA_INVALID,
3053
+ level: "error",
3054
+ file: "manifest.activities",
3055
+ message: "Manifest.activities must be an object"
3056
+ });
3057
+ return null;
3058
+ }
3059
+ activities = obj.activities;
3060
+ }
3061
+ const validatedActivities = {};
3062
+ for (const activityRef of Object.keys(activities)) {
3063
+ const activity = activities[activityRef];
3064
+ if (typeof activity !== "object" || activity === null || Array.isArray(activity)) {
3065
+ diagnostics.push({
3066
+ code: DiagnosticCode.LRN_MANIFEST_SCHEMA_INVALID,
3067
+ level: "error",
3068
+ file: `manifest.activities[${activityRef}]`,
3069
+ message: `Activity "${activityRef}" must be an object`
3070
+ });
3071
+ return null;
3072
+ }
3073
+ const activityObj = activity;
3074
+ if (!("items" in activityObj) || !Array.isArray(activityObj.items)) {
3075
+ diagnostics.push({
3076
+ code: DiagnosticCode.LRN_MANIFEST_SCHEMA_INVALID,
3077
+ level: "error",
3078
+ file: `manifest.activities[${activityRef}].items`,
3079
+ message: `Activity "${activityRef}" must have an items array`
3080
+ });
3081
+ return null;
3082
+ }
3083
+ const items = [];
3084
+ for (let i = 0; i < activityObj.items.length; i++) {
3085
+ const item = activityObj.items[i];
3086
+ if (typeof item !== "object" || item === null || Array.isArray(item)) {
3087
+ diagnostics.push({
3088
+ code: DiagnosticCode.LRN_MANIFEST_SCHEMA_INVALID,
3089
+ level: "error",
3090
+ file: `manifest.activities[${activityRef}].items[${i}]`,
3091
+ message: `Item at index ${i} must be an object`
3092
+ });
3093
+ return null;
3094
+ }
3095
+ const itemObj = item;
3096
+ if (!("reference" in itemObj) || typeof itemObj.reference !== "string") {
3097
+ diagnostics.push({
3098
+ code: DiagnosticCode.LRN_MANIFEST_SCHEMA_INVALID,
3099
+ level: "error",
3100
+ file: `manifest.activities[${activityRef}].items[${i}].reference`,
3101
+ message: `Item at index ${i} must have a reference string`
3102
+ });
3103
+ return null;
3104
+ }
3105
+ items.push({
3106
+ reference: itemObj.reference,
3107
+ id: itemObj.id !== void 0 ? itemObj.id : void 0
3108
+ });
3109
+ }
3110
+ validatedActivities[activityRef] = { items };
3111
+ }
3112
+ const knownKeys = [
3113
+ "activities",
3114
+ "items",
3115
+ "assets",
3116
+ "diagnostics"
3117
+ ];
3118
+ for (const key of Object.keys(obj)) if (!knownKeys.includes(key)) diagnostics.push({
3119
+ code: DiagnosticCode.LRN_MANIFEST_UNUSED_KEY,
3120
+ level: "warning",
3121
+ file: `manifest.${key}`,
3122
+ message: `Unknown key in manifest: "${key}"`
3123
+ });
3124
+ return {
3125
+ activities: validatedActivities,
3126
+ items: obj.items,
3127
+ assets: obj.assets
3128
+ };
3129
+ }
3130
+ /**
3131
+ * Compute MD5 hash of a string (used for hashed filenames)
3132
+ * @param str - String to hash
3133
+ * @returns MD5 hash in lowercase hex
3134
+ */
3135
+ function md5Hash(str) {
3136
+ return crypto.createHash("md5").update(str).digest("hex");
3137
+ }
3138
+ //#endregion
3139
+ //#region ../core/src/learnosity-bundle/writeLearnosityBundle.ts
3140
+ /**
3141
+ * Write Learnosity Bundle to directory with deterministic JSON
3142
+ * TASK 014
3143
+ */
3144
+ /**
3145
+ * Deterministic JSON stringify with sorted keys
3146
+ */
3147
+ function stringifyDeterministic(obj) {
3148
+ return JSON.stringify(obj, (_key, value) => {
3149
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3150
+ const sorted = {};
3151
+ for (const k of Object.keys(value).sort()) sorted[k] = value[k];
3152
+ return sorted;
3153
+ }
3154
+ return value;
3155
+ }, 2);
3156
+ }
3157
+ /**
3158
+ * Write Learnosity Bundle to directory or ZIP
3159
+ */
3160
+ async function writeLearnosityBundle(bundle, options) {
3161
+ const diagnostics = [];
3162
+ try {
3163
+ const { outDir, isZipOutput = false } = options;
3164
+ if (isZipOutput) {
3165
+ const files = [];
3166
+ files.push({
3167
+ path: "manifest.json",
3168
+ content: stringifyDeterministic(bundle.manifest)
3169
+ });
3170
+ for (const [activityId, activity] of bundle.activities) files.push({
3171
+ path: `activities/${activityId}.json`,
3172
+ content: stringifyDeterministic(activity)
3173
+ });
3174
+ for (const [itemRef, item] of bundle.items) {
3175
+ const filename = bundle.itemFilenames?.get(itemRef) ?? itemRef;
3176
+ files.push({
3177
+ path: `items/${filename}.json`,
3178
+ content: stringifyDeterministic(item)
3179
+ });
3180
+ }
3181
+ for (const [assetPath, data] of bundle.assets) files.push({
3182
+ path: `assets/${assetPath}`,
3183
+ content: Buffer.from(data)
3184
+ });
3185
+ writeZip(outDir, files);
3186
+ } else {
3187
+ await mkdir(outDir, { recursive: true });
3188
+ await mkdir(join(outDir, "activities"), { recursive: true });
3189
+ await mkdir(join(outDir, "items"), { recursive: true });
3190
+ await mkdir(join(outDir, "assets"), { recursive: true });
3191
+ const manifestPath = join(outDir, "manifest.json");
3192
+ await writeFile(manifestPath, stringifyDeterministic(bundle.manifest));
3193
+ for (const [activityId, activity] of bundle.activities) {
3194
+ const activityPath = join(outDir, "activities", `${activityId}.json`);
3195
+ await writeFile(activityPath, stringifyDeterministic(activity));
3196
+ }
3197
+ for (const [itemRef, item] of bundle.items) {
3198
+ const filename = bundle.itemFilenames?.get(itemRef) ?? itemRef;
3199
+ const itemPath = join(outDir, "items", `${filename}.json`);
3200
+ await writeFile(itemPath, stringifyDeterministic(item));
3201
+ }
3202
+ for (const [assetPath, data] of bundle.assets) {
3203
+ const fullPath = join(outDir, "assets", assetPath);
3204
+ const assetDir = join(fullPath, "..");
3205
+ await mkdir(assetDir, { recursive: true });
3206
+ await writeFile(fullPath, data);
3207
+ }
3208
+ }
3209
+ return { diagnostics };
3210
+ } catch (error) {
3211
+ diagnostics.push({
3212
+ code: DiagnosticCode.LRN_SCHEMA_INVALID,
3213
+ level: "error",
3214
+ file: options.outDir,
3215
+ message: `Failed to write bundle: ${error instanceof Error ? error.message : "Unknown error"}`
3216
+ });
3217
+ return { diagnostics };
3218
+ }
3219
+ }
3220
+ //#endregion
3221
+ //#region ../core/src/qti-serializer/serializeLomMetadata.ts
3222
+ /**
3223
+ * Serialize LOM metadata to XML
3224
+ *
3225
+ * Generates a complete IMS LOM XML document with:
3226
+ * - imsmd:lom namespace
3227
+ * - general section with item identifier
3228
+ * - classification sections for each tag type
3229
+ *
3230
+ * @param metadata - LOM metadata to serialize
3231
+ * @returns XML string
3232
+ */
3233
+ function serializeLomMetadata(metadata) {
3234
+ const parts = [];
3235
+ parts.push("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
3236
+ parts.push("<imsmd:lom");
3237
+ parts.push(" xmlns:imsmd=\"http://www.imsglobal.org/xsd/imsmd_v1p2\"");
3238
+ parts.push(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">");
3239
+ parts.push("");
3240
+ parts.push(" <imsmd:general>");
3241
+ parts.push(" <imsmd:catalogentry>");
3242
+ parts.push(" <imsmd:catalog>learnosity</imsmd:catalog>");
3243
+ parts.push(" <imsmd:entry>");
3244
+ parts.push(` <imsmd:langstring xml:lang="en">${escapeXml$3(metadata.identifier)}</imsmd:langstring>`);
3245
+ parts.push(" </imsmd:entry>");
3246
+ parts.push(" </imsmd:catalogentry>");
3247
+ parts.push(" </imsmd:general>");
3248
+ parts.push("");
3249
+ for (const classification of metadata.classifications) {
3250
+ parts.push(" <imsmd:classification>");
3251
+ parts.push(" <imsmd:taxonpath>");
3252
+ parts.push(" <imsmd:source>");
3253
+ parts.push(` <imsmd:langstring xml:lang="en">${escapeXml$3(classification.tagType)}</imsmd:langstring>`);
3254
+ parts.push(" </imsmd:source>");
3255
+ for (const tagName of classification.tagNames) {
3256
+ parts.push(" <imsmd:taxon>");
3257
+ parts.push(" <imsmd:entry>");
3258
+ parts.push(` <imsmd:langstring xml:lang="en">${escapeXml$3(tagName)}</imsmd:langstring>`);
3259
+ parts.push(" </imsmd:entry>");
3260
+ parts.push(" </imsmd:taxon>");
3261
+ }
3262
+ parts.push(" </imsmd:taxonpath>");
3263
+ parts.push(" </imsmd:classification>");
3264
+ parts.push("");
3265
+ }
3266
+ parts.push("</imsmd:lom>");
3267
+ return parts.join("\n");
3268
+ }
3269
+ //#endregion
3270
+ //#region ../core/src/qti-package/assets/lrnNormalizeCss.ts
3271
+ /**
3272
+ * Embedded lrn-normalize.css content.
3273
+ *
3274
+ * This is maintained as a string constant so the CSS can be included in QTI
3275
+ * packages without relying on __dirname-relative filesystem reads — which
3276
+ * break when the library is bundled into a single file by tsup/esbuild.
3277
+ *
3278
+ * If lrn-normalize.css changes, update this constant to match.
3279
+ */
3280
+ const LRN_NORMALIZE_CSS = `/* Utility styles for converter-introduced normalization classes. */
3281
+ /* Prefix policy: lrn-norm-* */
3282
+
3283
+ .lrn-norm-center {
3284
+ text-align: center;
3285
+ }
3286
+
3287
+ /* Ensure tables inside centered blocks remain inline-centered in common players */
3288
+ .lrn-norm-center table {
3289
+ margin-left: auto;
3290
+ margin-right: auto;
3291
+ }
3292
+
3293
+ .lrn-norm-underline {
3294
+ text-decoration: underline;
3295
+ }
3296
+
3297
+ /* Stimulus content embedded via object element */
3298
+ object[type="text/html"] {
3299
+ display: block;
3300
+ width: 100vw;
3301
+ height: 100vh;
3302
+ border: none;
3303
+ }
3304
+ `;
3305
+ //#endregion
3306
+ //#region ../core/src/learnosity-mapper/buildPackageFromActivity.ts
3307
+ /**
3308
+ * Build IMS Content Package from converted Activity (TASK 005, TASK 008)
3309
+ */
3310
+ /**
3311
+ * Build an IMS Content Package from a converted Activity
3312
+ *
3313
+ * Creates a package containing:
3314
+ * - imsmanifest.xml (generated by saveQtiContentPackage)
3315
+ * - assessmentTest.xml
3316
+ * - items/*.xml (one per item)
3317
+ * - assets/* (copied from bundle)
3318
+ *
3319
+ * @param conversion - Result from convertActivity
3320
+ * @param options - Build options including bundle directory
3321
+ * @returns { package?, diagnostics[] }
3322
+ */
3323
+ function buildPackageFromActivity(conversion, options) {
3324
+ const diagnostics = [];
3325
+ if (!conversion.testXml) {
3326
+ diagnostics.push({
3327
+ code: DiagnosticCode.LRN_ACTIVITY_NO_ITEMS,
3328
+ level: "error",
3329
+ message: "Cannot build package: no test XML generated",
3330
+ file: options.activityRef
3331
+ });
3332
+ return { diagnostics };
3333
+ }
3334
+ const pkg = {
3335
+ zipPath: "",
3336
+ resources: [],
3337
+ entries: /* @__PURE__ */ new Map(),
3338
+ items: [],
3339
+ assets: []
3340
+ };
3341
+ const testPath = "assessmentTest.xml";
3342
+ pkg.entries.set(testPath, {
3343
+ file: testPath,
3344
+ size: Buffer.byteLength(conversion.testXml, "utf-8"),
3345
+ data: Buffer.from(conversion.testXml, "utf-8")
3346
+ });
3347
+ const version = options.version ?? "2.2";
3348
+ const resourceType = version === "2.1" ? "imsqti_test_xmlv2p1" : "imsqti_test_xmlv2p2";
3349
+ const testResource = {
3350
+ identifier: `test_${options.activityRef}`,
3351
+ type: resourceType,
3352
+ href: testPath,
3353
+ files: [testPath]
3354
+ };
3355
+ pkg.resources.push(testResource);
3356
+ for (const item of conversion.items) {
3357
+ const itemPath = `items/${item.reference}.xml`;
3358
+ pkg.entries.set(itemPath, {
3359
+ file: itemPath,
3360
+ size: Buffer.byteLength(item.xml, "utf-8"),
3361
+ data: Buffer.from(item.xml, "utf-8")
3362
+ });
3363
+ pkg.items.push({
3364
+ identifier: item.reference,
3365
+ href: itemPath
3366
+ });
3367
+ const itemResourceType = version === "2.1" ? "imsqti_item_xmlv2p1" : "imsqti_item_xmlv2p2";
3368
+ const itemResource = {
3369
+ identifier: `item_${item.reference}`,
3370
+ type: itemResourceType,
3371
+ href: itemPath,
3372
+ files: [itemPath]
3373
+ };
3374
+ if (item.ast?.lomMetadata) {
3375
+ const metadataXml = serializeLomMetadata(item.ast.lomMetadata);
3376
+ const metadataPath = `metadata/${item.reference}.lom.xml`;
3377
+ pkg.entries.set(metadataPath, {
3378
+ file: metadataPath,
3379
+ size: Buffer.byteLength(metadataXml, "utf-8"),
3380
+ data: Buffer.from(metadataXml, "utf-8")
3381
+ });
3382
+ if (itemResource.files) itemResource.files.push(metadataPath);
3383
+ }
3384
+ pkg.resources.push(itemResource);
3385
+ }
3386
+ const stimuliResourceIds = /* @__PURE__ */ new Map();
3387
+ if (version === "2.2" && conversion.stimuli && conversion.stimuli.length > 0) for (const stimulus of conversion.stimuli) {
3388
+ const stimulusPath = `stimuli/stimulus_${stimulus.reference}.html`;
3389
+ pkg.entries.set(stimulusPath, {
3390
+ file: stimulusPath,
3391
+ size: Buffer.byteLength(stimulus.xml, "utf-8"),
3392
+ data: Buffer.from(stimulus.xml, "utf-8")
3393
+ });
3394
+ const stimulusResourceId = `stimulus_${stimulus.reference}`;
3395
+ stimuliResourceIds.set(stimulus.reference, stimulusResourceId);
3396
+ const stimulusResource = {
3397
+ identifier: stimulusResourceId,
3398
+ type: "webcontent",
3399
+ href: stimulusPath,
3400
+ files: [stimulusPath]
3401
+ };
3402
+ pkg.resources.push(stimulusResource);
3403
+ }
3404
+ const assetsDir = path$1.join(options.bundleDir, "assets");
3405
+ if (fs$1.existsSync(assetsDir) && fs$1.statSync(assetsDir).isDirectory()) {
3406
+ const assetFiles = fs$1.readdirSync(assetsDir, {
3407
+ recursive: true,
3408
+ withFileTypes: true
3409
+ });
3410
+ for (const entry of assetFiles) if (entry.isFile()) {
3411
+ const entryPath = entry.parentPath ? path$1.join(entry.parentPath, entry.name) : entry.name;
3412
+ const relativePath = path$1.relative(assetsDir, entryPath);
3413
+ const safeRelativePath = relativePath.replace(/\\/g, "/");
3414
+ const assetPath = `assets/${safeRelativePath}`;
3415
+ const resolvedPath = safeResolve(relativePath, assetsDir);
3416
+ if (!resolvedPath) {
3417
+ diagnostics.push({
3418
+ code: DiagnosticCode.LRN_PATH_UNSAFE,
3419
+ level: "warning",
3420
+ message: `Skipping unsafe asset file: ${relativePath}`,
3421
+ file: relativePath
3422
+ });
3423
+ continue;
3424
+ }
3425
+ try {
3426
+ const data = fs$1.readFileSync(resolvedPath);
3427
+ pkg.entries.set(assetPath, {
3428
+ file: assetPath,
3429
+ size: data.length,
3430
+ data
3431
+ });
3432
+ pkg.assets.push({
3433
+ identifier: `asset_${safeRelativePath.replace(/[^a-zA-Z0-9]/g, "_")}`,
3434
+ href: assetPath
3435
+ });
3436
+ } catch (err) {
3437
+ diagnostics.push({
3438
+ code: DiagnosticCode.LRN_ITEM_FILE_MISSING,
3439
+ level: "warning",
3440
+ message: `Failed to read asset: ${err}`,
3441
+ file: assetPath
3442
+ });
3443
+ }
3444
+ }
3445
+ for (const asset of pkg.assets) {
3446
+ const assetResource = {
3447
+ identifier: asset.identifier,
3448
+ type: "webcontent",
3449
+ href: asset.href
3450
+ };
3451
+ pkg.resources.push(assetResource);
3452
+ }
3453
+ }
3454
+ const cssPath = "assets/css/lrn-normalize.css";
3455
+ pkg.entries.set(cssPath, {
3456
+ file: cssPath,
3457
+ size: Buffer.byteLength(LRN_NORMALIZE_CSS, "utf-8"),
3458
+ data: Buffer.from(LRN_NORMALIZE_CSS, "utf-8")
3459
+ });
3460
+ pkg.assets.push({
3461
+ identifier: "asset_lrn_normalize_css",
3462
+ href: cssPath,
3463
+ type: "text/css"
3464
+ });
3465
+ pkg.resources.push({
3466
+ identifier: "asset_lrn_normalize_css",
3467
+ type: "webcontent",
3468
+ href: cssPath,
3469
+ files: [cssPath]
3470
+ });
3471
+ diagnostics.push({
3472
+ code: DiagnosticCode.PACKAGE_STYLESHEET_INCLUDED,
3473
+ level: "info",
3474
+ message: "Included utility stylesheet for normalization classes",
3475
+ file: "package.assets.css"
3476
+ });
3477
+ return {
3478
+ package: pkg,
3479
+ diagnostics
3480
+ };
3481
+ }
3482
+ //#endregion
3483
+ //#region ../core/src/qti-to-learnosity/loadPackageDirectory.ts
3484
+ /**
3485
+ * Node.js-only loader that reads a QTI Content Package **directory** from disk
3486
+ * into an in-memory entries map, for feeding into the (pure)
3487
+ * `convertQtiPackageToLearnosityBundle`.
3488
+ *
3489
+ * Kept separate so the converter itself stays filesystem-free and browser-safe.
3490
+ */
3491
+ /**
3492
+ * Recursively read every file under `dirPath` into an entries map, keyed by the
3493
+ * forward-slash relative path (matching ZIP entry keys).
3494
+ */
3495
+ function loadPackageDirectory(dirPath) {
3496
+ const diagnostics = [];
3497
+ if (!existsSync(dirPath)) {
3498
+ diagnostics.push({
3499
+ code: DiagnosticCode.LRN_BUNDLE_DIR_NOT_FOUND,
3500
+ level: "error",
3501
+ file: dirPath,
3502
+ message: `Directory not found: ${dirPath}`
3503
+ });
3504
+ return { diagnostics };
3505
+ }
3506
+ const entries = /* @__PURE__ */ new Map();
3507
+ function walk(currentPath) {
3508
+ for (const item of readdirSync(currentPath)) {
3509
+ const fullPath = join(currentPath, item);
3510
+ const stat = statSync(fullPath);
3511
+ if (stat.isDirectory()) walk(fullPath);
3512
+ else if (stat.isFile()) {
3513
+ const relativePath = relative(dirPath, fullPath).split(sep).join("/");
3514
+ const data = readFileSync(fullPath);
3515
+ entries.set(relativePath, {
3516
+ file: relativePath,
3517
+ size: data.length,
3518
+ data: Buffer.from(data)
3519
+ });
3520
+ }
3521
+ }
3522
+ }
3523
+ try {
3524
+ walk(dirPath);
3525
+ } catch (error) {
3526
+ diagnostics.push({
3527
+ code: DiagnosticCode.LRN_SCHEMA_INVALID,
3528
+ level: "error",
3529
+ file: dirPath,
3530
+ message: `Failed to read package directory: ${error instanceof Error ? error.message : String(error)}`
3531
+ });
3532
+ return { diagnostics };
3533
+ }
3534
+ return {
3535
+ entries,
3536
+ diagnostics
3537
+ };
3538
+ }
3539
+ //#endregion
3540
+ //#region src/utils/batchProcessors.ts
3541
+ /**
3542
+ * Per-package conversion tasks, shared by the serial batch path
3543
+ * (`processBatch`) and the parallel worker path (`processBatchParallel` via
3544
+ * `batchWorker`). Extracting them here keeps a single implementation per
3545
+ * direction — the same code runs inline or inside a worker thread.
3546
+ */
3547
+ /** Run one batch task in-process (used by the worker and directly in tests). */
3548
+ async function runBatchTask(task, quiet = true) {
3549
+ if (task.direction === "qti-to-learnosity") return processQtiPackageToLearnosity(task.pkg, task.packageOutputPath, task.options, quiet);
3550
+ return processLearnosityToQtiPackage(task.pkg, task.packageOutputPath, task.options, quiet);
3551
+ }
3552
+ function displayDiagnosticsSummary(diagnostics, quiet) {
3553
+ if (quiet) return;
3554
+ const summaryTable = formatDiagnosticsSummaryTable(diagnostics);
3555
+ if (summaryTable) {
3556
+ console.log(" Diagnostics:");
3557
+ console.log(summaryTable.split("\n").map((line) => " " + line).join("\n"));
3558
+ console.log("");
3559
+ }
3560
+ }
3561
+ /** Convert one QTI Content Package directory to a Learnosity bundle on disk. */
3562
+ async function processQtiPackageToLearnosity(pkg, packageOutputPath, options, quiet) {
3563
+ const loaded = loadPackageDirectory(pkg.path);
3564
+ const convertResult = loaded.entries ? convertQtiPackageToLearnosityBundle({ entries: loaded.entries }, {
3565
+ organisationId: options.organisationId,
3566
+ mediaVault: options.mediaVault,
3567
+ customAssetUrl: options.customAssetUrl,
3568
+ itemReferenceSource: options.itemReferenceSource,
3569
+ itemFilenameSource: options.itemFilenameSource,
3570
+ truncateTags: options.truncateTags,
3571
+ packageVersion: options.version,
3572
+ sourceDir: pkg.path,
3573
+ fileAccess: nodeFileAccess
3574
+ }) : { diagnostics: loaded.diagnostics };
3575
+ const errors = convertResult.diagnostics.filter((d) => d.level === "error");
3576
+ const warnings = convertResult.diagnostics.filter((d) => d.level === "warning");
3577
+ const hasValidBundle = convertResult.bundle && convertResult.bundle.items.size > 0;
3578
+ const convertedFiles = convertResult.convertedSourceFiles || [];
3579
+ const failedFiles = convertResult.failedSourceFiles || [];
3580
+ const filesWithErrors = /* @__PURE__ */ new Set();
3581
+ for (const d of convertResult.diagnostics) if (d.level === "error" && d.file) filesWithErrors.add(d.file);
3582
+ const convertedWithErrors = convertedFiles.filter((f) => filesWithErrors.has(f)).length;
3583
+ const erroredItemCount = failedFiles.length + convertedWithErrors;
3584
+ const cleanItemCount = convertedFiles.length - convertedWithErrors;
3585
+ if (errors.length > 0 && !hasValidBundle) return {
3586
+ success: false,
3587
+ errorCount: errors.length,
3588
+ warningCount: warnings.length,
3589
+ convertedItemCount: cleanItemCount,
3590
+ failedItemCount: erroredItemCount,
3591
+ message: "Conversion failed"
3592
+ };
3593
+ const writeResult = await writeLearnosityBundle(convertResult.bundle, {
3594
+ outDir: packageOutputPath,
3595
+ isZipOutput: false
3596
+ });
3597
+ const writeErrors = writeResult.diagnostics.filter((d) => d.level === "error");
3598
+ if (writeErrors.length > 0) return {
3599
+ success: false,
3600
+ errorCount: errors.length + writeErrors.length,
3601
+ warningCount: warnings.length,
3602
+ convertedItemCount: cleanItemCount,
3603
+ failedItemCount: erroredItemCount,
3604
+ message: "Write failed"
3605
+ };
3606
+ const diagnosticsPath = `${packageOutputPath}/diagnostics.json`;
3607
+ const allDiagnostics = [...convertResult.diagnostics, ...writeResult.diagnostics];
3608
+ const convertedActivityFiles = convertResult.convertedActivityFiles || [];
3609
+ await writeDiagnostics(allDiagnostics, "file", diagnosticsPath, packageOutputPath, false, {
3610
+ inputPath: pkg.path,
3611
+ outputPath: packageOutputPath,
3612
+ totalItemsFound: convertedFiles.length + failedFiles.length,
3613
+ totalActivitiesFound: convertedActivityFiles.length,
3614
+ convertedFiles,
3615
+ failedFiles,
3616
+ convertedActivities: convertedActivityFiles
3617
+ });
3618
+ if (!quiet) {
3619
+ const summaryTable = formatDiagnosticsSummaryTable(allDiagnostics);
3620
+ if (summaryTable) {
3621
+ console.log(" Diagnostics:");
3622
+ console.log(summaryTable.split("\n").map((line) => " " + line).join("\n"));
3623
+ console.log("");
3624
+ }
3625
+ }
3626
+ return {
3627
+ success: true,
3628
+ errorCount: errors.length,
3629
+ warningCount: warnings.length,
3630
+ convertedItemCount: cleanItemCount,
3631
+ failedItemCount: erroredItemCount
3632
+ };
3633
+ }
3634
+ /** Convert one Learnosity bundle directory to a QTI Content Package on disk. */
3635
+ async function processLearnosityToQtiPackage(pkg, packageOutputPath, options, quiet) {
3636
+ const loadResult = loadLearnosityBundle(pkg.path);
3637
+ if (!loadResult.bundle) {
3638
+ const errorCount = loadResult.diagnostics.filter((d) => d.level === "error").length;
3639
+ displayDiagnosticsSummary(loadResult.diagnostics, quiet);
3640
+ return {
3641
+ success: false,
3642
+ errorCount,
3643
+ warningCount: 0,
3644
+ message: "Bundle load error"
3645
+ };
3646
+ }
3647
+ const bundle = loadResult.bundle;
3648
+ const allDiagnostics = [...loadResult.diagnostics];
3649
+ const allConvertedActivities = [];
3650
+ const usedFolderNames = /* @__PURE__ */ new Set();
3651
+ const convertedItemRefs = /* @__PURE__ */ new Set();
3652
+ const failedItemRefs = /* @__PURE__ */ new Set();
3653
+ for (const activityRef of bundle.activityRefs) {
3654
+ const convertResult = convertActivity(bundle, activityRef, {
3655
+ pretty: options.pretty,
3656
+ version: options.qtiVersion,
3657
+ customAssetUrl: options.customAssetUrl
3658
+ });
3659
+ allDiagnostics.push(...convertResult.diagnostics);
3660
+ const itemRefs = bundle.activityItemRefs.get(activityRef) ?? [];
3661
+ const successfulItemRefs = new Set(convertResult.items.map((item) => item.reference));
3662
+ for (const itemRef of itemRefs) if (successfulItemRefs.has(itemRef)) convertedItemRefs.add(itemRef);
3663
+ else failedItemRefs.add(itemRef);
3664
+ if (convertResult.items.length > 0) {
3665
+ const folderName = ensureUniqueFolderName(sanitizeFolderName(activityRef, `activity_${allConvertedActivities.length + 1}`), usedFolderNames);
3666
+ allConvertedActivities.push({
3667
+ activityRef,
3668
+ folderName,
3669
+ conversion: convertResult
3670
+ });
3671
+ }
3672
+ }
3673
+ for (const itemRef of convertedItemRefs) failedItemRefs.delete(itemRef);
3674
+ const convertedFiles = itemRefsToFilenames(bundle, convertedItemRefs);
3675
+ const failedFiles = itemRefsToFilenames(bundle, failedItemRefs);
3676
+ const convertedActivityFiles = allConvertedActivities.map(({ activityRef }) => `activities/${activityRef}.json`);
3677
+ const failedActivityFiles = bundle.activityRefs.filter((ref) => !allConvertedActivities.some((a) => a.activityRef === ref)).map((ref) => `activities/${ref}.json`);
3678
+ const totalItemsConverted = convertedItemRefs.size;
3679
+ const totalItemsFailed = failedItemRefs.size;
3680
+ const writePackageDiagnostics = () => writeDiagnostics(allDiagnostics, "file", `${packageOutputPath}/diagnostics.json`, packageOutputPath, false, {
3681
+ inputPath: pkg.path,
3682
+ outputPath: packageOutputPath,
3683
+ totalItemsFound: totalItemsConverted + totalItemsFailed,
3684
+ totalActivitiesFound: bundle.activityRefs.length,
3685
+ convertedFiles,
3686
+ failedFiles,
3687
+ convertedActivities: convertedActivityFiles,
3688
+ failedActivities: failedActivityFiles
3689
+ });
3690
+ if (allConvertedActivities.length === 0) {
3691
+ const errorCount = allDiagnostics.filter((d) => d.level === "error").length;
3692
+ await writePackageDiagnostics();
3693
+ return {
3694
+ success: false,
3695
+ errorCount,
3696
+ warningCount: allDiagnostics.filter((d) => d.level === "warning").length,
3697
+ convertedItemCount: 0,
3698
+ failedItemCount: totalItemsFailed,
3699
+ message: "No activities converted"
3700
+ };
3701
+ }
3702
+ const pkgData = {
3703
+ zipPath: "",
3704
+ version: options.qtiVersion,
3705
+ resources: [],
3706
+ entries: /* @__PURE__ */ new Map(),
3707
+ items: [],
3708
+ assets: []
3709
+ };
3710
+ const addedResourceIds = /* @__PURE__ */ new Set();
3711
+ for (const { activityRef, folderName, conversion } of allConvertedActivities) {
3712
+ const packageResult = buildPackageFromActivity(conversion, {
3713
+ bundleDir: pkg.path,
3714
+ activityRef,
3715
+ version: options.qtiVersion
3716
+ });
3717
+ allDiagnostics.push(...packageResult.diagnostics);
3718
+ mergeActivityPackage(pkgData, folderName, packageResult, addedResourceIds);
3719
+ }
3720
+ const saveResult = saveQtiContentPackage(pkgData, packageOutputPath);
3721
+ allDiagnostics.push(...saveResult.diagnostics);
3722
+ const errors = allDiagnostics.filter((d) => d.level === "error");
3723
+ const warnings = allDiagnostics.filter((d) => d.level === "warning");
3724
+ await writePackageDiagnostics();
3725
+ displayDiagnosticsSummary(allDiagnostics, quiet);
3726
+ if (errors.length > 0) return {
3727
+ success: false,
3728
+ errorCount: errors.length,
3729
+ warningCount: warnings.length,
3730
+ convertedItemCount: totalItemsConverted,
3731
+ failedItemCount: totalItemsFailed,
3732
+ message: "Conversion failed"
3733
+ };
3734
+ return {
3735
+ success: true,
3736
+ errorCount: 0,
3737
+ warningCount: warnings.length,
3738
+ convertedItemCount: totalItemsConverted,
3739
+ failedItemCount: totalItemsFailed
3740
+ };
3741
+ }
3742
+ /**
3743
+ * Map item references to the filenames they were loaded from, for the
3744
+ * diagnostics report. Falls back to the reference when the bundle has no
3745
+ * filename recorded, so counts always match the listed items.
3746
+ */
3747
+ function itemRefsToFilenames(bundle, itemRefs) {
3748
+ return [...itemRefs].map((itemRef) => bundle.itemRefToFilename.get(itemRef) ?? itemRef);
3749
+ }
3750
+ //#endregion
3751
+ export { buildPackageFromActivity as a, saveQtiContentPackage as c, ensureUniqueFolderName as d, sanitizeFolderName as f, loadPackageDirectory as i, convertQtiPackageToLearnosityBundle as l, processQtiPackageToLearnosity as n, writeLearnosityBundle as o, convertActivity as p, runBatchTask as r, loadLearnosityBundle as s, processLearnosityToQtiPackage as t, mergeActivityPackage as u };
3752
+
3753
+ //# sourceMappingURL=batchProcessors-DU1HwpHY.js.map