@learnosity/lib-qti-converter 0.12.7 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/docs/GETTING_STARTED.md +71 -18
  2. package/docs/LEARNOSITY_BUNDLE_FORMAT.md +23 -7
  3. package/package.json +8 -8
  4. package/packages/cli/dist/{batchProcessors-DU1HwpHY.js → batchProcessors-DgiDpfpP.js} +271 -77
  5. package/packages/cli/dist/batchProcessors-DgiDpfpP.js.map +1 -0
  6. package/packages/cli/dist/batchWorker.js +1 -1
  7. package/packages/cli/dist/{create-prompt-DU9wLVhI.js → create-prompt-DyNnKXYU.js} +63 -53
  8. package/packages/cli/dist/create-prompt-DyNnKXYU.js.map +1 -0
  9. package/packages/cli/dist/{dist-DjpU2mIj.js → dist-D3v6G5F8.js} +6 -6
  10. package/packages/cli/dist/{dist-DjpU2mIj.js.map → dist-D3v6G5F8.js.map} +1 -1
  11. package/packages/cli/dist/{learnosityToQti-BSbH3jyx.js → learnosityToQti-CIj5603P.js} +4 -4
  12. package/packages/cli/dist/{learnosityToQti-BSbH3jyx.js.map → learnosityToQti-CIj5603P.js.map} +1 -1
  13. package/packages/cli/dist/{learnosityToQtiPackage-B0xRzYmy.js → learnosityToQtiPackage-n6nGGr32.js} +7 -7
  14. package/packages/cli/dist/{learnosityToQtiPackage-B0xRzYmy.js.map → learnosityToQtiPackage-n6nGGr32.js.map} +1 -1
  15. package/packages/cli/dist/main.js +5 -5
  16. package/packages/cli/dist/{nodeFileAccess-BkzSHCOh.js → nodeFileAccess-BhCoGDOi.js} +6 -3
  17. package/packages/cli/dist/{nodeFileAccess-BkzSHCOh.js.map → nodeFileAccess-BhCoGDOi.js.map} +1 -1
  18. package/packages/cli/dist/{pathUtils-B9yPTlVF.js → pathUtils-mTQZ0wYS.js} +36 -20
  19. package/packages/cli/dist/pathUtils-mTQZ0wYS.js.map +1 -0
  20. package/packages/cli/dist/{qtiPackageToLearnosity-C7JaaUDU.js → qtiPackageToLearnosity-B4cD8jUw.js} +13 -7
  21. package/packages/cli/dist/qtiPackageToLearnosity-B4cD8jUw.js.map +1 -0
  22. package/packages/cli/dist/{qtiToLearnosity-CYoG2aIX.js → qtiToLearnosity-DDjcpShJ.js} +7 -6
  23. package/packages/cli/dist/qtiToLearnosity-DDjcpShJ.js.map +1 -0
  24. package/packages/cli/dist/{resolveOptions-CW80R2EQ.js → resolveOptions-Czapkfc1.js} +22 -8
  25. package/packages/cli/dist/resolveOptions-Czapkfc1.js.map +1 -0
  26. package/packages/cli/dist/{table-DjOn2Tsk.js → table-DTSv0atR.js} +619 -236
  27. package/packages/cli/dist/table-DTSv0atR.js.map +1 -0
  28. package/packages/core/dist/index.d.ts +197 -184
  29. package/packages/core/dist/index.js +858 -303
  30. package/packages/core/dist/node.d.ts +211 -196
  31. package/packages/core/dist/node.js +889 -310
  32. package/packages/cli/dist/batchProcessors-DU1HwpHY.js.map +0 -1
  33. package/packages/cli/dist/create-prompt-DU9wLVhI.js.map +0 -1
  34. package/packages/cli/dist/pathUtils-B9yPTlVF.js.map +0 -1
  35. package/packages/cli/dist/qtiPackageToLearnosity-C7JaaUDU.js.map +0 -1
  36. package/packages/cli/dist/qtiToLearnosity-CYoG2aIX.js.map +0 -1
  37. package/packages/cli/dist/resolveOptions-CW80R2EQ.js.map +0 -1
  38. package/packages/cli/dist/table-DjOn2Tsk.js.map +0 -1
@@ -1,5 +1,5 @@
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";
1
+ import { C as mapLearnosityToAst, D as DiagnosticCode, E as parseLearnosityItem, S as downgradeAssessmentTestToQti21, T as sanitizeHtmlContent, _ as md5hex, b as serializeAssessmentItem, c as transformForwardAssetUrlsInXml, d as getAllPassageDataPaths, f as generateItemReference, g as serializeQtiAssetIdentity, h as selectQtiAssetFilename, l as convertQtiAssessmentItemToLearnosity, m as isSupportedQtiAssetPath, n as formatDiagnosticsSummaryTable, p as canonicalizeQtiAssetHref, s as writeDiagnostics, u as parseMetadataTags, v as getAttr$2, w as normalizeXhtmlVoidElements, x as escapeXml$3, y as require_saxes } from "./table-DTSv0atR.js";
2
+ import { t as nodeFileAccess } from "./nodeFileAccess-BhCoGDOi.js";
3
3
  import * as path$1 from "node:path";
4
4
  import { join, relative, sep } from "node:path";
5
5
  import * as fs$1 from "node:fs";
@@ -2163,6 +2163,108 @@ function textToBytes(text) {
2163
2163
  return strToU8(text);
2164
2164
  }
2165
2165
  //#endregion
2166
+ //#region ../core/src/qti-to-learnosity/utils/assetFilenameRegistry.ts
2167
+ /**
2168
+ * Browser-safe registry for item-scoped QTI asset filenames.
2169
+ *
2170
+ * Filename selection belongs to asset identity, not package traversal. Keeping
2171
+ * both identity and filename indexes here lets URL and bundle seams validate
2172
+ * the same contract before either one can overwrite a physical asset.
2173
+ */
2174
+ var AssetFilenameConflictError = class extends Error {
2175
+ kind;
2176
+ mode;
2177
+ filename;
2178
+ existing;
2179
+ incoming;
2180
+ constructor(kind, mode, filename, existing, incoming) {
2181
+ const existingIdentity = existing.serializedIdentity;
2182
+ const incomingIdentity = incoming.serializedIdentity;
2183
+ const message = kind === "identity-bytes" ? `Asset identity conflict in ${mode} mode for ${incomingIdentity}: filename "${filename}" was registered with different bytes.` : `Asset filename conflict in ${mode} mode: filename "${filename}" is assigned to both ${existingIdentity} and ${incomingIdentity}.`;
2184
+ super(message);
2185
+ this.name = "AssetFilenameConflictError";
2186
+ this.kind = kind;
2187
+ this.mode = mode;
2188
+ this.filename = filename;
2189
+ this.existing = existing;
2190
+ this.incoming = incoming;
2191
+ }
2192
+ };
2193
+ function bytesEqual(left, right) {
2194
+ if (left.length !== right.length) return false;
2195
+ for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
2196
+ return true;
2197
+ }
2198
+ function cloneBytes(bytes) {
2199
+ return new Uint8Array(bytes);
2200
+ }
2201
+ /**
2202
+ * Track selected asset names and their bytes for one conversion.
2203
+ *
2204
+ * Registering an equivalent identity repeatedly is idempotent when its bytes
2205
+ * agree. A filename can never silently change owners, and an identity can
2206
+ * never silently change bytes, in either hashed or preserve mode.
2207
+ */
2208
+ var AssetFilenameRegistry = class {
2209
+ preserveAssetFilenames;
2210
+ byIdentity = /* @__PURE__ */ new Map();
2211
+ byFilename = /* @__PURE__ */ new Map();
2212
+ constructor(preserveAssetFilenames = false) {
2213
+ this.preserveAssetFilenames = preserveAssetFilenames;
2214
+ }
2215
+ get mode() {
2216
+ return this.preserveAssetFilenames ? "preserve" : "hashed";
2217
+ }
2218
+ get size() {
2219
+ return this.byIdentity.size;
2220
+ }
2221
+ /**
2222
+ * Register an asset and return its selected filename and bytes.
2223
+ *
2224
+ * The input href is canonicalized before both indexes are consulted, so
2225
+ * equivalent directory and ZIP representations reuse one registration.
2226
+ */
2227
+ register(finalItemReference, qtiAssetHref, bytes) {
2228
+ const canonicalHref = canonicalizeQtiAssetHref(qtiAssetHref);
2229
+ const serializedIdentity = serializeQtiAssetIdentity(finalItemReference, canonicalHref);
2230
+ const filename = selectQtiAssetFilename(finalItemReference, canonicalHref, this.preserveAssetFilenames);
2231
+ const incoming = {
2232
+ finalItemReference,
2233
+ qtiAssetHref: canonicalHref,
2234
+ serializedIdentity,
2235
+ filename,
2236
+ bytes: cloneBytes(bytes)
2237
+ };
2238
+ const existingIdentity = this.byIdentity.get(serializedIdentity);
2239
+ if (existingIdentity) {
2240
+ if (!bytesEqual(existingIdentity.bytes, incoming.bytes)) throw new AssetFilenameConflictError("identity-bytes", this.mode, filename, existingIdentity, incoming);
2241
+ return existingIdentity;
2242
+ }
2243
+ const existingFilename = this.byFilename.get(filename);
2244
+ if (existingFilename) throw new AssetFilenameConflictError("filename-identity", this.mode, filename, existingFilename, incoming);
2245
+ this.byIdentity.set(serializedIdentity, incoming);
2246
+ this.byFilename.set(filename, incoming);
2247
+ return incoming;
2248
+ }
2249
+ /** Look up a previously registered canonical identity without registering it. */
2250
+ get(finalItemReference, qtiAssetHref) {
2251
+ return this.byIdentity.get(serializeQtiAssetIdentity(finalItemReference, qtiAssetHref));
2252
+ }
2253
+ /** Look up an asset by its selected bundle-relative filename. */
2254
+ getByFilename(filename) {
2255
+ return this.byFilename.get(filename);
2256
+ }
2257
+ /** Iterate registrations in deterministic registration order. */
2258
+ entries() {
2259
+ return this.byIdentity.values();
2260
+ }
2261
+ /** Remove all registrations so the registry can be reused for a new conversion. */
2262
+ clear() {
2263
+ this.byIdentity.clear();
2264
+ this.byFilename.clear();
2265
+ }
2266
+ };
2267
+ //#endregion
2166
2268
  //#region ../core/src/qti-to-learnosity/convertQtiPackageToLearnosityBundle.ts
2167
2269
  /**
2168
2270
  * QTI Content Package → Learnosity Bundle converter (v1)
@@ -2210,57 +2312,70 @@ function ensureFailedItemDiagnostic(itemDiagnostics, href) {
2210
2312
  }];
2211
2313
  }
2212
2314
  /**
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
2315
  * Normalize href path by removing leading ./ sequences
2231
2316
  * This ensures manifest hrefs like "./items/foo.xml" match entries stored as "items/foo.xml"
2232
2317
  */
2233
2318
  function normalizeHref(href) {
2234
2319
  return href.replace(/^(\.\/)+/, "");
2235
2320
  }
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
- ];
2321
+ function readAssessmentItemIdentifier(inputXml, fallback) {
2322
+ let identifier = fallback;
2323
+ const parser = new import_saxes.SaxesParser({ xmlns: true });
2324
+ parser.on("opentag", (tag) => {
2325
+ if ((tag.local ?? tag.name) === "assessmentItem") identifier = getAttr$2(tag, "identifier") ?? fallback;
2326
+ });
2327
+ try {
2328
+ parser.write(inputXml).close();
2329
+ } catch {}
2330
+ return identifier;
2331
+ }
2332
+ function uniqueItemReference(baseReference, sourceHref, items) {
2333
+ if (!items.has(baseReference)) return baseReference;
2334
+ const readableCandidate = `${baseReference}_${normalizeHref(sourceHref).split("/").at(-1)?.replace(/\.xml$/i, "") ?? "item"}`;
2335
+ if (!items.has(readableCandidate)) return readableCandidate;
2336
+ const sourceDigest = md5hex(normalizeHref(sourceHref));
2337
+ let candidate = `${readableCandidate}_${sourceDigest}`;
2338
+ let suffix = 1;
2339
+ while (items.has(candidate)) {
2340
+ candidate = `${readableCandidate}_${sourceDigest}_${suffix}`;
2341
+ suffix += 1;
2342
+ }
2343
+ return candidate;
2344
+ }
2345
+ function isUnsafeAssetHrefError(error) {
2346
+ return error instanceof Error && (error.message.startsWith("Unsafe QTI asset href:") || error.message.startsWith("QTI asset href has no filename:"));
2347
+ }
2348
+ function hasAssetNamingDiagnostic(diagnostics) {
2349
+ return diagnostics.some((diagnostic) => diagnostic.code === DiagnosticCode.QTI_ASSET_HREF_UNSAFE || diagnostic.code === DiagnosticCode.QTI_ASSET_FILENAME_CONFLICT || diagnostic.code === DiagnosticCode.QTI_ASSET_IDENTITY_BYTES_CONFLICT);
2350
+ }
2351
+ /**
2352
+ * Resolve a local QTI reference exactly as asset URL transformation does.
2353
+ * References without a leading dot segment are already package-relative;
2354
+ * `./` and `../` references are resolved from the item source directory.
2355
+ */
2356
+ function resolvePackageAssetHref(href, sourceHrefBase) {
2357
+ const cleanHref = href.split(/[?#]/, 1)[0].replaceAll("\\", "/");
2358
+ if (!cleanHref || /^https?:\/\//i.test(cleanHref) || cleanHref.startsWith("//") || cleanHref.startsWith("data:") || cleanHref.includes("assets.learnosity.com") || cleanHref.includes("media-vault.learnosity.com")) return;
2359
+ if (!(/^\.\.?\//.test(cleanHref) || !cleanHref.includes("/"))) return canonicalizeQtiAssetHref(cleanHref);
2360
+ const baseHref = canonicalizeQtiAssetHref(sourceHrefBase);
2361
+ const baseDirectory = baseHref.slice(0, baseHref.lastIndexOf("/") + 1);
2362
+ return canonicalizeQtiAssetHref(`${baseDirectory}${cleanHref}`);
2363
+ }
2364
+ /** Extract local asset-bearing attributes from item XML or resolved passage HTML. */
2365
+ function extractAssetHrefs(content) {
2366
+ const hrefs = [];
2367
+ const seen = /* @__PURE__ */ new Set();
2368
+ const attributePattern = /\b(?:src|data|href)\s*=\s*["']([^"']+)["']/gi;
2369
+ let match;
2370
+ while ((match = attributePattern.exec(content)) !== null) if (!seen.has(match[1])) {
2371
+ seen.add(match[1]);
2372
+ hrefs.push(match[1]);
2373
+ }
2374
+ return hrefs;
2375
+ }
2376
+ function isCopyableAssetPath(path) {
2377
+ return isSupportedQtiAssetPath(path);
2378
+ }
2264
2379
  /**
2265
2380
  * Merge two tag objects, combining tag values for each tag type
2266
2381
  * Source tags are merged into base tags, avoiding duplicates
@@ -2331,7 +2446,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
2331
2446
  if (needed.has(normalized)) return true;
2332
2447
  const lower = normalized.toLowerCase();
2333
2448
  if (lower.endsWith(".html")) return false;
2334
- return lower.endsWith(".xml") || ASSET_EXTENSIONS.some((ext) => lower.endsWith(ext));
2449
+ return lower.endsWith(".xml") || isSupportedQtiAssetPath(normalized);
2335
2450
  };
2336
2451
  }
2337
2452
  const unzipped = unzipToEntries(input.zipBytes, label, filter ? { filter } : void 0);
@@ -2366,6 +2481,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
2366
2481
  }
2367
2482
  const items = /* @__PURE__ */ new Map();
2368
2483
  const itemFilenames = /* @__PURE__ */ new Map();
2484
+ const itemAssetContexts = [];
2369
2485
  const qtiRefToMd5Refs = /* @__PURE__ */ new Map();
2370
2486
  const convertedSourceFiles = [];
2371
2487
  const failedSourceFiles = [];
@@ -2428,23 +2544,34 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
2428
2544
  }
2429
2545
  const itemXml = decodeUtf8(itemEntry.data);
2430
2546
  const itemFilePath = opts?.sourceDir ? posixJoin(opts.sourceDir, itemResource.href) : itemResource.href;
2547
+ const qtiIdentifier = readAssessmentItemIdentifier(itemXml, itemResource.identifier);
2548
+ const baseItemReference = generateItemReference(qtiIdentifier, opts?.itemReferenceSource, itemFilePath);
2549
+ const finalItemReference = uniqueItemReference(baseItemReference, itemResource.href, items);
2431
2550
  const itemResult = convertQtiAssessmentItemToLearnosity(itemXml, {
2432
2551
  inputPath: itemFilePath,
2433
2552
  sourceFile: itemFilePath,
2434
2553
  organisationId: opts?.organisationId,
2435
2554
  mediaVault: opts?.mediaVault,
2436
2555
  customAssetUrl: opts?.customAssetUrl,
2556
+ preserveAssetFilenames: opts?.preserveAssetFilenames ?? false,
2437
2557
  itemReferenceSource: opts?.itemReferenceSource,
2438
2558
  fileAccess: opts?.fileAccess,
2439
- packageRoot: opts?.sourceDir
2559
+ packageRoot: opts?.sourceDir,
2560
+ finalItemReference,
2561
+ sourceHrefBase: itemResource.href
2440
2562
  });
2441
2563
  diagnostics.push(...itemResult.diagnostics);
2442
2564
  if (itemResult.item) {
2443
2565
  let md5Ref = itemResult.item.item.reference;
2566
+ if (finalItemReference !== baseItemReference) diagnostics.push({
2567
+ code: DiagnosticCode.QTI_PACKAGE_DUPLICATE_IDENTIFIER,
2568
+ level: "warning",
2569
+ file: itemResource.href,
2570
+ message: `Duplicate item reference "${finalItemReference}" disambiguated from "${baseItemReference}" (source: ${itemResource.href})`
2571
+ });
2444
2572
  if (items.has(md5Ref)) {
2445
- const hrefParts = itemResource.href.split("/");
2446
- const filename = hrefParts[hrefParts.length - 1].replace(/\.xml$/i, "");
2447
- md5Ref = `${md5Ref}_${filename}`;
2573
+ const originalRef = md5Ref;
2574
+ md5Ref = uniqueItemReference(finalItemReference, itemResource.href, items);
2448
2575
  itemResult.item.item.reference = md5Ref;
2449
2576
  for (const question of itemResult.item.questions) {
2450
2577
  const oldRef = question.reference;
@@ -2458,7 +2585,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
2458
2585
  code: DiagnosticCode.QTI_PACKAGE_DUPLICATE_IDENTIFIER,
2459
2586
  level: "warning",
2460
2587
  file: itemResource.href,
2461
- message: `Duplicate item reference "${itemResult.item.item.reference}" disambiguated from "${md5Ref.replace(`_${filename}`, "")}" (source: ${itemResource.href})`
2588
+ message: `Duplicate item reference "${md5Ref}" disambiguated from "${originalRef}" (source: ${itemResource.href})`
2462
2589
  });
2463
2590
  }
2464
2591
  if (itemResource.metadataXml) try {
@@ -2478,9 +2605,15 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
2478
2605
  });
2479
2606
  }
2480
2607
  items.set(md5Ref, itemResult.item);
2608
+ itemAssetContexts.push({
2609
+ finalItemReference: md5Ref,
2610
+ sourceHref: itemResource.href,
2611
+ sourceFile: itemFilePath,
2612
+ inputXml: itemXml
2613
+ });
2481
2614
  const filenameSource = opts?.itemFilenameSource;
2482
2615
  if (filenameSource && filenameSource !== (opts.itemReferenceSource ?? "sourceFilename")) {
2483
- const qtiIdentifier = itemXml.match(/<assessmentItem[^>]+identifier="([^"]+)"/)?.[1] ?? md5Ref;
2616
+ const qtiIdentifier = readAssessmentItemIdentifier(itemXml, md5Ref);
2484
2617
  const filename = generateItemReference(qtiIdentifier, filenameSource, itemFilePath);
2485
2618
  itemFilenames.set(md5Ref, filename);
2486
2619
  }
@@ -2492,6 +2625,12 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
2492
2625
  diagnostics.push(...ensureFailedItemDiagnostic(itemResult.diagnostics, itemResource.href));
2493
2626
  }
2494
2627
  }
2628
+ if (hasAssetNamingDiagnostic(diagnostics)) return {
2629
+ diagnostics,
2630
+ convertedSourceFiles,
2631
+ failedSourceFiles,
2632
+ convertedActivityFiles
2633
+ };
2495
2634
  if (items.size === 0 && itemResourcesToConvert.length > 0) {
2496
2635
  diagnostics.push({
2497
2636
  code: DiagnosticCode.QTI_PACKAGE_ITEM_NOT_FOUND,
@@ -2596,24 +2735,39 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
2596
2735
  activitiesManifest[activityId] = { items: activityItems };
2597
2736
  }
2598
2737
  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
- }
2738
+ const assetCandidates = /* @__PURE__ */ new Map();
2739
+ const addAssetCandidate = (href, data) => {
2740
+ try {
2741
+ const canonicalHref = canonicalizeQtiAssetHref(href);
2742
+ if (isCopyableAssetPath(canonicalHref)) assetCandidates.set(canonicalHref, new Uint8Array(data));
2743
+ } catch {}
2744
+ };
2745
+ for (const resource of resources) if (resource.type === "webcontent" || resource.type.includes("associated")) for (const href of [resource.href, ...resource.files ?? []]) {
2746
+ const assetEntry = entries.get(normalizeHref(href));
2747
+ if (assetEntry) addAssetCandidate(href, assetEntry.data);
2608
2748
  }
2609
2749
  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);
2750
+ if (path === "imsmanifest.xml" || path.toLowerCase().endsWith(".xml")) continue;
2751
+ addAssetCandidate(path, entry.data);
2752
+ }
2753
+ const registry = new AssetFilenameRegistry(opts?.preserveAssetFilenames ?? false);
2754
+ const registerContextAsset = (context, rawHref, sourceHrefBase) => {
2755
+ const canonicalHref = resolvePackageAssetHref(rawHref, sourceHrefBase);
2756
+ if (!canonicalHref) return;
2757
+ const bytes = assetCandidates.get(canonicalHref);
2758
+ if (!bytes) return;
2759
+ const registration = registry.register(context.finalItemReference, canonicalHref, bytes);
2760
+ assets.set(registration.filename, registration.bytes);
2761
+ };
2762
+ for (const context of itemAssetContexts) {
2763
+ for (const rawHref of extractAssetHrefs(context.inputXml)) registerContextAsset(context, rawHref, context.sourceHref);
2764
+ for (const passagePath of getAllPassageDataPaths(context.inputXml)) {
2765
+ const passageContent = opts?.fileAccess?.resolvePassageFile(passagePath, context.sourceFile);
2766
+ const passageHref = resolvePackageAssetHref(passagePath, context.sourceHref);
2767
+ const entryContent = passageHref ? entries.get(passageHref) : void 0;
2768
+ const resolvedPassageContent = passageContent ?? (entryContent ? decodeUtf8(entryContent.data) : void 0);
2769
+ if (!resolvedPassageContent) continue;
2770
+ for (const rawHref of extractAssetHrefs(resolvedPassageContent)) registerContextAsset(context, rawHref, context.sourceHref);
2617
2771
  }
2618
2772
  }
2619
2773
  return {
@@ -2626,6 +2780,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
2626
2780
  organisationId: opts?.organisationId,
2627
2781
  mediaVault: opts?.mediaVault ?? false,
2628
2782
  customAssetUrl: opts?.customAssetUrl,
2783
+ preserveAssetFilenames: opts?.preserveAssetFilenames ?? false,
2629
2784
  itemReferenceSource: opts?.itemReferenceSource ?? "sourceFilename"
2630
2785
  }
2631
2786
  },
@@ -2647,7 +2802,25 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
2647
2802
  convertedActivityFiles
2648
2803
  };
2649
2804
  } catch (error) {
2650
- diagnostics.push({
2805
+ if (error instanceof AssetFilenameConflictError) diagnostics.push({
2806
+ code: error.kind === "identity-bytes" ? DiagnosticCode.QTI_ASSET_IDENTITY_BYTES_CONFLICT : DiagnosticCode.QTI_ASSET_FILENAME_CONFLICT,
2807
+ level: "error",
2808
+ file: opts?.sourceLabel ?? opts?.sourceDir ?? "package",
2809
+ message: error.message,
2810
+ context: {
2811
+ mode: error.mode,
2812
+ filename: error.filename,
2813
+ existingIdentity: error.existing.serializedIdentity,
2814
+ incomingIdentity: error.incoming.serializedIdentity
2815
+ }
2816
+ });
2817
+ else if (isUnsafeAssetHrefError(error)) diagnostics.push({
2818
+ code: DiagnosticCode.QTI_ASSET_HREF_UNSAFE,
2819
+ level: "error",
2820
+ file: opts?.sourceLabel ?? opts?.sourceDir ?? "package",
2821
+ message: error.message
2822
+ });
2823
+ else diagnostics.push({
2651
2824
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
2652
2825
  level: "error",
2653
2826
  file: "root",
@@ -3155,6 +3328,22 @@ function stringifyDeterministic(obj) {
3155
3328
  }, 2);
3156
3329
  }
3157
3330
  /**
3331
+ * Return an asset key relative to the bundle's `assets/` root.
3332
+ *
3333
+ * New callers provide selected filenames or other root-relative keys. Strip
3334
+ * legacy leading `assets/` segments so the writer remains compatible with
3335
+ * source-relative keys without producing `assets/assets/...` paths.
3336
+ */
3337
+ function normalizeBundleAssetPath(assetPath) {
3338
+ let normalized = assetPath.replaceAll("\\", "/");
3339
+ while (normalized.startsWith("./")) normalized = normalized.slice(2);
3340
+ while (normalized.startsWith("assets/")) normalized = normalized.slice(7);
3341
+ const segments = normalized.split("/").filter((segment) => segment && segment !== ".");
3342
+ const isAbsolute = normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized) || /^[A-Za-z][A-Za-z\d+.-]*:/.test(normalized);
3343
+ if (!normalized || isAbsolute || segments.some((segment) => segment === "..")) throw new Error(`Unsafe bundle asset path: ${assetPath}`);
3344
+ return segments.join("/");
3345
+ }
3346
+ /**
3158
3347
  * Write Learnosity Bundle to directory or ZIP
3159
3348
  */
3160
3349
  async function writeLearnosityBundle(bundle, options) {
@@ -3178,10 +3367,13 @@ async function writeLearnosityBundle(bundle, options) {
3178
3367
  content: stringifyDeterministic(item)
3179
3368
  });
3180
3369
  }
3181
- for (const [assetPath, data] of bundle.assets) files.push({
3182
- path: `assets/${assetPath}`,
3183
- content: Buffer.from(data)
3184
- });
3370
+ for (const [assetPath, data] of bundle.assets) {
3371
+ const relativeAssetPath = normalizeBundleAssetPath(assetPath);
3372
+ files.push({
3373
+ path: `assets/${relativeAssetPath}`,
3374
+ content: Buffer.from(data)
3375
+ });
3376
+ }
3185
3377
  writeZip(outDir, files);
3186
3378
  } else {
3187
3379
  await mkdir(outDir, { recursive: true });
@@ -3200,7 +3392,8 @@ async function writeLearnosityBundle(bundle, options) {
3200
3392
  await writeFile(itemPath, stringifyDeterministic(item));
3201
3393
  }
3202
3394
  for (const [assetPath, data] of bundle.assets) {
3203
- const fullPath = join(outDir, "assets", assetPath);
3395
+ const relativeAssetPath = normalizeBundleAssetPath(assetPath);
3396
+ const fullPath = join(outDir, "assets", relativeAssetPath);
3204
3397
  const assetDir = join(fullPath, "..");
3205
3398
  await mkdir(assetDir, { recursive: true });
3206
3399
  await writeFile(fullPath, data);
@@ -3565,6 +3758,7 @@ async function processQtiPackageToLearnosity(pkg, packageOutputPath, options, qu
3565
3758
  organisationId: options.organisationId,
3566
3759
  mediaVault: options.mediaVault,
3567
3760
  customAssetUrl: options.customAssetUrl,
3761
+ preserveAssetFilenames: options.preserveAssetFilenames,
3568
3762
  itemReferenceSource: options.itemReferenceSource,
3569
3763
  itemFilenameSource: options.itemFilenameSource,
3570
3764
  truncateTags: options.truncateTags,
@@ -3750,4 +3944,4 @@ function itemRefsToFilenames(bundle, itemRefs) {
3750
3944
  //#endregion
3751
3945
  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
3946
 
3753
- //# sourceMappingURL=batchProcessors-DU1HwpHY.js.map
3947
+ //# sourceMappingURL=batchProcessors-DgiDpfpP.js.map