@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
@@ -174,6 +174,9 @@ const DiagnosticCode = {
174
174
  QTI_PACKAGE_NO_CONTENT: "QTI_PACKAGE_NO_CONTENT",
175
175
  QTI_PACKAGE_DUPLICATE_IDENTIFIER: "QTI_PACKAGE_DUPLICATE_IDENTIFIER",
176
176
  QTI_ITEM_CONVERSION_FAILED: "QTI_ITEM_CONVERSION_FAILED",
177
+ QTI_ASSET_HREF_UNSAFE: "QTI_ASSET_HREF_UNSAFE",
178
+ QTI_ASSET_FILENAME_CONFLICT: "QTI_ASSET_FILENAME_CONFLICT",
179
+ QTI_ASSET_IDENTITY_BYTES_CONFLICT: "QTI_ASSET_IDENTITY_BYTES_CONFLICT",
177
180
  LRN_BUNDLE_WRITTEN: "LRN_BUNDLE_WRITTEN",
178
181
  QTI_DOWNGRADE_NAMESPACE: "QTI_DOWNGRADE_NAMESPACE",
179
182
  QTI_DOWNGRADE_SCHEMA_LOCATION: "QTI_DOWNGRADE_SCHEMA_LOCATION",
@@ -5833,14 +5836,14 @@ var DomHandler = class {
5833
5836
  //#endregion
5834
5837
  //#region ../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/escape.js
5835
5838
  const xmlReplacer = /["&'<>$\x80-\uFFFF]/g;
5836
- const xmlCodeMap$1 = /* @__PURE__ */ new Map([
5839
+ const xmlCodeMap = /* @__PURE__ */ new Map([
5837
5840
  [34, "&quot;"],
5838
5841
  [38, "&amp;"],
5839
5842
  [39, "&apos;"],
5840
5843
  [60, "&lt;"],
5841
5844
  [62, "&gt;"]
5842
5845
  ]);
5843
- const getCodePoint$1 = String.prototype.codePointAt != null ? (str, index) => str.codePointAt(index) : (c, index) => (c.charCodeAt(index) & 64512) === 55296 ? (c.charCodeAt(index) - 55296) * 1024 + c.charCodeAt(index + 1) - 56320 + 65536 : c.charCodeAt(index);
5846
+ const getCodePoint = String.prototype.codePointAt != null ? (str, index) => str.codePointAt(index) : (c, index) => (c.charCodeAt(index) & 64512) === 55296 ? (c.charCodeAt(index) - 55296) * 1024 + c.charCodeAt(index + 1) - 56320 + 65536 : c.charCodeAt(index);
5844
5847
  /**
5845
5848
  * Encodes all non-ASCII characters, as well as characters not valid in XML
5846
5849
  * documents using XML entities.
@@ -5855,12 +5858,12 @@ function encodeXML$1(str) {
5855
5858
  while ((match = xmlReplacer.exec(str)) !== null) {
5856
5859
  const i = match.index;
5857
5860
  const char = str.charCodeAt(i);
5858
- const next = xmlCodeMap$1.get(char);
5861
+ const next = xmlCodeMap.get(char);
5859
5862
  if (next !== void 0) {
5860
5863
  ret += str.substring(lastIdx, i) + next;
5861
5864
  lastIdx = i + 1;
5862
5865
  } else {
5863
- ret += `${str.substring(lastIdx, i)}&#x${getCodePoint$1(str, i).toString(16)};`;
5866
+ ret += `${str.substring(lastIdx, i)}&#x${getCodePoint(str, i).toString(16)};`;
5864
5867
  lastIdx = xmlReplacer.lastIndex += Number((char & 64512) === 55296);
5865
5868
  }
5866
5869
  }
@@ -5876,7 +5879,7 @@ function encodeXML$1(str) {
5876
5879
  * @returns Function that escapes all characters matched by the given regular
5877
5880
  * expression using the given map of characters to escape to their entities.
5878
5881
  */
5879
- function getEscaper$1(regex, map) {
5882
+ function getEscaper(regex, map) {
5880
5883
  return function escape(data) {
5881
5884
  let match;
5882
5885
  let lastIdx = 0;
@@ -5895,7 +5898,7 @@ function getEscaper$1(regex, map) {
5895
5898
  *
5896
5899
  * @param data String to escape.
5897
5900
  */
5898
- const escapeAttribute$1 = getEscaper$1(/["&\u00A0]/g, /* @__PURE__ */ new Map([
5901
+ const escapeAttribute$1 = getEscaper(/["&\u00A0]/g, /* @__PURE__ */ new Map([
5899
5902
  [34, "&quot;"],
5900
5903
  [38, "&amp;"],
5901
5904
  [160, "&nbsp;"]
@@ -5906,7 +5909,7 @@ const escapeAttribute$1 = getEscaper$1(/["&\u00A0]/g, /* @__PURE__ */ new Map([
5906
5909
  *
5907
5910
  * @param data String to escape.
5908
5911
  */
5909
- const escapeText$1 = getEscaper$1(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
5912
+ const escapeText$1 = getEscaper(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
5910
5913
  [38, "&amp;"],
5911
5914
  [60, "&lt;"],
5912
5915
  [62, "&gt;"],
@@ -8969,93 +8972,116 @@ function getElementsByTagType(type, nodes, recurse = true, limit = Number.POSITI
8969
8972
  return filter(Checks["tag_type"](type), nodes, recurse, limit);
8970
8973
  }
8971
8974
  //#endregion
8972
- //#region ../../node_modules/.pnpm/entities@8.0.0/node_modules/entities/dist/escape.js
8973
- const xmlCodeMap = /* @__PURE__ */ new Map([
8974
- [34, "&quot;"],
8975
- [38, "&amp;"],
8976
- [39, "&apos;"],
8977
- [60, "&lt;"],
8978
- [62, "&gt;"]
8979
- ]);
8975
+ //#region ../../node_modules/.pnpm/entities@8.1.0/node_modules/entities/dist/escape.js
8980
8976
  /**
8981
- * Read a code point at a given index.
8982
- * @param input Input string to encode or decode.
8983
- * @param index Current read position in the input string.
8977
+ * Get the named reference for an XML special character or U+00A0.
8978
+ * @param char Code unit matched by one of the escape regexes.
8984
8979
  */
8985
- const getCodePoint = typeof String.prototype.codePointAt === "function" ? (input, index) => input.codePointAt(index) : (c, index) => (c.charCodeAt(index) & 64512) === 55296 ? (c.charCodeAt(index) - 55296) * 1024 + c.charCodeAt(index + 1) - 56320 + 65536 : c.charCodeAt(index);
8980
+ function getEscape(char) {
8981
+ return char === 34 ? "&quot;" : char === 38 ? "&amp;" : char === 39 ? "&apos;" : char === 60 ? "&lt;" : char === 62 ? "&gt;" : "&nbsp;";
8982
+ }
8983
+ /**
8984
+ * Matches exactly the characters `encodeXML` escapes: the five XML special
8985
+ * characters plus every non-ASCII code unit (lone surrogates included — no
8986
+ * `u` flag). Kept in sync with `XML_BITSET_VALUE`.
8987
+ *
8988
+ * Shared with `encodeNonAsciiHTML` in `encode.ts`. Because the regex is
8989
+ * stateful (`g` flag), every call site must set `lastIndex` before use.
8990
+ */
8991
+ const xmlEncodeRegex = /["&'<>\u0080-\uFFFF]/g;
8992
+ /**
8993
+ * Whether `code` (a UTF-16 code unit) is escaped by {@link encodeXML}: a
8994
+ * non-ASCII unit, or one of the five XML specials flagged in
8995
+ * `XML_BITSET_VALUE` (which is only meaningful for code units 32-63).
8996
+ * @param code Code unit to test.
8997
+ */
8998
+ function isXmlEscapable(code) {
8999
+ return code >= 128 || code >= 32 && code < 64 && (1342177476 >>> code & 1) === 1;
9000
+ }
8986
9001
  /**
8987
9002
  * Encodes all non-ASCII characters, as well as characters not valid in XML
8988
- * documents using XML entities. Uses a fast bitset scan instead of RegExp.
9003
+ * documents using XML entities.
8989
9004
  *
8990
9005
  * If a character has no equivalent entity, a numeric hexadecimal reference
8991
9006
  * (eg. `&#xfc;`) will be used.
8992
- * @param input Input string to encode or decode.
9007
+ * @param input Input string to encode.
8993
9008
  */
8994
9009
  function encodeXML(input) {
9010
+ const { length } = input;
8995
9011
  let out;
8996
9012
  let last = 0;
8997
- const { length } = input;
8998
- for (let index = 0; index < length; index++) {
9013
+ let index = 0;
9014
+ while (index < length) {
8999
9015
  const char = input.charCodeAt(index);
9000
- if (char < 128 && ((1342177476 >>> char & 1) === 0 || char >= 64 || char < 32)) continue;
9016
+ if (!isXmlEscapable(char)) {
9017
+ const bound = Math.min(index + 32, length);
9018
+ let next = index + 1;
9019
+ while (next < bound && !isXmlEscapable(input.charCodeAt(next))) next++;
9020
+ if (next < bound) {
9021
+ index = next;
9022
+ continue;
9023
+ }
9024
+ if (next >= length) break;
9025
+ xmlEncodeRegex.lastIndex = next;
9026
+ if (!xmlEncodeRegex.test(input)) break;
9027
+ index = xmlEncodeRegex.lastIndex - 1;
9028
+ continue;
9029
+ }
9001
9030
  if (out === void 0) out = input.substring(0, index);
9002
9031
  else if (last !== index) out += input.substring(last, index);
9003
9032
  if (char < 64) {
9004
- out += xmlCodeMap.get(char);
9005
- last = index + 1;
9033
+ out += getEscape(char);
9034
+ last = index += 1;
9006
9035
  continue;
9007
9036
  }
9008
- const cp = getCodePoint(input, index);
9037
+ const cp = input.codePointAt(index);
9009
9038
  out += `&#x${cp.toString(16)};`;
9010
9039
  if (cp !== char) index++;
9011
- last = index + 1;
9040
+ last = index += 1;
9012
9041
  }
9013
9042
  if (out === void 0) return input;
9014
9043
  if (last < length) out += input.substr(last);
9015
9044
  return out;
9016
9045
  }
9017
9046
  /**
9018
- * Creates a function that escapes all characters matched by the given regular
9019
- * expression using the given map of characters to escape to their entities.
9020
- * @param regex Regular expression to match characters to escape.
9021
- * @param map Map of characters to escape to their entities.
9022
- * @returns Function that escapes all characters matched by the given regular
9023
- * expression using the given map of characters to escape to their entities.
9047
+ * Escape `data` using `re`, mapping each matched character to its entity.
9048
+ * Every match is one UTF-16 code unit, so its index is `lastIndex - 1`.
9049
+ * @param re Global regex matching exactly the characters to escape
9050
+ * (`"`, `&`, `'`, `<`, `>`, `\u00A0` at most).
9051
+ * @param data String to escape.
9024
9052
  */
9025
- function getEscaper(regex, map) {
9026
- return function escape(data) {
9027
- let match;
9028
- let lastIndex = 0;
9029
- let result = "";
9030
- while (match = regex.exec(data)) {
9031
- if (lastIndex !== match.index) result += data.substring(lastIndex, match.index);
9032
- result += map.get(match[0].charCodeAt(0));
9033
- lastIndex = match.index + 1;
9034
- }
9035
- return result + data.substring(lastIndex);
9036
- };
9053
+ function escapeWithRegex(re, data) {
9054
+ re.lastIndex = 0;
9055
+ if (!re.test(data)) return data;
9056
+ let out = "";
9057
+ let last = 0;
9058
+ do {
9059
+ const index = re.lastIndex - 1;
9060
+ if (last !== index) out += data.substring(last, index);
9061
+ const char = data.charCodeAt(index);
9062
+ out += getEscape(char);
9063
+ last = index + 1;
9064
+ } while (re.test(data));
9065
+ return out + data.substring(last);
9037
9066
  }
9067
+ const attributeEscapeRegex = /["&\u{A0}]/gu;
9038
9068
  /**
9039
9069
  * Encodes all characters that have to be escaped in HTML attributes,
9040
9070
  * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
9041
9071
  * @param data String to escape.
9042
9072
  */
9043
- const escapeAttribute = /* #__PURE__ */ getEscaper(/["&\u00A0]/g, /* @__PURE__ */ new Map([
9044
- [34, "&quot;"],
9045
- [38, "&amp;"],
9046
- [160, "&nbsp;"]
9047
- ]));
9073
+ function escapeAttribute(data) {
9074
+ return escapeWithRegex(attributeEscapeRegex, data);
9075
+ }
9076
+ const textEscapeRegex = /[&<>\u{A0}]/gu;
9048
9077
  /**
9049
9078
  * Encodes all characters that have to be escaped in HTML text,
9050
9079
  * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
9051
9080
  * @param data String to escape.
9052
9081
  */
9053
- const escapeText = /* #__PURE__ */ getEscaper(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
9054
- [38, "&amp;"],
9055
- [60, "&lt;"],
9056
- [62, "&gt;"],
9057
- [160, "&nbsp;"]
9058
- ]));
9082
+ function escapeText(data) {
9083
+ return escapeWithRegex(textEscapeRegex, data);
9084
+ }
9059
9085
  //#endregion
9060
9086
  //#region ../../node_modules/.pnpm/dom-serializer@3.1.1/node_modules/dom-serializer/dist/foreign-names.js
9061
9087
  /**
@@ -22966,6 +22992,33 @@ function md5hex(input) {
22966
22992
  return hex;
22967
22993
  }
22968
22994
  //#endregion
22995
+ //#region src/qti-to-learnosity/utils/mediaFeature.ts
22996
+ /**
22997
+ * Build a stable UUID-shaped identifier for a media feature.
22998
+ *
22999
+ * Feature output must remain identical for equivalent directory and ZIP
23000
+ * package conversions, so the identifier is derived from the final media URL
23001
+ * rather than generated randomly. The UUID version and variant bits are set
23002
+ * to keep the value compatible with consumers expecting a v4-shaped UUID.
23003
+ */
23004
+ function buildMediaFeatureId(transformedUrl) {
23005
+ const hash = md5hex(transformedUrl).split("");
23006
+ const variant = [
23007
+ "8",
23008
+ "9",
23009
+ "a",
23010
+ "b"
23011
+ ][parseInt(hash[16], 16) & 3];
23012
+ hash[12] = "4";
23013
+ hash[16] = variant;
23014
+ return `${hash.slice(0, 8).join("")}-${hash.slice(8, 12).join("")}-${hash.slice(12, 16).join("")}-${hash.slice(16, 20).join("")}-${hash.slice(20).join("")}`;
23015
+ }
23016
+ /** Build a Learnosity simple-feature span for audio or hosted video. */
23017
+ function buildMediaFeatureSpan(transformedUrl, kind, featureId = buildMediaFeatureId(transformedUrl)) {
23018
+ if (kind === "audio") return `<span class="learnosity-feature" data-player="button" data-simplefeature_id="${featureId}" data-src="${transformedUrl}" data-type="audioplayer"></span>`;
23019
+ return `<span class="learnosity-feature" data-player_type="hosted-video" data-simplefeature_id="${featureId}" data-src="${transformedUrl}" data-text_alternative.caption.src="" data-type="videoplayer"></span>`;
23020
+ }
23021
+ //#endregion
22969
23022
  //#region src/qti-to-learnosity/utils/convertObjectElement.ts
22970
23023
  /**
22971
23024
  * Convert QTI <object> elements to appropriate Learnosity HTML elements
@@ -23017,7 +23070,7 @@ function buildDeterministicFeatureId(transformedUrl) {
23017
23070
  * <object data="video.mp4" type="video/mp4"/>
23018
23071
  * → <span class="learnosity-feature" data-player_type="hosted-video" data-simplefeature_id="..." data-src="[cdn-url]" data-text_alternative.caption.src="" data-type="videoplayer"></span>
23019
23072
  */
23020
- function convertObjectToElement(objectTag, organisationId, mediaVault = false, customAssetUrl) {
23073
+ function convertObjectToElement(objectTag, organisationId, mediaVault = false, customAssetUrl, assetContext = {}) {
23021
23074
  const dataMatch = objectTag.match(/data=["']([^"']+)["']/i);
23022
23075
  const srcMatch = objectTag.match(/src=["']([^"']+)["']/i);
23023
23076
  const typeMatch = objectTag.match(/type=["']([^"']+)["']/i);
@@ -23027,11 +23080,11 @@ function convertObjectToElement(objectTag, organisationId, mediaVault = false, c
23027
23080
  if (!urlMatch) return objectTag;
23028
23081
  const sourceUrl = urlMatch[1];
23029
23082
  const category = getMimeTypeCategory(typeMatch ? typeMatch[1] : "");
23030
- const transformedUrl = transformUrl(sourceUrl, organisationId, mediaVault, customAssetUrl);
23083
+ const transformedUrl = transformUrl(sourceUrl, organisationId, mediaVault, customAssetUrl, assetContext);
23031
23084
  switch (category) {
23032
23085
  case "image": return buildImageTag(transformedUrl, heightMatch, widthMatch);
23033
- case "audio": return `<span class="learnosity-feature" data-player="button" data-simplefeature_id="${buildDeterministicFeatureId(transformedUrl)}" data-src="${transformedUrl}" data-type="audioplayer"></span>`;
23034
- case "video": return `<span class="learnosity-feature" data-player_type="hosted-video" data-simplefeature_id="${buildDeterministicFeatureId(transformedUrl)}" data-src="${transformedUrl}" data-text_alternative.caption.src="" data-type="videoplayer"></span>`;
23086
+ case "audio": return buildMediaFeatureSpan(transformedUrl, "audio", buildDeterministicFeatureId(transformedUrl));
23087
+ case "video": return buildMediaFeatureSpan(transformedUrl, "video", buildDeterministicFeatureId(transformedUrl));
23035
23088
  default: return objectTag.replace(sourceUrl, transformedUrl);
23036
23089
  }
23037
23090
  }
@@ -23075,55 +23128,139 @@ function normalizeTableClass(html) {
23075
23128
  });
23076
23129
  }
23077
23130
  //#endregion
23078
- //#region src/qti-to-learnosity/utils/assetUrlTransform.ts
23131
+ //#region src/qti-to-learnosity/utils/assetIdentity.ts
23079
23132
  /**
23080
- * Asset URL transformation for Learnosity CDN
23081
- * TASK 030
23133
+ * Browser-safe helpers for identifying package-local QTI assets.
23082
23134
  *
23083
- * Transforms asset URLs in HTML content to use Learnosity CDN URLs.
23135
+ * QTI asset references are package-relative paths, not filesystem paths. Keeping
23136
+ * their canonical form here makes directory and ZIP inputs produce the same
23137
+ * identity while rejecting references that could escape the package root.
23084
23138
  */
23139
+ /** Asset extensions copied and rewritten by QTI → Learnosity conversion. */
23140
+ const QTI_ASSET_EXTENSIONS = [
23141
+ ".png",
23142
+ ".jpg",
23143
+ ".jpeg",
23144
+ ".gif",
23145
+ ".svg",
23146
+ ".webp",
23147
+ ".bmp",
23148
+ ".ico",
23149
+ ".mp3",
23150
+ ".mp4",
23151
+ ".wav",
23152
+ ".ogg",
23153
+ ".webm",
23154
+ ".ogv",
23155
+ ".m4a",
23156
+ ".m4v",
23157
+ ".css",
23158
+ ".woff",
23159
+ ".woff2",
23160
+ ".ttf",
23161
+ ".eot",
23162
+ ".pdf",
23163
+ ".json"
23164
+ ];
23165
+ function isSupportedQtiAssetPath(path) {
23166
+ const lowerPath = path.toLowerCase();
23167
+ return !lowerPath.endsWith(".html") && !lowerPath.endsWith(".htm") && QTI_ASSET_EXTENSIONS.some((extension) => lowerPath.endsWith(extension));
23168
+ }
23169
+ function isUnsafeQtiAssetHrefError(error) {
23170
+ return error instanceof Error && (error.message.startsWith("Unsafe QTI asset href:") || error.message.startsWith("QTI asset href has no filename:"));
23171
+ }
23085
23172
  /**
23086
- * Supported asset file extensions
23087
- */
23088
- const SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
23089
- "jpg",
23090
- "jpeg",
23091
- "png",
23092
- "gif",
23093
- "svg",
23094
- "webp",
23095
- "mp3",
23096
- "wav",
23097
- "ogg",
23098
- "m4a",
23099
- "mp4",
23100
- "webm",
23101
- "ogv",
23102
- "m4v"
23103
- ]);
23173
+ * Canonicalize a package-relative QTI asset href.
23174
+ *
23175
+ * Query strings and fragments are URL metadata and do not identify a different
23176
+ * package asset. Path separators are normalized to `/`, dot segments are
23177
+ * resolved, and traversal above the package root is rejected.
23178
+ */
23179
+ function stripHrefMetadata(href) {
23180
+ const metadataStart = href.search(/[?#]/);
23181
+ return (metadataStart === -1 ? href : href.slice(0, metadataStart)).replaceAll("\\", "/");
23182
+ }
23183
+ function assertPackageRelativePath(path, href) {
23184
+ const isAbsolute = path.startsWith("/") || /^[A-Za-z]:/.test(path) || /^[A-Za-z][A-Za-z\d+.-]*:/.test(path);
23185
+ if (!path || path.includes("\0") || isAbsolute) throw new Error(`Unsafe QTI asset href: ${href}`);
23186
+ if (path.endsWith("/")) throw new Error(`QTI asset href has no filename: ${href}`);
23187
+ }
23188
+ function normalizePathSegments(path, href) {
23189
+ const segments = [];
23190
+ for (const segment of path.split("/")) {
23191
+ if (!segment || segment === ".") continue;
23192
+ if (segment === "..") {
23193
+ if (segments.length === 0) throw new Error(`Unsafe QTI asset href: ${href}`);
23194
+ segments.pop();
23195
+ continue;
23196
+ }
23197
+ segments.push(segment);
23198
+ }
23199
+ if (segments.length === 0) throw new Error(`QTI asset href has no filename: ${href}`);
23200
+ return segments.join("/");
23201
+ }
23202
+ function canonicalizeQtiAssetHref(href) {
23203
+ if (typeof href !== "string") throw new TypeError("QTI asset href must be a string");
23204
+ const path = stripHrefMetadata(href);
23205
+ assertPackageRelativePath(path, href);
23206
+ return normalizePathSegments(path, href);
23207
+ }
23208
+ /** Return the final filename from a canonicalized package-relative href. */
23209
+ function extractQtiAssetBasename(href) {
23210
+ const canonicalHref = canonicalizeQtiAssetHref(href);
23211
+ return canonicalHref.slice(canonicalHref.lastIndexOf("/") + 1);
23212
+ }
23104
23213
  /**
23105
- * Patterns that detect any asset reference in HTML (object[data] or
23106
- * img/audio/video/source[src]). Precompiled once; used only with
23107
- * `RegExp.prototype.test` on non-global regexes, so they are safe to share.
23214
+ * Return the final filename extension, including its leading dot.
23215
+ * Dotfiles and filenames ending in a dot have no extension.
23108
23216
  */
23109
- const ASSET_REFERENCE_PATTERNS = [
23110
- /<object\s+[^>]*data=/i,
23111
- /<img\s+[^>]*src=/i,
23112
- /<audio\s+[^>]*src=/i,
23113
- /<video\s+[^>]*src=/i,
23114
- /<source\s+[^>]*src=/i
23115
- ];
23116
- /** Matches `<object ...>` (optionally with its closing tag) for element conversion. */
23117
- const OBJECT_TAG_PATTERN = /<object\s+[^>]*>(?:<\/object>)?/gi;
23217
+ function extractQtiAssetExtension(href) {
23218
+ const basename = extractQtiAssetBasename(href);
23219
+ const extensionStart = basename.lastIndexOf(".");
23220
+ return extensionStart > 0 && extensionStart < basename.length - 1 ? basename.slice(extensionStart) : "";
23221
+ }
23118
23222
  /**
23119
- * src-attribute capture pattern for media elements (img/audio/video/source).
23223
+ * Serialize the item-scoped asset identity using an ordered JSON tuple.
23120
23224
  *
23121
- * Hardcoded literal (rather than built with `new RegExp`) so the pattern cannot
23122
- * be influenced at runtime. Global regex used only with
23123
- * `String.prototype.replace`, which resets lastIndex on completion, so sharing
23124
- * a single compiled instance across calls is safe.
23225
+ * JSON serialization is intentional: unlike delimiter-based concatenation, it
23226
+ * keeps the item reference and canonical href unambiguous when either value
23227
+ * contains punctuation that could otherwise be mistaken for a separator.
23125
23228
  */
23126
- const MEDIA_SRC_PATTERN = /(<(?:img|audio|video|source)\s+[^>]*src=["'])([^"']+)(["'][^>]*>)/gi;
23229
+ function serializeQtiAssetIdentity(finalItemReference, qtiAssetHref) {
23230
+ const canonicalHref = canonicalizeQtiAssetHref(qtiAssetHref);
23231
+ return JSON.stringify([finalItemReference, canonicalHref]);
23232
+ }
23233
+ /** Derive the lowercase MD5 hex hash for a canonical item-scoped identity. */
23234
+ function hashQtiAssetIdentity(finalItemReference, qtiAssetHref) {
23235
+ return md5hex(serializeQtiAssetIdentity(finalItemReference, qtiAssetHref));
23236
+ }
23237
+ /**
23238
+ * Select the output filename for a package-local QTI asset.
23239
+ *
23240
+ * Hashed naming is the default so the full item-scoped identity, rather than a
23241
+ * globally ambiguous source basename, determines the output name. Only the
23242
+ * canonical source extension is retained after the digest. Preserve mode is
23243
+ * an explicit compatibility opt-out and returns the canonical final basename.
23244
+ */
23245
+ function selectQtiAssetFilename(finalItemReference, qtiAssetHref, preserveAssetFilenames = false) {
23246
+ const canonicalHref = canonicalizeQtiAssetHref(qtiAssetHref);
23247
+ if (preserveAssetFilenames) return extractQtiAssetBasename(canonicalHref);
23248
+ return `${hashQtiAssetIdentity(finalItemReference, canonicalHref)}${extractQtiAssetExtension(canonicalHref)}`;
23249
+ }
23250
+ //#endregion
23251
+ //#region src/qti-to-learnosity/utils/assetUrlTransform.ts
23252
+ /**
23253
+ * Asset URL transformation for Learnosity CDN
23254
+ * TASK 030
23255
+ *
23256
+ * Transforms asset URLs in HTML content to use Learnosity CDN URLs.
23257
+ */
23258
+ /** Matches supported asset-bearing HTML attributes on any element. */
23259
+ const ASSET_ATTRIBUTE_PATTERN = /(<[A-Za-z][^>]*?\b(?:src|data|href)\s*=\s*["'])([^"']+)(["'][^>]*>)/gi;
23260
+ /** Matches <object ...> (optionally with its closing tag) for element conversion. */
23261
+ const OBJECT_TAG_PATTERN = /<object\s+[^>]*>(?:<\/object>)?/gi;
23262
+ /** Matches anchors whose href points to inline audio/video media. */
23263
+ const INLINE_MEDIA_LINK_PATTERN = /<a\b([^>]*?)\bhref\s*=\s*(["'])([^"']+)\2([^>]*)>([\s\S]*?)<\/a\s*>/gi;
23127
23264
  /**
23128
23265
  * Extract filename from a URL path
23129
23266
  * Examples:
@@ -23135,12 +23272,26 @@ function extractFilename$1(url) {
23135
23272
  const segments = url.split("?")[0].split("#")[0].split("/");
23136
23273
  return segments[segments.length - 1];
23137
23274
  }
23138
- /**
23139
- * Check if a filename has a supported asset extension
23140
- */
23141
23275
  function isSupportedAsset(filename) {
23142
- const ext = filename.split(".").pop()?.toLowerCase();
23143
- return ext ? SUPPORTED_EXTENSIONS.has(ext) : false;
23276
+ return isSupportedQtiAssetPath(filename);
23277
+ }
23278
+ function getInlineMediaKind(url, attributes) {
23279
+ const mimeType = attributes.match(/\btype\s*=\s*(["'])([^"']+)\1/i)?.[2].toLowerCase();
23280
+ if (mimeType?.startsWith("audio/")) return "audio";
23281
+ if (mimeType?.startsWith("video/")) return "video";
23282
+ const filename = extractFilename$1(url).toLowerCase();
23283
+ if ([
23284
+ ".mp3",
23285
+ ".wav",
23286
+ ".ogg",
23287
+ ".m4a"
23288
+ ].some((extension) => filename.endsWith(extension))) return "audio";
23289
+ if ([
23290
+ ".mp4",
23291
+ ".webm",
23292
+ ".ogv",
23293
+ ".m4v"
23294
+ ].some((extension) => filename.endsWith(extension))) return "video";
23144
23295
  }
23145
23296
  /**
23146
23297
  * Build Learnosity CDN URL for an asset
@@ -23150,17 +23301,24 @@ function buildLearnosityAssetUrl(filename, organisationId, mediaVault = false, c
23150
23301
  if (customAssetUrl) return `${customAssetUrl.endsWith("/") ? customAssetUrl.slice(0, -1) : customAssetUrl}/${filename}`;
23151
23302
  return `https://${mediaVault ? "media-vault" : "assets"}.learnosity.com/organisations/${organisationId}/${filename}`;
23152
23303
  }
23304
+ function resolveQtiAssetHref(url, sourceHrefBase) {
23305
+ const normalizedUrl = url.split(/[?#]/, 1)[0].replaceAll("\\", "/");
23306
+ const isItemRelative = /^\.\.?\//.test(normalizedUrl) || !normalizedUrl.includes("/");
23307
+ if (!sourceHrefBase || !isItemRelative) return canonicalizeQtiAssetHref(url);
23308
+ const baseHref = canonicalizeQtiAssetHref(sourceHrefBase);
23309
+ return canonicalizeQtiAssetHref(`${baseHref.slice(0, baseHref.lastIndexOf("/") + 1)}${normalizedUrl}`);
23310
+ }
23153
23311
  /**
23154
23312
  * Transform a single URL to Learnosity CDN format
23155
23313
  * Exported for use in image object source fields
23156
23314
  */
23157
- function transformUrl(url, organisationId, mediaVault = false, customAssetUrl) {
23315
+ function transformUrl(url, organisationId, mediaVault = false, customAssetUrl, context = {}) {
23158
23316
  if (url.includes("assets.learnosity.com") || url.includes("media-vault.learnosity.com")) return url;
23159
- if (url.match(/^https?:\/\//i)) return url;
23317
+ if (/^https?:\/\//i.test(url) || url.startsWith("//")) return url;
23160
23318
  if (url.startsWith("data:")) return url;
23161
23319
  const filename = extractFilename$1(url);
23162
23320
  if (!isSupportedAsset(filename)) return url;
23163
- return buildLearnosityAssetUrl(filename, organisationId, mediaVault, customAssetUrl);
23321
+ return buildLearnosityAssetUrl(context.finalItemReference ? selectQtiAssetFilename(context.finalItemReference, resolveQtiAssetHref(url, context.sourceHrefBase), context.preserveAssetFilenames ?? false) : filename, organisationId, mediaVault, customAssetUrl);
23164
23322
  }
23165
23323
  /**
23166
23324
  * Transform asset URLs in HTML content
@@ -23178,14 +23336,24 @@ function transformUrl(url, organisationId, mediaVault = false, customAssetUrl) {
23178
23336
  */
23179
23337
  function transformAssetUrls(html, options) {
23180
23338
  if (!html) return html;
23181
- if (ASSET_REFERENCE_PATTERNS.some((pattern) => pattern.test(html)) && !options.organisationId) throw new Error("Asset references found in QTI content but no --organisation_id provided. Please provide --organisation_id to convert assets to Learnosity CDN URLs.");
23339
+ if (Array.from(html.matchAll(ASSET_ATTRIBUTE_PATTERN)).some((match) => isSupportedAsset(extractFilename$1(match[2]))) && !options.organisationId) throw new Error("Asset references found in QTI content but no --organisation_id provided. Please provide --organisation_id to convert assets to Learnosity CDN URLs.");
23182
23340
  if (!options.organisationId) return normalizeTableClass(html);
23183
23341
  const orgId = options.organisationId;
23184
23342
  const mediaVault = options.mediaVault ?? false;
23185
23343
  const customAssetUrl = options.customAssetUrl;
23344
+ const assetContext = {
23345
+ finalItemReference: options.finalItemReference,
23346
+ preserveAssetFilenames: options.preserveAssetFilenames,
23347
+ sourceHrefBase: options.sourceHrefBase
23348
+ };
23186
23349
  let result = html;
23187
- result = result.replace(OBJECT_TAG_PATTERN, (match) => convertObjectToElement(match, orgId, mediaVault, customAssetUrl));
23188
- result = result.replace(MEDIA_SRC_PATTERN, (_match, prefix, url, suffix) => prefix + transformUrl(url, orgId, mediaVault, customAssetUrl) + suffix);
23350
+ result = result.replace(OBJECT_TAG_PATTERN, (match) => convertObjectToElement(match, orgId, mediaVault, customAssetUrl, assetContext));
23351
+ result = result.replace(INLINE_MEDIA_LINK_PATTERN, (match, beforeAttributes, _quote, url, afterAttributes) => {
23352
+ const kind = getInlineMediaKind(url, `${beforeAttributes}${afterAttributes}`);
23353
+ if (!kind) return match;
23354
+ return buildMediaFeatureSpan(transformUrl(url, orgId, mediaVault, customAssetUrl, assetContext), kind);
23355
+ });
23356
+ result = result.replace(ASSET_ATTRIBUTE_PATTERN, (_match, prefix, url, suffix) => prefix + transformUrl(url, orgId, mediaVault, customAssetUrl, assetContext) + suffix);
23189
23357
  result = normalizeHtmlWhitespace(result);
23190
23358
  result = normalizeTableClass(result);
23191
23359
  return result;
@@ -23331,23 +23499,30 @@ function mapCorrectPairsToValidation(correctPairs, stemIdToIndex, optionIdToInde
23331
23499
  /**
23332
23500
  * Convert matchInteraction to Learnosity choicematrix
23333
23501
  */
23334
- function convertMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
23502
+ function convertMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
23335
23503
  const parsed = readAssessmentItemMatch(inputXml);
23336
23504
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
23337
23505
  diagnostics.push(...updatedDiagnostics);
23338
23506
  if (hasErrors(diagnostics)) return { diagnostics };
23339
23507
  if (!parsed.identifier || parsed.stems.length === 0 || parsed.options.length === 0) return { diagnostics };
23340
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23508
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23509
+ const transformContext = {
23510
+ finalItemReference: itemRef,
23511
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
23512
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
23513
+ };
23341
23514
  const questionRef = md5hex(itemRef);
23342
23515
  const stems = parsed.stems.map((stem) => transformAssetUrls(stem.text, {
23343
23516
  organisationId,
23344
23517
  mediaVault,
23345
- customAssetUrl
23518
+ customAssetUrl,
23519
+ ...transformContext
23346
23520
  }));
23347
23521
  const options = parsed.options.map((option) => transformAssetUrls(option.text, {
23348
23522
  organisationId,
23349
23523
  mediaVault,
23350
- customAssetUrl
23524
+ customAssetUrl,
23525
+ ...transformContext
23351
23526
  }));
23352
23527
  const stemIdToIndex = /* @__PURE__ */ new Map();
23353
23528
  parsed.stems.forEach((stem, index) => {
@@ -23365,7 +23540,8 @@ function convertMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId
23365
23540
  const stimulus = transformAssetUrls(parsed.stimulusText ? `<p>${parsed.stimulusText}</p>` : "", {
23366
23541
  organisationId,
23367
23542
  mediaVault,
23368
- customAssetUrl
23543
+ customAssetUrl,
23544
+ ...transformContext
23369
23545
  });
23370
23546
  const item = {
23371
23547
  item: {
@@ -23745,25 +23921,32 @@ function buildGapValidation(gaps, gapIdToGapTextIds, gapTextIdToContent, sourceF
23745
23921
  /**
23746
23922
  * Convert gapMatchInteraction to Learnosity clozeassociation
23747
23923
  */
23748
- function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
23924
+ function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
23749
23925
  const parsed = readAssessmentItemGapMatch(inputXml);
23750
23926
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
23751
23927
  diagnostics.push(...updatedDiagnostics);
23752
23928
  if (hasErrors(diagnostics)) return { diagnostics };
23753
23929
  if (!parsed.identifier || parsed.gapTexts.length === 0 || parsed.gaps.length === 0) return { diagnostics };
23754
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23930
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
23931
+ const transformContext = {
23932
+ finalItemReference: itemRef,
23933
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
23934
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
23935
+ };
23755
23936
  const questionRef = md5hex(itemRef);
23756
23937
  const possibleResponses = parsed.gapTexts.map((gt) => transformAssetUrls(gt.text, {
23757
23938
  organisationId,
23758
23939
  mediaVault,
23759
- customAssetUrl
23940
+ customAssetUrl,
23941
+ ...transformContext
23760
23942
  }));
23761
23943
  const gapTextIdToContent = /* @__PURE__ */ new Map();
23762
23944
  parsed.gapTexts.forEach((gt) => {
23763
23945
  const transformedText = transformAssetUrls(gt.text, {
23764
23946
  organisationId,
23765
23947
  mediaVault,
23766
- customAssetUrl
23948
+ customAssetUrl,
23949
+ ...transformContext
23767
23950
  });
23768
23951
  gapTextIdToContent.set(gt.identifier, transformedText);
23769
23952
  });
@@ -23781,7 +23964,8 @@ function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisatio
23781
23964
  template: transformAssetUrls(parsed.templateHtml ?? "", {
23782
23965
  organisationId,
23783
23966
  mediaVault,
23784
- customAssetUrl
23967
+ customAssetUrl,
23968
+ ...transformContext
23785
23969
  }),
23786
23970
  possible_responses: possibleResponses,
23787
23971
  shuffle_options: parsed.shuffle ?? false,
@@ -23796,7 +23980,8 @@ function convertGapMatchToLearnosity(inputXml, diagnostics, lomTags, organisatio
23796
23980
  if (parsed.promptHtml) questionData.stimulus = transformAssetUrls(parsed.promptHtml, {
23797
23981
  organisationId,
23798
23982
  mediaVault,
23799
- customAssetUrl
23983
+ customAssetUrl,
23984
+ ...transformContext
23800
23985
  });
23801
23986
  if (maxResponsesPerZone > 1) questionData.max_response_per_zone = maxResponsesPerZone;
23802
23987
  const choiceCounts = /* @__PURE__ */ new Map();
@@ -24201,19 +24386,22 @@ function buildValidationValues(interactions, responseDeclarations, diagnostics,
24201
24386
  * Convert inlineChoiceInteraction to Learnosity clozedropdown
24202
24387
  * TASK 036: Added stimulusOverride parameter for composite items
24203
24388
  */
24204
- function convertInlineChoiceToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
24389
+ function convertInlineChoiceToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
24205
24390
  const parsed = readAssessmentItemInlineChoice(inputXml);
24206
24391
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
24207
24392
  diagnostics.push(...updatedDiagnostics);
24208
24393
  if (hasErrors(diagnostics)) return { diagnostics };
24209
24394
  if (!parsed.identifier || parsed.interactions.length === 0) return { diagnostics };
24210
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24211
- const questionRef = md5hex(itemRef);
24395
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24212
24396
  const transformOpts = {
24213
24397
  organisationId,
24214
24398
  mediaVault,
24215
- customAssetUrl
24399
+ customAssetUrl,
24400
+ finalItemReference: itemRef,
24401
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
24402
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
24216
24403
  };
24404
+ const questionRef = md5hex(itemRef);
24217
24405
  const possibleResponses = parsed.interactions.map((interaction) => interaction.choices.map((choice) => transformAssetUrls(choice.text, transformOpts)));
24218
24406
  const validationValue = buildValidationValues(parsed.interactions, parsed.responseDeclarations, diagnostics, transformOpts, sourceFile);
24219
24407
  if (!validationValue) return { diagnostics };
@@ -24337,6 +24525,7 @@ function readAssessmentItemOrder(inputXml) {
24337
24525
  } else if (localName === "value" && capture === "correct") {}
24338
24526
  if (capture === "stimulus" && stack.length > stimulusCaptureDepth && localName !== "orderInteraction") stimulusBuf.push(buildOpeningTag$3(tag, localName));
24339
24527
  else if (capture === "prompt" && localName !== "prompt") promptBuf.push(buildOpeningTag$3(tag, localName));
24528
+ else if (capture === "choice" && localName !== "simpleChoice") choiceBuf.push(buildOpeningTag$3(tag, localName));
24340
24529
  });
24341
24530
  parser.on("text", (text) => {
24342
24531
  if (capture === "stimulus") stimulusBuf.push(text);
@@ -24360,6 +24549,8 @@ function readAssessmentItemOrder(inputXml) {
24360
24549
  capture = null;
24361
24550
  } else if (capture === "prompt" && localName !== "prompt") {
24362
24551
  if (!QTI_VOID_ELEMENTS.has(localName.toLowerCase())) promptBuf.push(`</${localName}>`);
24552
+ } else if (capture === "choice" && localName !== "simpleChoice") {
24553
+ if (!QTI_VOID_ELEMENTS.has(localName.toLowerCase())) choiceBuf.push(`</${localName}>`);
24363
24554
  } else if (localName === "simpleChoice" && capture === "choice") {
24364
24555
  const text = normalizeWhitespace(choiceBuf.join(""));
24365
24556
  if (currentChoiceId) {
@@ -24477,23 +24668,30 @@ function readAssessmentItemOrder(inputXml) {
24477
24668
  /**
24478
24669
  * Convert orderInteraction to Learnosity orderlist
24479
24670
  */
24480
- function convertOrderToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
24671
+ function convertOrderToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
24481
24672
  const parsed = readAssessmentItemOrder(inputXml);
24482
24673
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
24483
24674
  diagnostics.push(...updatedDiagnostics);
24484
24675
  if (hasErrors(diagnostics)) return { diagnostics };
24485
24676
  if (!parsed.identifier || !parsed.responseIdentifier || parsed.choices.length === 0) return { diagnostics };
24486
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24677
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
24678
+ const transformContext = {
24679
+ finalItemReference: itemRef,
24680
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
24681
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
24682
+ };
24487
24683
  const questionRef = md5hex(itemRef);
24488
24684
  const stimulus = transformAssetUrls(parsed.stimulusText ?? "", {
24489
24685
  organisationId,
24490
24686
  mediaVault,
24491
- customAssetUrl
24687
+ customAssetUrl,
24688
+ ...transformContext
24492
24689
  });
24493
24690
  const list = parsed.choices.map((choice) => transformAssetUrls(choice.text, {
24494
24691
  organisationId,
24495
24692
  mediaVault,
24496
- customAssetUrl
24693
+ customAssetUrl,
24694
+ ...transformContext
24497
24695
  }));
24498
24696
  let validationValue;
24499
24697
  if (parsed.correctOrder && parsed.correctOrder.length > 0) {
@@ -24762,14 +24960,14 @@ function readAssessmentItemHotspot(inputXml) {
24762
24960
  * Convert QTI shape coordinates to Learnosity polygon coordinates
24763
24961
  * QTI uses absolute pixel coordinates, Learnosity uses percentage coordinates
24764
24962
  */
24765
- function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24963
+ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics, sourceFile) {
24766
24964
  const coords = choice.coords.split(",").map((c) => parseFloat(c.trim()));
24767
24965
  if (choice.shape === "circle") {
24768
24966
  if (coords.length !== 3) {
24769
24967
  diagnostics.push({
24770
24968
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24771
24969
  level: "error",
24772
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
24970
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24773
24971
  message: `Invalid circle coords for ${choice.identifier}: expected 3 values (x,y,radius), got ${coords.length}`
24774
24972
  });
24775
24973
  return null;
@@ -24792,7 +24990,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24792
24990
  diagnostics.push({
24793
24991
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24794
24992
  level: "error",
24795
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
24993
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24796
24994
  message: `Invalid rect coords for ${choice.identifier}: expected 4 values (x1,y1,x2,y2), got ${coords.length}`
24797
24995
  });
24798
24996
  return null;
@@ -24821,7 +25019,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24821
25019
  diagnostics.push({
24822
25020
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24823
25021
  level: "error",
24824
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
25022
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24825
25023
  message: `Invalid poly coords for ${choice.identifier}: expected at least 6 values (3 points) in pairs, got ${coords.length}`
24826
25024
  });
24827
25025
  return null;
@@ -24837,7 +25035,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24837
25035
  diagnostics.push({
24838
25036
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24839
25037
  level: "error",
24840
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
25038
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24841
25039
  message: `Invalid ellipse coords for ${choice.identifier}: expected 4 values (cx,cy,rx,ry), got ${coords.length}`
24842
25040
  });
24843
25041
  return null;
@@ -24859,7 +25057,7 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24859
25057
  diagnostics.push({
24860
25058
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
24861
25059
  level: "error",
24862
- file: `hotspotChoice[@identifier="${choice.identifier}"]`,
25060
+ file: sourceFile ?? `hotspotChoice[@identifier="${choice.identifier}"]`,
24863
25061
  message: `Unsupported shape type: ${choice.shape}`
24864
25062
  });
24865
25063
  return null;
@@ -24868,17 +25066,19 @@ function convertShapeToPolygon(choice, imageWidth, imageHeight, diagnostics) {
24868
25066
  /**
24869
25067
  * Build the combined stimulus HTML from parsed stimulusText and promptText
24870
25068
  */
24871
- function buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl) {
25069
+ function buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
24872
25070
  let stimulus = "";
24873
25071
  if (parsed.stimulusText) stimulus += transformAssetUrls(parsed.stimulusText, {
24874
25072
  organisationId,
24875
25073
  mediaVault,
24876
- customAssetUrl
25074
+ customAssetUrl,
25075
+ ...assetTransformContext
24877
25076
  });
24878
25077
  if (parsed.promptText) stimulus += `<p>${transformAssetUrls(parsed.promptText, {
24879
25078
  organisationId,
24880
25079
  mediaVault,
24881
- customAssetUrl
25080
+ customAssetUrl,
25081
+ ...assetTransformContext
24882
25082
  })}</p>`;
24883
25083
  return stimulus;
24884
25084
  }
@@ -24903,7 +25103,7 @@ function buildHotspotValidation(correctResponses, choiceIdToIndex) {
24903
25103
  /**
24904
25104
  * Convert hotspotInteraction to Learnosity hotspot
24905
25105
  */
24906
- function convertHotspotToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot) {
25106
+ function convertHotspotToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot, assetTransformContext) {
24907
25107
  const parsed = readAssessmentItemHotspot(inputXml);
24908
25108
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
24909
25109
  diagnostics.push(...updatedDiagnostics);
@@ -24925,14 +25125,19 @@ function convertHotspotToLearnosity(inputXml, diagnostics, lomTags, organisation
24925
25125
  return { diagnostics };
24926
25126
  }
24927
25127
  }
24928
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25128
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25129
+ const transformContext = {
25130
+ finalItemReference: itemRef,
25131
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
25132
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
25133
+ };
24929
25134
  const questionRef = md5hex(itemRef);
24930
- const stimulus = buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl);
24931
- const imageSource = organisationId ? transformUrl(parsed.imageSource, organisationId, mediaVault, customAssetUrl) : parsed.imageSource;
25135
+ const stimulus = buildHotspotStimulus(parsed, organisationId, mediaVault, customAssetUrl, transformContext);
25136
+ const imageSource = organisationId ? transformUrl(parsed.imageSource, organisationId, mediaVault, customAssetUrl, transformContext) : parsed.imageSource;
24932
25137
  const areas = [];
24933
25138
  const choiceIdToIndex = /* @__PURE__ */ new Map();
24934
25139
  for (const choice of parsed.hotspotChoices) {
24935
- const polygon = convertShapeToPolygon(choice, parsed.imageWidth, parsed.imageHeight, diagnostics);
25140
+ const polygon = convertShapeToPolygon(choice, parsed.imageWidth, parsed.imageHeight, diagnostics, sourceFile);
24936
25141
  if (polygon) {
24937
25142
  choiceIdToIndex.set(choice.identifier, areas.length);
24938
25143
  areas.push(polygon);
@@ -25211,14 +25416,19 @@ function readAssessmentItemHottext(inputXml) {
25211
25416
  /**
25212
25417
  * Convert hottextInteraction to Learnosity tokenhighlight
25213
25418
  */
25214
- function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
25419
+ function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
25215
25420
  const parsed = readAssessmentItemHottext(inputXml);
25216
25421
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
25217
25422
  diagnostics.push(...updatedDiagnostics);
25218
25423
  if (hasErrors(diagnostics)) return { diagnostics };
25219
25424
  if (!parsed.identifier || !parsed.responseIdentifier || !parsed.templateHtml) return { diagnostics };
25220
25425
  if (parsed.hottextElements.length === 0) return { diagnostics };
25221
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25426
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25427
+ const transformContext = {
25428
+ finalItemReference: itemRef,
25429
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
25430
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
25431
+ };
25222
25432
  const questionRef = md5hex(itemRef);
25223
25433
  if (parsed.shuffle) diagnostics.push({
25224
25434
  code: DiagnosticCode.QTI_SHUFFLE_NOT_SUPPORTED,
@@ -25230,7 +25440,8 @@ function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisation
25230
25440
  if (stimulus) stimulus = transformAssetUrls(stimulus, {
25231
25441
  organisationId,
25232
25442
  mediaVault,
25233
- customAssetUrl
25443
+ customAssetUrl,
25444
+ ...transformContext
25234
25445
  });
25235
25446
  let template = parsed.templateHtml || "";
25236
25447
  const identifierToIndex = /* @__PURE__ */ new Map();
@@ -25243,7 +25454,8 @@ function convertHottextToLearnosity(inputXml, diagnostics, lomTags, organisation
25243
25454
  template = transformAssetUrls(template, {
25244
25455
  organisationId,
25245
25456
  mediaVault,
25246
- customAssetUrl
25457
+ customAssetUrl,
25458
+ ...transformContext
25247
25459
  });
25248
25460
  let validation = void 0;
25249
25461
  if (parsed.correctResponses && parsed.correctResponses.length > 0) {
@@ -25710,7 +25922,7 @@ function readAssessmentItemMcq(inputXml, stimulusOverride) {
25710
25922
  * Supports both single and composite (multiple) choiceInteractions
25711
25923
  * TASK 036: Added stimulusOverride parameter for composite items
25712
25924
  */
25713
- function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
25925
+ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
25714
25926
  const parsed = readAssessmentItemMcq(inputXml, stimulusOverride);
25715
25927
  const contextualDiagnostics = sourceFile ? parsed.diagnostics.map((d) => ({
25716
25928
  ...d,
@@ -25719,7 +25931,12 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25719
25931
  diagnostics.push(...contextualDiagnostics);
25720
25932
  if (diagnostics.some((d) => d.level === "error")) return { diagnostics };
25721
25933
  if (!parsed.identifier || parsed.interactions.length === 0) return { diagnostics };
25722
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25934
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
25935
+ const transformContext = {
25936
+ finalItemReference: itemRef,
25937
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
25938
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
25939
+ };
25723
25940
  const isComposite = parsed.interactions.length > 1;
25724
25941
  const questions = [];
25725
25942
  const widgets = [];
@@ -25729,7 +25946,8 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25729
25946
  const stimulus = interaction.stimulusText ? transformAssetUrls(interaction.stimulusText, {
25730
25947
  organisationId,
25731
25948
  mediaVault,
25732
- customAssetUrl
25949
+ customAssetUrl,
25950
+ ...transformContext
25733
25951
  }) : void 0;
25734
25952
  const choiceMapping = /* @__PURE__ */ new Map();
25735
25953
  const options = interaction.choices.map((choice) => {
@@ -25738,7 +25956,8 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25738
25956
  label: transformAssetUrls(choice.text, {
25739
25957
  organisationId,
25740
25958
  mediaVault,
25741
- customAssetUrl
25959
+ customAssetUrl,
25960
+ ...transformContext
25742
25961
  }),
25743
25962
  value: choice.identifier
25744
25963
  };
@@ -25775,7 +25994,8 @@ function convertMcqToLearnosity(inputXml, diagnostics, lomTags, sourceFile, orga
25775
25994
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
25776
25995
  organisationId,
25777
25996
  mediaVault,
25778
- customAssetUrl
25997
+ customAssetUrl,
25998
+ ...transformContext
25779
25999
  }) : void 0;
25780
26000
  questions.push({
25781
26001
  reference: questionRef,
@@ -26143,7 +26363,7 @@ function stripWrapperDiv(html) {
26143
26363
  * Convert textEntry (textEntryInteraction) to Learnosity clozetext or shorttext
26144
26364
  * TASK 036: Added stimulusOverride parameter for composite items
26145
26365
  */
26146
- function convertTextEntryToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
26366
+ function convertTextEntryToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
26147
26367
  const parsed = readAssessmentItemTextEntry(inputXml, stimulusOverride);
26148
26368
  const contextualDiagnostics = sourceFile ? parsed.diagnostics.map((d) => ({
26149
26369
  ...d,
@@ -26153,24 +26373,31 @@ function convertTextEntryToLearnosity(inputXml, diagnostics, lomTags, sourceFile
26153
26373
  if (diagnostics.some((d) => d.level === "error")) return { diagnostics };
26154
26374
  if (!parsed.identifier || parsed.textEntries.length === 0) return { diagnostics };
26155
26375
  if (typeof parsed.templateText === "string") parsed.templateText = stripWrapperDiv(parsed.templateText);
26156
- if (parsed.textEntries.length === 1 && /{{response}}(?:\s*<\/[^>]+>)*\s*$/.test(parsed.templateText.trim())) return convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile);
26157
- else return convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile);
26376
+ if (parsed.textEntries.length === 1 && /{{response}}(?:\s*<\/[^>]+>)*\s*$/.test(parsed.templateText.trim())) return convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext);
26377
+ else return convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext);
26158
26378
  }
26159
26379
  /**
26160
26380
  * Convert single textEntry to Learnosity shorttext
26161
26381
  */
26162
- function convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile) {
26163
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26382
+ function convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext) {
26383
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26384
+ const transformContext = {
26385
+ finalItemReference: itemRef,
26386
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26387
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26388
+ };
26164
26389
  const questionRef = md5hex(parsed.responseIdentifier ?? parsed.identifier);
26165
26390
  const stimulus = normalizeFinalText(transformAssetUrls((parsed.templateText || "").replace(/{{response}}(?:\s*<\/[^>]+>)*\s*$/, "").trim(), {
26166
26391
  organisationId,
26167
26392
  mediaVault,
26168
- customAssetUrl
26393
+ customAssetUrl,
26394
+ ...transformContext
26169
26395
  }));
26170
26396
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
26171
26397
  organisationId,
26172
26398
  mediaVault,
26173
- customAssetUrl
26399
+ customAssetUrl,
26400
+ ...transformContext
26174
26401
  }) : void 0;
26175
26402
  const entry = parsed.textEntries[0];
26176
26403
  const correctResponses = entry.correctResponses || (entry.correctResponse ? [entry.correctResponse] : []);
@@ -26244,25 +26471,33 @@ function convertShorttextToLearnosity(parsed, diagnostics, lomTags, organisation
26244
26471
  /**
26245
26472
  * Convert textEntry with template to Learnosity clozetext
26246
26473
  */
26247
- function convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile) {
26474
+ function convertClozetextToLearnosity(parsed, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext) {
26248
26475
  const correctResponses = [];
26249
26476
  for (const entry of parsed.textEntries) if (entry.correctResponse) correctResponses.push(entry.correctResponse);
26250
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26477
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
26478
+ const transformContext = {
26479
+ finalItemReference: itemRef,
26480
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26481
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26482
+ };
26251
26483
  const questionRef = md5hex(parsed.responseIdentifier ?? parsed.identifier);
26252
26484
  const stimulus = parsed.stimulusText ? normalizeFinalText(transformAssetUrls(parsed.stimulusText, {
26253
26485
  organisationId,
26254
26486
  mediaVault,
26255
- customAssetUrl
26487
+ customAssetUrl,
26488
+ ...transformContext
26256
26489
  })) : void 0;
26257
26490
  const template = normalizeFinalText(transformAssetUrls(parsed.templateText, {
26258
26491
  organisationId,
26259
26492
  mediaVault,
26260
- customAssetUrl
26493
+ customAssetUrl,
26494
+ ...transformContext
26261
26495
  }));
26262
26496
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
26263
26497
  organisationId,
26264
26498
  mediaVault,
26265
- customAssetUrl
26499
+ customAssetUrl,
26500
+ ...transformContext
26266
26501
  }) : void 0;
26267
26502
  const validation = {
26268
26503
  scoring_type: "exactMatch",
@@ -26495,8 +26730,13 @@ function readAssessmentItemExtendedText(inputXml) {
26495
26730
  /**
26496
26731
  * Build multi-interaction extended text item (multiple longtextV2 questions)
26497
26732
  */
26498
- function buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile) {
26499
- const itemRef = generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26733
+ function buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext) {
26734
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26735
+ const transformContext = {
26736
+ finalItemReference: itemRef,
26737
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26738
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26739
+ };
26500
26740
  const questions = [];
26501
26741
  const widgets = [];
26502
26742
  const questionSpans = [];
@@ -26506,7 +26746,8 @@ function buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnost
26506
26746
  const stimulus = transformAssetUrls(stimulusOverride[i], {
26507
26747
  organisationId,
26508
26748
  mediaVault,
26509
- customAssetUrl
26749
+ customAssetUrl,
26750
+ ...transformContext
26510
26751
  });
26511
26752
  widgets.push({
26512
26753
  reference: questionRef,
@@ -26556,19 +26797,25 @@ function extractResponseIdentifiers(inputXml, interactionTag) {
26556
26797
  * Convert extended text (extendedTextInteraction) to Learnosity longtextV2
26557
26798
  * TASK 036: Added stimulusOverride parameter for composite items
26558
26799
  */
26559
- function convertExtendedTextToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride) {
26800
+ function convertExtendedTextToLearnosity(inputXml, diagnostics, lomTags, sourceFile, organisationId, mediaVault, customAssetUrl, itemReferenceSource, stimulusOverride, assetTransformContext) {
26560
26801
  const parsed = readAssessmentItemExtendedText(inputXml);
26561
26802
  const contextualDiagnostics = addFileContextIfProvided(stimulusOverride ? filterOutCodes(parsed.diagnostics, [DiagnosticCode.QTI_EXTENDED_TEXT_MULTIPLE_INTERACTIONS]) : parsed.diagnostics, sourceFile);
26562
26803
  diagnostics.push(...contextualDiagnostics);
26563
26804
  if (hasErrors(diagnostics)) return { diagnostics };
26564
- if (stimulusOverride && stimulusOverride.length > 1) return buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile);
26565
- const itemRef = generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26805
+ if (stimulusOverride && stimulusOverride.length > 1) return buildMultiExtendedTextItem(parsed, inputXml, stimulusOverride, diagnostics, lomTags, organisationId, mediaVault, customAssetUrl, itemReferenceSource, sourceFile, assetTransformContext);
26806
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier ?? "unknown", itemReferenceSource, sourceFile);
26807
+ const transformContext = {
26808
+ finalItemReference: itemRef,
26809
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
26810
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
26811
+ };
26566
26812
  const questionRef = md5hex(parsed.responseIdentifier ?? parsed.identifier ?? "unknown");
26567
26813
  const stimulusRaw = stimulusOverride && stimulusOverride.length === 1 ? stimulusOverride[0] : parsed.stimulusText;
26568
26814
  const stimulus = stimulusRaw ? transformAssetUrls(stimulusRaw, {
26569
26815
  organisationId,
26570
26816
  mediaVault,
26571
- customAssetUrl
26817
+ customAssetUrl,
26818
+ ...transformContext
26572
26819
  }) : void 0;
26573
26820
  const instructorStimulus = parsed.instructorStimulus ? transformAssetUrls(parsed.instructorStimulus, {
26574
26821
  organisationId,
@@ -26863,7 +27110,7 @@ function buildValidationValue$1(hotspots, correctPairs, gapImgIdToResponse) {
26863
27110
  /**
26864
27111
  * Convert QTI graphicGapMatchInteraction to Learnosity imageclozeassociationV2
26865
27112
  */
26866
- function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
27113
+ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
26867
27114
  const parsed = readAssessmentItemGraphicGapMatch(inputXml);
26868
27115
  const contextualDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
26869
27116
  diagnostics.push(...contextualDiagnostics);
@@ -26879,6 +27126,12 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26879
27126
  }
26880
27127
  const bgWidth = parsed.backgroundImage.width;
26881
27128
  const bgHeight = parsed.backgroundImage.height;
27129
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
27130
+ const transformContext = {
27131
+ finalItemReference: itemRef,
27132
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
27133
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
27134
+ };
26882
27135
  const gapImgIdToResponse = /* @__PURE__ */ new Map();
26883
27136
  const possible_responses = parsed.gapImages.map((g) => {
26884
27137
  if (g.text !== void 0) {
@@ -26897,7 +27150,8 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26897
27150
  const transformedImgTag = transformAssetUrls(imgTag, {
26898
27151
  organisationId,
26899
27152
  mediaVault,
26900
- customAssetUrl
27153
+ customAssetUrl,
27154
+ ...transformContext
26901
27155
  });
26902
27156
  gapImgIdToResponse.set(g.identifier, transformedImgTag);
26903
27157
  return transformedImgTag;
@@ -26935,7 +27189,7 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26935
27189
  const question = {
26936
27190
  type: "imageclozeassociationV2",
26937
27191
  image: {
26938
- src: organisationId ? transformUrl(parsed.backgroundImage.src, organisationId, mediaVault, customAssetUrl) : parsed.backgroundImage.src,
27192
+ src: organisationId ? transformUrl(parsed.backgroundImage.src, organisationId, mediaVault, customAssetUrl, transformContext) : parsed.backgroundImage.src,
26939
27193
  width: bgWidth,
26940
27194
  height: bgHeight
26941
27195
  },
@@ -26959,11 +27213,12 @@ function convertGraphicGapMatchToLearnosity(inputXml, diagnostics, _lomTags, org
26959
27213
  if (parsed.stimulus) question.stimulus = transformAssetUrls(parsed.stimulus, {
26960
27214
  organisationId,
26961
27215
  mediaVault,
26962
- customAssetUrl
27216
+ customAssetUrl,
27217
+ ...transformContext
26963
27218
  });
26964
27219
  const item = {
26965
27220
  item: {
26966
- reference: generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile),
27221
+ reference: itemRef,
26967
27222
  title: parsed.title ?? void 0,
26968
27223
  definition: { widgets: [{
26969
27224
  reference: questionRef,
@@ -27253,35 +27508,38 @@ const readAssessmentItemDrawing = createAssessmentItemReader({
27253
27508
  /**
27254
27509
  * Build drawing stimulus from parsed QTI data
27255
27510
  */
27256
- function buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl) {
27511
+ function buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
27257
27512
  if (!parsed.stimulusText && !parsed.promptText) return;
27258
27513
  const stimulus = parsed.promptText || parsed.stimulusText || "";
27259
27514
  try {
27260
27515
  return transformAssetUrls(stimulus, {
27261
27516
  organisationId,
27262
27517
  mediaVault,
27263
- customAssetUrl
27518
+ customAssetUrl,
27519
+ ...assetTransformContext
27264
27520
  });
27265
- } catch {
27521
+ } catch (error) {
27522
+ if (isUnsafeQtiAssetHrefError(error)) throw error;
27266
27523
  return stimulus;
27267
27524
  }
27268
27525
  }
27269
27526
  /**
27270
27527
  * Transform a single image source URL
27271
27528
  */
27272
- function transformImageSource(imageSource, organisationId, mediaVault, customAssetUrl) {
27529
+ function transformImageSource(imageSource, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
27273
27530
  try {
27274
- return organisationId ? transformUrl(imageSource, organisationId, mediaVault, customAssetUrl) : imageSource;
27275
- } catch {
27531
+ return organisationId ? transformUrl(imageSource, organisationId, mediaVault, customAssetUrl, assetTransformContext) : imageSource;
27532
+ } catch (error) {
27533
+ if (isUnsafeQtiAssetHrefError(error)) throw error;
27276
27534
  return imageSource;
27277
27535
  }
27278
27536
  }
27279
27537
  /**
27280
27538
  * Build drawing image data from parsed QTI data
27281
27539
  */
27282
- function buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl) {
27540
+ function buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl, assetTransformContext) {
27283
27541
  if (!parsed.imageSource) return;
27284
- const image = { source: transformImageSource(parsed.imageSource, organisationId, mediaVault, customAssetUrl) };
27542
+ const image = { source: transformImageSource(parsed.imageSource, organisationId, mediaVault, customAssetUrl, assetTransformContext) };
27285
27543
  if (parsed.imageWidth) image.width = parsed.imageWidth;
27286
27544
  if (parsed.imageHeight) image.height = parsed.imageHeight;
27287
27545
  if (parsed.imageAlt) image.alt = parsed.imageAlt;
@@ -27290,21 +27548,27 @@ function buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl) {
27290
27548
  /**
27291
27549
  * Convert QTI drawingInteraction to Learnosity drawing question
27292
27550
  */
27293
- function convertDrawingToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
27551
+ function convertDrawingToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
27294
27552
  const parsed = readAssessmentItemDrawing(inputXml);
27295
27553
  diagnostics.push(...parsed.diagnostics);
27296
27554
  if (parsed.diagnostics.some((d) => d.level === "error")) return { diagnostics };
27297
- const itemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
27555
+ const generatedItemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
27556
+ const itemRef = assetTransformContext?.finalItemReference ?? parsed.identifier ?? generatedItemRef;
27557
+ const transformContext = {
27558
+ finalItemReference: itemRef,
27559
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
27560
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
27561
+ };
27298
27562
  const questionRef = md5hex(itemRef + (parsed.responseIdentifier ?? "drawing"));
27299
27563
  const questionData = { type: "drawing" };
27300
- const stimulus = buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl);
27564
+ const stimulus = buildDrawingStimulus(parsed, organisationId, mediaVault, customAssetUrl, transformContext);
27301
27565
  if (stimulus !== void 0) questionData.stimulus = stimulus;
27302
- const image = buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl);
27566
+ const image = buildDrawingImage(parsed, organisationId, mediaVault, customAssetUrl, transformContext);
27303
27567
  if (image) questionData.image = image;
27304
27568
  const content = `<span class="learnosity-response question-${questionRef}"></span>`;
27305
27569
  const item = {
27306
27570
  item: {
27307
- reference: parsed.identifier ?? itemRef,
27571
+ reference: itemRef,
27308
27572
  title: parsed.title ?? void 0,
27309
27573
  content,
27310
27574
  definition: { widgets: [{
@@ -27594,7 +27858,7 @@ function buildValidationValue(choices, correctPairs, diagnostics, sourceFile) {
27594
27858
  * This reflects the undirected-pair nature of associateInteraction: no choice is
27595
27859
  * inherently a "category" or a "draggable" — both sides of a pair are equivalent.
27596
27860
  */
27597
- function convertAssociationToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
27861
+ function convertAssociationToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
27598
27862
  const parsed = readAssessmentItemAssociation(inputXml);
27599
27863
  const updatedDiagnostics = addFileContextIfProvided(parsed.diagnostics, sourceFile);
27600
27864
  diagnostics.push(...updatedDiagnostics);
@@ -27602,17 +27866,24 @@ function convertAssociationToLearnosity(inputXml, diagnostics, lomTags, organisa
27602
27866
  if (!parsed.identifier || parsed.choices.length === 0) return { diagnostics };
27603
27867
  const validationValue = buildValidationValue(parsed.choices, parsed.correctPairs, diagnostics, sourceFile);
27604
27868
  if (hasErrors(diagnostics)) return { diagnostics };
27605
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
27869
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
27870
+ const transformContext = {
27871
+ finalItemReference: itemRef,
27872
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
27873
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
27874
+ };
27606
27875
  const questionRef = md5hex(itemRef);
27607
27876
  const stimulus = transformAssetUrls(parsed.stimulusText ? `<p>${parsed.stimulusText}</p>` : "", {
27608
27877
  organisationId,
27609
27878
  mediaVault,
27610
- customAssetUrl
27879
+ customAssetUrl,
27880
+ ...transformContext
27611
27881
  });
27612
27882
  const possibleResponses = parsed.choices.map((c) => transformAssetUrls(c.text, {
27613
27883
  organisationId,
27614
27884
  mediaVault,
27615
- customAssetUrl
27885
+ customAssetUrl,
27886
+ ...transformContext
27616
27887
  }));
27617
27888
  const pairCount = validationValue.length > 0 ? validationValue.length : Math.round(parsed.maxAssociations ?? parsed.choices.length / 2);
27618
27889
  const columnHeaders = Array.from({ length: pairCount }, (_, i) => `Pair ${i + 1}`);
@@ -28028,8 +28299,8 @@ function computeClosingTags(html) {
28028
28299
  * Converters with different parameter orders are wrapped to normalize the signature.
28029
28300
  */
28030
28301
  function getConverterMap() {
28031
- const wrapSourceFirst = (fn) => (xml, diag, tags, orgId, sf, mv, cau, irs, stimuli) => fn(xml, diag, tags, sf, orgId, mv, cau, irs, stimuli);
28032
- const hotspotConverter = (xml, diag, tags, orgId, sf, mv, cau, irs, _stimuli, fileAccess, packageRoot) => convertHotspotToLearnosity(xml, diag, tags, orgId, sf, mv, cau, irs, fileAccess, packageRoot);
28302
+ const wrapSourceFirst = (fn) => (xml, diag, tags, orgId, sf, mv, cau, irs, stimuli, assetTransformContext) => fn(xml, diag, tags, sf, orgId, mv, cau, irs, stimuli, assetTransformContext);
28303
+ const hotspotConverter = (xml, diag, tags, orgId, sf, mv, cau, irs, _stimuli, assetTransformContext, fileAccess, packageRoot) => convertHotspotToLearnosity(xml, diag, tags, orgId, sf, mv, cau, irs, fileAccess, packageRoot, assetTransformContext);
28033
28304
  return {
28034
28305
  choiceInteraction: wrapSourceFirst(convertMcqToLearnosity),
28035
28306
  textEntryInteraction: wrapSourceFirst(convertTextEntryToLearnosity),
@@ -28052,8 +28323,14 @@ const CONVERTER_MAP = getConverterMap();
28052
28323
  * Strategy: Call each individual converter for its interaction type,
28053
28324
  * then combine all questions and widgets into a single composite item
28054
28325
  */
28055
- function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot) {
28326
+ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, packageRoot, assetTransformContext) {
28056
28327
  const metadata = extractItemMetadata(inputXml);
28328
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(metadata.identifier ?? "mixed_item", itemReferenceSource, sourceFile);
28329
+ const transformContext = {
28330
+ finalItemReference: itemRef,
28331
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
28332
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
28333
+ };
28057
28334
  const { segments } = segmentItemBodyByInteractions(inputXml);
28058
28335
  const stimuliByType = /* @__PURE__ */ new Map();
28059
28336
  for (const segment of segments) {
@@ -28135,7 +28412,8 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28135
28412
  const template = normalizeFinalText(transformAssetUrls(rawTemplate, {
28136
28413
  organisationId,
28137
28414
  mediaVault,
28138
- customAssetUrl
28415
+ customAssetUrl,
28416
+ ...transformContext
28139
28417
  }));
28140
28418
  if (groupEntries.length === 1 && /{{response}}(?:<\/[^>]+>|\s)*$/.test(rawTemplate.trim())) {
28141
28419
  let stimulusRaw = rawTemplate.replace(/{{response}}(?:<\/[^>]+>|\s)*$/, "").trim();
@@ -28143,7 +28421,8 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28143
28421
  const stimulus = normalizeFinalText(transformAssetUrls(stimulusRaw, {
28144
28422
  organisationId,
28145
28423
  mediaVault,
28146
- customAssetUrl
28424
+ customAssetUrl,
28425
+ ...transformContext
28147
28426
  }));
28148
28427
  const entry = groupEntries[0];
28149
28428
  const allCorrectResponses = entry.correctResponses ?? (entry.correctResponse ? [entry.correctResponse] : []);
@@ -28269,7 +28548,7 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28269
28548
  continue;
28270
28549
  }
28271
28550
  const converter = CONVERTER_MAP[group.type];
28272
- if (converter) processResult(converter(inputXml, subDiagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, group.stimuli, fileAccess, packageRoot), subDiagnostics);
28551
+ if (converter) processResult(converter(inputXml, subDiagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, group.stimuli, transformContext, fileAccess, packageRoot), subDiagnostics);
28273
28552
  }
28274
28553
  if (allQuestions.length === 0) {
28275
28554
  diagnostics.push({
@@ -28292,9 +28571,16 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28292
28571
  passageContent = transformAssetUrls(rawContent, {
28293
28572
  organisationId,
28294
28573
  mediaVault,
28295
- customAssetUrl
28574
+ customAssetUrl,
28575
+ ...transformContext
28576
+ });
28577
+ } catch (error) {
28578
+ if (isUnsafeQtiAssetHrefError(error)) diagnostics.push({
28579
+ code: DiagnosticCode.QTI_ASSET_HREF_UNSAFE,
28580
+ level: "error",
28581
+ file: sourceFile ?? "passage",
28582
+ message: error.message
28296
28583
  });
28297
- } catch {
28298
28584
  passageContent = rawContent;
28299
28585
  }
28300
28586
  allFeatures.push({
@@ -28326,7 +28612,7 @@ function convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, or
28326
28612
  const content = `<div class="row"><div class="col-xs-12">${[...featureSpans, ...questionSpans].join("")}</div></div>`;
28327
28613
  const item = {
28328
28614
  item: {
28329
- reference: generateItemReference(metadata.identifier ?? "mixed_item", itemReferenceSource, sourceFile),
28615
+ reference: itemRef,
28330
28616
  title: metadata.title ?? void 0,
28331
28617
  content,
28332
28618
  definition: { widgets: allWidgets },
@@ -28372,8 +28658,13 @@ function resolvePassageObjects(html, sourceFile, resolvePassageFile) {
28372
28658
  /**
28373
28659
  * Convert passage-only item to Learnosity format with sharedpassage feature
28374
28660
  */
28375
- function convertPassageToLearnosity(parsed, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess) {
28376
- const itemRef = generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
28661
+ function convertPassageToLearnosity(parsed, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, fileAccess, assetTransformContext) {
28662
+ const itemRef = assetTransformContext?.finalItemReference ?? generateItemReference(parsed.identifier, itemReferenceSource, sourceFile);
28663
+ const transformContext = {
28664
+ finalItemReference: itemRef,
28665
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
28666
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
28667
+ };
28377
28668
  const featureRef = `passage-${md5hex(getPassageDataPath(parsed.content) ?? itemRef).substring(0, 8)}`;
28378
28669
  const resolvedContent = resolvePassageObjects(parsed.content, sourceFile, fileAccess?.resolvePassageFile.bind(fileAccess));
28379
28670
  let content;
@@ -28381,11 +28672,12 @@ function convertPassageToLearnosity(parsed, diagnostics, lomTags, organisationId
28381
28672
  content = transformAssetUrls(resolvedContent, {
28382
28673
  organisationId,
28383
28674
  mediaVault,
28384
- customAssetUrl
28675
+ customAssetUrl,
28676
+ ...transformContext
28385
28677
  });
28386
28678
  } catch (error) {
28387
28679
  diagnostics.push({
28388
- code: DiagnosticCode.LRN_SCHEMA_INVALID,
28680
+ code: isUnsafeQtiAssetHrefError(error) ? DiagnosticCode.QTI_ASSET_HREF_UNSAFE : DiagnosticCode.LRN_SCHEMA_INVALID,
28389
28681
  level: "error",
28390
28682
  file: sourceFile ?? "assessmentItem",
28391
28683
  message: error instanceof Error ? error.message : "Failed to transform asset URLs"
@@ -28775,20 +29067,28 @@ function readAssessmentItemUpload(inputXml) {
28775
29067
  * and the file limit from `maxChoices` (see readAssessmentItemUpload / the
28776
29068
  * serializer). fileupload questions are unscored, so there is no validation.
28777
29069
  */
28778
- function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource) {
29070
+ function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationId, sourceFile, mediaVault, customAssetUrl, itemReferenceSource, _stimulusOverride, assetTransformContext) {
28779
29071
  const parsed = readAssessmentItemUpload(inputXml);
28780
29072
  diagnostics.push(...parsed.diagnostics);
28781
29073
  if (parsed.diagnostics.some((d) => d.level === "error")) return { diagnostics };
28782
- const itemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
29074
+ const generatedItemRef = generateItemReference(parsed.identifier ?? "item", itemReferenceSource, sourceFile);
29075
+ const itemRef = assetTransformContext?.finalItemReference ?? parsed.identifier ?? generatedItemRef;
29076
+ const transformContext = {
29077
+ finalItemReference: itemRef,
29078
+ preserveAssetFilenames: assetTransformContext?.preserveAssetFilenames ?? false,
29079
+ sourceHrefBase: assetTransformContext?.sourceHrefBase
29080
+ };
28783
29081
  const questionRef = md5hex(itemRef + (parsed.responseIdentifier ?? "fileupload"));
28784
29082
  const questionData = { type: "fileupload" };
28785
29083
  if (parsed.stimulus) try {
28786
29084
  questionData.stimulus = transformAssetUrls(parsed.stimulus, {
28787
29085
  organisationId,
28788
29086
  mediaVault,
28789
- customAssetUrl
29087
+ customAssetUrl,
29088
+ ...transformContext
28790
29089
  });
28791
- } catch {
29090
+ } catch (error) {
29091
+ if (isUnsafeQtiAssetHrefError(error)) throw error;
28792
29092
  questionData.stimulus = parsed.stimulus;
28793
29093
  }
28794
29094
  for (const suffix of parsed.allowedFileTypes) questionData[`allow_${suffix}`] = true;
@@ -28796,7 +29096,7 @@ function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationI
28796
29096
  const content = `<span class="learnosity-response question-${questionRef}"></span>`;
28797
29097
  const item = {
28798
29098
  item: {
28799
- reference: parsed.identifier ?? itemRef,
29099
+ reference: itemRef,
28800
29100
  title: parsed.title ?? void 0,
28801
29101
  content,
28802
29102
  definition: { widgets: [{
@@ -28831,9 +29131,19 @@ function convertUploadToLearnosity(inputXml, diagnostics, lomTags, organisationI
28831
29131
  * - Rejects DOCTYPE / ENTITY declarations up-front (DTD not allowed).
28832
29132
  * - Uses streaming parsers for all interaction types.
28833
29133
  */
29134
+ function getAssetSourceHrefBase(opts) {
29135
+ if (opts.sourceHrefBase) return opts.sourceHrefBase;
29136
+ const source = opts.sourceFile ?? opts.inputPath;
29137
+ if (!source) return;
29138
+ const normalized = source.replaceAll("\\", "/");
29139
+ return normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized) || /^[A-Za-z][A-Za-z\d+.-]*:/.test(normalized) ? normalized.slice(normalized.lastIndexOf("/") + 1) : normalized;
29140
+ }
28834
29141
  /**
28835
29142
  * Supported interaction type names for counting
28836
29143
  */
29144
+ function isUnsafeAssetHrefError$1(error) {
29145
+ return error instanceof Error && (error.message.startsWith("Unsafe QTI asset href:") || error.message.startsWith("QTI asset href has no filename:"));
29146
+ }
28837
29147
  const INTERACTION_NAMES = [
28838
29148
  "choiceInteraction",
28839
29149
  "textEntryInteraction",
@@ -28899,19 +29209,71 @@ function countAllInteractions(xml) {
28899
29209
  };
28900
29210
  }
28901
29211
  const SINGLE_INTERACTION_CONVERTERS = /* @__PURE__ */ new Map([
28902
- ["choiceInteraction", (xml, diag, lom, opts, stim) => convertMcqToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim)],
28903
- ["textEntryInteraction", (xml, diag, lom, opts, stim) => convertTextEntryToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim)],
28904
- ["extendedTextInteraction", (xml, diag, lom, opts, stim) => convertExtendedTextToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim)],
28905
- ["inlineChoiceInteraction", (xml, diag, lom, opts) => convertInlineChoiceToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28906
- ["matchInteraction", (xml, diag, lom, opts) => convertMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28907
- ["gapMatchInteraction", (xml, diag, lom, opts) => convertGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28908
- ["orderInteraction", (xml, diag, lom, opts) => convertOrderToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28909
- ["hotspotInteraction", (xml, diag, lom, opts) => convertHotspotToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot)],
28910
- ["hottextInteraction", (xml, diag, lom, opts) => convertHottextToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28911
- ["graphicGapMatchInteraction", (xml, diag, lom, opts) => convertGraphicGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28912
- ["drawingInteraction", (xml, diag, lom, opts) => convertDrawingToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28913
- ["associateInteraction", (xml, diag, lom, opts) => convertAssociationToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)],
28914
- ["uploadInteraction", (xml, diag, lom, opts) => convertUploadToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource)]
29212
+ ["choiceInteraction", (xml, diag, lom, opts, stim) => convertMcqToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim, {
29213
+ finalItemReference: opts.finalItemReference,
29214
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29215
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29216
+ })],
29217
+ ["textEntryInteraction", (xml, diag, lom, opts, stim) => convertTextEntryToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim, {
29218
+ finalItemReference: opts.finalItemReference,
29219
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29220
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29221
+ })],
29222
+ ["extendedTextInteraction", (xml, diag, lom, opts, stim) => convertExtendedTextToLearnosity(xml, diag, lom, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, stim, {
29223
+ finalItemReference: opts.finalItemReference,
29224
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29225
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29226
+ })],
29227
+ ["inlineChoiceInteraction", (xml, diag, lom, opts) => convertInlineChoiceToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29228
+ finalItemReference: opts.finalItemReference,
29229
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29230
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29231
+ })],
29232
+ ["matchInteraction", (xml, diag, lom, opts) => convertMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29233
+ finalItemReference: opts.finalItemReference,
29234
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29235
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29236
+ })],
29237
+ ["gapMatchInteraction", (xml, diag, lom, opts) => convertGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29238
+ finalItemReference: opts.finalItemReference,
29239
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29240
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29241
+ })],
29242
+ ["orderInteraction", (xml, diag, lom, opts) => convertOrderToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29243
+ finalItemReference: opts.finalItemReference,
29244
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29245
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29246
+ })],
29247
+ ["hotspotInteraction", (xml, diag, lom, opts) => convertHotspotToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot, {
29248
+ finalItemReference: opts.finalItemReference,
29249
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29250
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29251
+ })],
29252
+ ["hottextInteraction", (xml, diag, lom, opts) => convertHottextToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29253
+ finalItemReference: opts.finalItemReference,
29254
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29255
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29256
+ })],
29257
+ ["graphicGapMatchInteraction", (xml, diag, lom, opts) => convertGraphicGapMatchToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29258
+ finalItemReference: opts.finalItemReference,
29259
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29260
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29261
+ })],
29262
+ ["drawingInteraction", (xml, diag, lom, opts) => convertDrawingToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29263
+ finalItemReference: opts.finalItemReference,
29264
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29265
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29266
+ })],
29267
+ ["associateInteraction", (xml, diag, lom, opts) => convertAssociationToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29268
+ finalItemReference: opts.finalItemReference,
29269
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29270
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29271
+ })],
29272
+ ["uploadInteraction", (xml, diag, lom, opts) => convertUploadToLearnosity(xml, diag, lom, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29273
+ finalItemReference: opts.finalItemReference,
29274
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29275
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29276
+ })]
28915
29277
  ]);
28916
29278
  /**
28917
29279
  * Dispatch to the appropriate single-interaction converter
@@ -28937,9 +29299,18 @@ function dispatchSingleInteractionConverter(interactionType, inputXml, count, di
28937
29299
  passageContent = transformAssetUrls(rawContent, {
28938
29300
  organisationId: opts.organisationId,
28939
29301
  mediaVault: opts.mediaVault,
28940
- customAssetUrl: opts.customAssetUrl
29302
+ customAssetUrl: opts.customAssetUrl,
29303
+ finalItemReference: opts.finalItemReference ?? result.item.item.reference,
29304
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29305
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29306
+ });
29307
+ } catch (error) {
29308
+ if (isUnsafeAssetHrefError$1(error)) diagnostics.push({
29309
+ code: DiagnosticCode.QTI_ASSET_HREF_UNSAFE,
29310
+ level: "error",
29311
+ file: opts.sourceFile ?? "passage",
29312
+ message: error.message
28941
29313
  });
28942
- } catch {
28943
29314
  passageContent = rawContent;
28944
29315
  }
28945
29316
  result.item.features = [...result.item.features, {
@@ -28987,8 +29358,16 @@ function handleNoInteractions(inputXml, diagnostics, allInteractions, lomTags, o
28987
29358
  }
28988
29359
  const passageResult = readAssessmentItemPassage(inputXml);
28989
29360
  diagnostics.push(...addFileContextIfProvided(passageResult.diagnostics, opts.sourceFile));
28990
- if (passageResult.data) return convertPassageToLearnosity(passageResult.data, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess);
28991
- const mcqResult = convertMcqToLearnosity(inputXml, diagnostics, lomTags, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource);
29361
+ if (passageResult.data) return convertPassageToLearnosity(passageResult.data, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, {
29362
+ finalItemReference: opts.finalItemReference,
29363
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29364
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29365
+ });
29366
+ const mcqResult = convertMcqToLearnosity(inputXml, diagnostics, lomTags, opts.sourceFile, opts.organisationId, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, void 0, {
29367
+ finalItemReference: opts.finalItemReference,
29368
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29369
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29370
+ });
28992
29371
  if (diagnostics.some((d) => d.code === DiagnosticCode.LRN_SCHEMA_INVALID)) return mcqResult;
28993
29372
  return { diagnostics };
28994
29373
  }
@@ -29034,14 +29413,18 @@ function convertQtiAssessmentItemToLearnosity(inputXml, opts = {}) {
29034
29413
  const { counts, allInteractions } = countAllInteractions(inputXml);
29035
29414
  const presentTypes = INTERACTION_NAMES.filter((name) => counts[name] > 0);
29036
29415
  if (presentTypes.reduce((sum, name) => sum + counts[name], 0) === 0) return handleNoInteractions(inputXml, diagnostics, allInteractions, lomTags, opts);
29037
- if (presentTypes.length > 1) return convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot);
29416
+ if (presentTypes.length > 1) return convertMixedInteractionsToLearnosity(inputXml, diagnostics, lomTags, opts.organisationId, opts.sourceFile, opts.mediaVault, opts.customAssetUrl, opts.itemReferenceSource, opts.fileAccess, opts.packageRoot, {
29417
+ finalItemReference: opts.finalItemReference,
29418
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29419
+ sourceHrefBase: getAssetSourceHrefBase(opts)
29420
+ });
29038
29421
  return dispatchSingleInteractionConverter(presentTypes[0], inputXml, counts[presentTypes[0]], diagnostics, lomTags, opts);
29039
29422
  } catch (error) {
29040
29423
  diagnostics.push({
29041
- code: DiagnosticCode.LRN_SCHEMA_INVALID,
29424
+ code: isUnsafeAssetHrefError$1(error) ? DiagnosticCode.QTI_ASSET_HREF_UNSAFE : DiagnosticCode.LRN_SCHEMA_INVALID,
29042
29425
  level: "error",
29043
- file: "root",
29044
- message: `Failed to parse QTI XML: ${error instanceof Error ? error.message : "Unknown error"}`
29426
+ file: opts.sourceFile ?? "root",
29427
+ message: isUnsafeAssetHrefError$1(error) ? error.message : `Failed to parse QTI XML: ${error instanceof Error ? error.message : "Unknown error"}`
29045
29428
  });
29046
29429
  return { diagnostics };
29047
29430
  }
@@ -29157,6 +29540,7 @@ function convertQtiToLearnosity(input, opts) {
29157
29540
  organisationId: opts.organisationId,
29158
29541
  mediaVault: opts.mediaVault,
29159
29542
  customAssetUrl: opts.customAssetUrl,
29543
+ preserveAssetFilenames: opts.preserveAssetFilenames ?? false,
29160
29544
  itemReferenceSource: opts.itemReferenceSource,
29161
29545
  fileAccess: opts.fileAccess
29162
29546
  });
@@ -30850,6 +31234,108 @@ function unzipToEntries(bytes, sourceLabel, options) {
30850
31234
  };
30851
31235
  }
30852
31236
  //#endregion
31237
+ //#region src/qti-to-learnosity/utils/assetFilenameRegistry.ts
31238
+ /**
31239
+ * Browser-safe registry for item-scoped QTI asset filenames.
31240
+ *
31241
+ * Filename selection belongs to asset identity, not package traversal. Keeping
31242
+ * both identity and filename indexes here lets URL and bundle seams validate
31243
+ * the same contract before either one can overwrite a physical asset.
31244
+ */
31245
+ var AssetFilenameConflictError = class extends Error {
31246
+ kind;
31247
+ mode;
31248
+ filename;
31249
+ existing;
31250
+ incoming;
31251
+ constructor(kind, mode, filename, existing, incoming) {
31252
+ const existingIdentity = existing.serializedIdentity;
31253
+ const incomingIdentity = incoming.serializedIdentity;
31254
+ 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}.`;
31255
+ super(message);
31256
+ this.name = "AssetFilenameConflictError";
31257
+ this.kind = kind;
31258
+ this.mode = mode;
31259
+ this.filename = filename;
31260
+ this.existing = existing;
31261
+ this.incoming = incoming;
31262
+ }
31263
+ };
31264
+ function bytesEqual(left, right) {
31265
+ if (left.length !== right.length) return false;
31266
+ for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
31267
+ return true;
31268
+ }
31269
+ function cloneBytes(bytes) {
31270
+ return new Uint8Array(bytes);
31271
+ }
31272
+ /**
31273
+ * Track selected asset names and their bytes for one conversion.
31274
+ *
31275
+ * Registering an equivalent identity repeatedly is idempotent when its bytes
31276
+ * agree. A filename can never silently change owners, and an identity can
31277
+ * never silently change bytes, in either hashed or preserve mode.
31278
+ */
31279
+ var AssetFilenameRegistry = class {
31280
+ preserveAssetFilenames;
31281
+ byIdentity = /* @__PURE__ */ new Map();
31282
+ byFilename = /* @__PURE__ */ new Map();
31283
+ constructor(preserveAssetFilenames = false) {
31284
+ this.preserveAssetFilenames = preserveAssetFilenames;
31285
+ }
31286
+ get mode() {
31287
+ return this.preserveAssetFilenames ? "preserve" : "hashed";
31288
+ }
31289
+ get size() {
31290
+ return this.byIdentity.size;
31291
+ }
31292
+ /**
31293
+ * Register an asset and return its selected filename and bytes.
31294
+ *
31295
+ * The input href is canonicalized before both indexes are consulted, so
31296
+ * equivalent directory and ZIP representations reuse one registration.
31297
+ */
31298
+ register(finalItemReference, qtiAssetHref, bytes) {
31299
+ const canonicalHref = canonicalizeQtiAssetHref(qtiAssetHref);
31300
+ const serializedIdentity = serializeQtiAssetIdentity(finalItemReference, canonicalHref);
31301
+ const filename = selectQtiAssetFilename(finalItemReference, canonicalHref, this.preserveAssetFilenames);
31302
+ const incoming = {
31303
+ finalItemReference,
31304
+ qtiAssetHref: canonicalHref,
31305
+ serializedIdentity,
31306
+ filename,
31307
+ bytes: cloneBytes(bytes)
31308
+ };
31309
+ const existingIdentity = this.byIdentity.get(serializedIdentity);
31310
+ if (existingIdentity) {
31311
+ if (!bytesEqual(existingIdentity.bytes, incoming.bytes)) throw new AssetFilenameConflictError("identity-bytes", this.mode, filename, existingIdentity, incoming);
31312
+ return existingIdentity;
31313
+ }
31314
+ const existingFilename = this.byFilename.get(filename);
31315
+ if (existingFilename) throw new AssetFilenameConflictError("filename-identity", this.mode, filename, existingFilename, incoming);
31316
+ this.byIdentity.set(serializedIdentity, incoming);
31317
+ this.byFilename.set(filename, incoming);
31318
+ return incoming;
31319
+ }
31320
+ /** Look up a previously registered canonical identity without registering it. */
31321
+ get(finalItemReference, qtiAssetHref) {
31322
+ return this.byIdentity.get(serializeQtiAssetIdentity(finalItemReference, qtiAssetHref));
31323
+ }
31324
+ /** Look up an asset by its selected bundle-relative filename. */
31325
+ getByFilename(filename) {
31326
+ return this.byFilename.get(filename);
31327
+ }
31328
+ /** Iterate registrations in deterministic registration order. */
31329
+ entries() {
31330
+ return this.byIdentity.values();
31331
+ }
31332
+ /** Remove all registrations so the registry can be reused for a new conversion. */
31333
+ clear() {
31334
+ this.byIdentity.clear();
31335
+ this.byFilename.clear();
31336
+ }
31337
+ };
31338
+ //#endregion
30853
31339
  //#region src/qti-to-learnosity/convertQtiPackageToLearnosityBundle.ts
30854
31340
  /**
30855
31341
  * QTI Content Package → Learnosity Bundle converter (v1)
@@ -30897,57 +31383,69 @@ function ensureFailedItemDiagnostic(itemDiagnostics, href) {
30897
31383
  }];
30898
31384
  }
30899
31385
  /**
30900
- * Normalize a forward-slash relative path (collapse `.`/`//`, resolve `..`).
30901
- * Pure replacement for `node:path`'s `normalize(...).split(sep).join('/')` on
30902
- * the forward-slash paths used as entry keys.
30903
- */
30904
- function normalizePosix(p) {
30905
- const parts = [];
30906
- for (const seg of p.split("/")) {
30907
- if (seg === "" || seg === ".") continue;
30908
- if (seg === "..") {
30909
- parts.pop();
30910
- continue;
30911
- }
30912
- parts.push(seg);
30913
- }
30914
- return parts.join("/");
30915
- }
30916
- /**
30917
31386
  * Normalize href path by removing leading ./ sequences
30918
31387
  * This ensures manifest hrefs like "./items/foo.xml" match entries stored as "items/foo.xml"
30919
31388
  */
30920
31389
  function normalizeHref(href) {
30921
31390
  return href.replace(/^(\.\/)+/, "");
30922
31391
  }
30923
- /**
30924
- * File extensions treated as copyable assets (images, audio, video, styles,
30925
- * fonts, etc.). Undeclared files with these extensions are copied to the bundle
30926
- * even if the manifest omits them.
30927
- */
30928
- const ASSET_EXTENSIONS = [
30929
- ".png",
30930
- ".jpg",
30931
- ".jpeg",
30932
- ".gif",
30933
- ".svg",
30934
- ".webp",
30935
- ".bmp",
30936
- ".ico",
30937
- ".mp3",
30938
- ".mp4",
30939
- ".wav",
30940
- ".ogg",
30941
- ".webm",
30942
- ".m4a",
30943
- ".css",
30944
- ".woff",
30945
- ".woff2",
30946
- ".ttf",
30947
- ".eot",
30948
- ".pdf",
30949
- ".json"
30950
- ];
31392
+ function readAssessmentItemIdentifier(inputXml, fallback) {
31393
+ let identifier = fallback;
31394
+ const parser = new import_saxes.SaxesParser({ xmlns: true });
31395
+ parser.on("opentag", (tag) => {
31396
+ if ((tag.local ?? tag.name) === "assessmentItem") identifier = getAttr$5(tag, "identifier") ?? fallback;
31397
+ });
31398
+ try {
31399
+ parser.write(inputXml).close();
31400
+ } catch {}
31401
+ return identifier;
31402
+ }
31403
+ function uniqueItemReference(baseReference, sourceHref, items) {
31404
+ if (!items.has(baseReference)) return baseReference;
31405
+ const readableCandidate = `${baseReference}_${normalizeHref(sourceHref).split("/").at(-1)?.replace(/\.xml$/i, "") ?? "item"}`;
31406
+ if (!items.has(readableCandidate)) return readableCandidate;
31407
+ const sourceDigest = md5hex(normalizeHref(sourceHref));
31408
+ let candidate = `${readableCandidate}_${sourceDigest}`;
31409
+ let suffix = 1;
31410
+ while (items.has(candidate)) {
31411
+ candidate = `${readableCandidate}_${sourceDigest}_${suffix}`;
31412
+ suffix += 1;
31413
+ }
31414
+ return candidate;
31415
+ }
31416
+ function isUnsafeAssetHrefError(error) {
31417
+ return error instanceof Error && (error.message.startsWith("Unsafe QTI asset href:") || error.message.startsWith("QTI asset href has no filename:"));
31418
+ }
31419
+ function hasAssetNamingDiagnostic(diagnostics) {
31420
+ 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);
31421
+ }
31422
+ /**
31423
+ * Resolve a local QTI reference exactly as asset URL transformation does.
31424
+ * References without a leading dot segment are already package-relative;
31425
+ * `./` and `../` references are resolved from the item source directory.
31426
+ */
31427
+ function resolvePackageAssetHref(href, sourceHrefBase) {
31428
+ const cleanHref = href.split(/[?#]/, 1)[0].replaceAll("\\", "/");
31429
+ if (!cleanHref || /^https?:\/\//i.test(cleanHref) || cleanHref.startsWith("//") || cleanHref.startsWith("data:") || cleanHref.includes("assets.learnosity.com") || cleanHref.includes("media-vault.learnosity.com")) return;
31430
+ if (!(/^\.\.?\//.test(cleanHref) || !cleanHref.includes("/"))) return canonicalizeQtiAssetHref(cleanHref);
31431
+ const baseHref = canonicalizeQtiAssetHref(sourceHrefBase);
31432
+ return canonicalizeQtiAssetHref(`${baseHref.slice(0, baseHref.lastIndexOf("/") + 1)}${cleanHref}`);
31433
+ }
31434
+ /** Extract local asset-bearing attributes from item XML or resolved passage HTML. */
31435
+ function extractAssetHrefs(content) {
31436
+ const hrefs = [];
31437
+ const seen = /* @__PURE__ */ new Set();
31438
+ const attributePattern = /\b(?:src|data|href)\s*=\s*["']([^"']+)["']/gi;
31439
+ let match;
31440
+ while ((match = attributePattern.exec(content)) !== null) if (!seen.has(match[1])) {
31441
+ seen.add(match[1]);
31442
+ hrefs.push(match[1]);
31443
+ }
31444
+ return hrefs;
31445
+ }
31446
+ function isCopyableAssetPath(path) {
31447
+ return isSupportedQtiAssetPath(path);
31448
+ }
30951
31449
  /**
30952
31450
  * Merge two tag objects, combining tag values for each tag type
30953
31451
  * Source tags are merged into base tags, avoiding duplicates
@@ -31018,7 +31516,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31018
31516
  if (needed.has(normalized)) return true;
31019
31517
  const lower = normalized.toLowerCase();
31020
31518
  if (lower.endsWith(".html")) return false;
31021
- return lower.endsWith(".xml") || ASSET_EXTENSIONS.some((ext) => lower.endsWith(ext));
31519
+ return lower.endsWith(".xml") || isSupportedQtiAssetPath(normalized);
31022
31520
  };
31023
31521
  }
31024
31522
  const unzipped = unzipToEntries(input.zipBytes, label, filter ? { filter } : void 0);
@@ -31053,6 +31551,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31053
31551
  }
31054
31552
  const items = /* @__PURE__ */ new Map();
31055
31553
  const itemFilenames = /* @__PURE__ */ new Map();
31554
+ const itemAssetContexts = [];
31056
31555
  const qtiRefToMd5Refs = /* @__PURE__ */ new Map();
31057
31556
  const convertedSourceFiles = [];
31058
31557
  const failedSourceFiles = [];
@@ -31115,23 +31614,33 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31115
31614
  }
31116
31615
  const itemXml = decodeUtf8(itemEntry.data);
31117
31616
  const itemFilePath = opts?.sourceDir ? posixJoin(opts.sourceDir, itemResource.href) : itemResource.href;
31617
+ const baseItemReference = generateItemReference(readAssessmentItemIdentifier(itemXml, itemResource.identifier), opts?.itemReferenceSource, itemFilePath);
31618
+ const finalItemReference = uniqueItemReference(baseItemReference, itemResource.href, items);
31118
31619
  const itemResult = convertQtiAssessmentItemToLearnosity(itemXml, {
31119
31620
  inputPath: itemFilePath,
31120
31621
  sourceFile: itemFilePath,
31121
31622
  organisationId: opts?.organisationId,
31122
31623
  mediaVault: opts?.mediaVault,
31123
31624
  customAssetUrl: opts?.customAssetUrl,
31625
+ preserveAssetFilenames: opts?.preserveAssetFilenames ?? false,
31124
31626
  itemReferenceSource: opts?.itemReferenceSource,
31125
31627
  fileAccess: opts?.fileAccess,
31126
- packageRoot: opts?.sourceDir
31628
+ packageRoot: opts?.sourceDir,
31629
+ finalItemReference,
31630
+ sourceHrefBase: itemResource.href
31127
31631
  });
31128
31632
  diagnostics.push(...itemResult.diagnostics);
31129
31633
  if (itemResult.item) {
31130
31634
  let md5Ref = itemResult.item.item.reference;
31635
+ if (finalItemReference !== baseItemReference) diagnostics.push({
31636
+ code: DiagnosticCode.QTI_PACKAGE_DUPLICATE_IDENTIFIER,
31637
+ level: "warning",
31638
+ file: itemResource.href,
31639
+ message: `Duplicate item reference "${finalItemReference}" disambiguated from "${baseItemReference}" (source: ${itemResource.href})`
31640
+ });
31131
31641
  if (items.has(md5Ref)) {
31132
- const hrefParts = itemResource.href.split("/");
31133
- const filename = hrefParts[hrefParts.length - 1].replace(/\.xml$/i, "");
31134
- md5Ref = `${md5Ref}_${filename}`;
31642
+ const originalRef = md5Ref;
31643
+ md5Ref = uniqueItemReference(finalItemReference, itemResource.href, items);
31135
31644
  itemResult.item.item.reference = md5Ref;
31136
31645
  for (const question of itemResult.item.questions) {
31137
31646
  const oldRef = question.reference;
@@ -31145,7 +31654,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31145
31654
  code: DiagnosticCode.QTI_PACKAGE_DUPLICATE_IDENTIFIER,
31146
31655
  level: "warning",
31147
31656
  file: itemResource.href,
31148
- message: `Duplicate item reference "${itemResult.item.item.reference}" disambiguated from "${md5Ref.replace(`_${filename}`, "")}" (source: ${itemResource.href})`
31657
+ message: `Duplicate item reference "${md5Ref}" disambiguated from "${originalRef}" (source: ${itemResource.href})`
31149
31658
  });
31150
31659
  }
31151
31660
  if (itemResource.metadataXml) try {
@@ -31165,9 +31674,15 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31165
31674
  });
31166
31675
  }
31167
31676
  items.set(md5Ref, itemResult.item);
31677
+ itemAssetContexts.push({
31678
+ finalItemReference: md5Ref,
31679
+ sourceHref: itemResource.href,
31680
+ sourceFile: itemFilePath,
31681
+ inputXml: itemXml
31682
+ });
31168
31683
  const filenameSource = opts?.itemFilenameSource;
31169
31684
  if (filenameSource && filenameSource !== (opts.itemReferenceSource ?? "sourceFilename")) {
31170
- const filename = generateItemReference(itemXml.match(/<assessmentItem[^>]+identifier="([^"]+)"/)?.[1] ?? md5Ref, filenameSource, itemFilePath);
31685
+ const filename = generateItemReference(readAssessmentItemIdentifier(itemXml, md5Ref), filenameSource, itemFilePath);
31171
31686
  itemFilenames.set(md5Ref, filename);
31172
31687
  }
31173
31688
  if (!qtiRefToMd5Refs.has(itemResource.identifier)) qtiRefToMd5Refs.set(itemResource.identifier, []);
@@ -31178,6 +31693,12 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31178
31693
  diagnostics.push(...ensureFailedItemDiagnostic(itemResult.diagnostics, itemResource.href));
31179
31694
  }
31180
31695
  }
31696
+ if (hasAssetNamingDiagnostic(diagnostics)) return {
31697
+ diagnostics,
31698
+ convertedSourceFiles,
31699
+ failedSourceFiles,
31700
+ convertedActivityFiles
31701
+ };
31181
31702
  if (items.size === 0 && itemResourcesToConvert.length > 0) {
31182
31703
  diagnostics.push({
31183
31704
  code: DiagnosticCode.QTI_PACKAGE_ITEM_NOT_FOUND,
@@ -31282,24 +31803,39 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31282
31803
  activitiesManifest[activityId] = { items: activityItems };
31283
31804
  }
31284
31805
  const assets = /* @__PURE__ */ new Map();
31285
- const copiedPaths = /* @__PURE__ */ new Set();
31286
- for (const resource of resources) if (resource.type === "webcontent" || resource.type.includes("associated")) {
31287
- if (resource.href.toLowerCase().endsWith(".html")) continue;
31288
- const assetEntry = entries.get(resource.href);
31289
- if (assetEntry) {
31290
- const normalizedPath = normalizePosix(resource.href);
31291
- assets.set(normalizedPath, new Uint8Array(assetEntry.data));
31292
- copiedPaths.add(resource.href);
31293
- }
31806
+ const assetCandidates = /* @__PURE__ */ new Map();
31807
+ const addAssetCandidate = (href, data) => {
31808
+ try {
31809
+ const canonicalHref = canonicalizeQtiAssetHref(href);
31810
+ if (isCopyableAssetPath(canonicalHref)) assetCandidates.set(canonicalHref, new Uint8Array(data));
31811
+ } catch {}
31812
+ };
31813
+ for (const resource of resources) if (resource.type === "webcontent" || resource.type.includes("associated")) for (const href of [resource.href, ...resource.files ?? []]) {
31814
+ const assetEntry = entries.get(normalizeHref(href));
31815
+ if (assetEntry) addAssetCandidate(href, assetEntry.data);
31294
31816
  }
31295
31817
  for (const [path, entry] of entries) {
31296
- if (copiedPaths.has(path)) continue;
31297
- if (path === "imsmanifest.xml" || path.endsWith(".xml")) continue;
31298
- const lowerPath = path.toLowerCase();
31299
- if (ASSET_EXTENSIONS.some((ext) => lowerPath.endsWith(ext))) {
31300
- const normalizedPath = normalizePosix(path);
31301
- assets.set(normalizedPath, new Uint8Array(entry.data));
31302
- copiedPaths.add(path);
31818
+ if (path === "imsmanifest.xml" || path.toLowerCase().endsWith(".xml")) continue;
31819
+ addAssetCandidate(path, entry.data);
31820
+ }
31821
+ const registry = new AssetFilenameRegistry(opts?.preserveAssetFilenames ?? false);
31822
+ const registerContextAsset = (context, rawHref, sourceHrefBase) => {
31823
+ const canonicalHref = resolvePackageAssetHref(rawHref, sourceHrefBase);
31824
+ if (!canonicalHref) return;
31825
+ const bytes = assetCandidates.get(canonicalHref);
31826
+ if (!bytes) return;
31827
+ const registration = registry.register(context.finalItemReference, canonicalHref, bytes);
31828
+ assets.set(registration.filename, registration.bytes);
31829
+ };
31830
+ for (const context of itemAssetContexts) {
31831
+ for (const rawHref of extractAssetHrefs(context.inputXml)) registerContextAsset(context, rawHref, context.sourceHref);
31832
+ for (const passagePath of getAllPassageDataPaths(context.inputXml)) {
31833
+ const passageContent = opts?.fileAccess?.resolvePassageFile(passagePath, context.sourceFile);
31834
+ const passageHref = resolvePackageAssetHref(passagePath, context.sourceHref);
31835
+ const entryContent = passageHref ? entries.get(passageHref) : void 0;
31836
+ const resolvedPassageContent = passageContent ?? (entryContent ? decodeUtf8(entryContent.data) : void 0);
31837
+ if (!resolvedPassageContent) continue;
31838
+ for (const rawHref of extractAssetHrefs(resolvedPassageContent)) registerContextAsset(context, rawHref, context.sourceHref);
31303
31839
  }
31304
31840
  }
31305
31841
  return {
@@ -31312,6 +31848,7 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31312
31848
  organisationId: opts?.organisationId,
31313
31849
  mediaVault: opts?.mediaVault ?? false,
31314
31850
  customAssetUrl: opts?.customAssetUrl,
31851
+ preserveAssetFilenames: opts?.preserveAssetFilenames ?? false,
31315
31852
  itemReferenceSource: opts?.itemReferenceSource ?? "sourceFilename"
31316
31853
  }
31317
31854
  },
@@ -31333,7 +31870,25 @@ function convertQtiPackageToLearnosityBundle(input, opts) {
31333
31870
  convertedActivityFiles
31334
31871
  };
31335
31872
  } catch (error) {
31336
- diagnostics.push({
31873
+ if (error instanceof AssetFilenameConflictError) diagnostics.push({
31874
+ code: error.kind === "identity-bytes" ? DiagnosticCode.QTI_ASSET_IDENTITY_BYTES_CONFLICT : DiagnosticCode.QTI_ASSET_FILENAME_CONFLICT,
31875
+ level: "error",
31876
+ file: opts?.sourceLabel ?? opts?.sourceDir ?? "package",
31877
+ message: error.message,
31878
+ context: {
31879
+ mode: error.mode,
31880
+ filename: error.filename,
31881
+ existingIdentity: error.existing.serializedIdentity,
31882
+ incomingIdentity: error.incoming.serializedIdentity
31883
+ }
31884
+ });
31885
+ else if (isUnsafeAssetHrefError(error)) diagnostics.push({
31886
+ code: DiagnosticCode.QTI_ASSET_HREF_UNSAFE,
31887
+ level: "error",
31888
+ file: opts?.sourceLabel ?? opts?.sourceDir ?? "package",
31889
+ message: error.message
31890
+ });
31891
+ else diagnostics.push({
31337
31892
  code: DiagnosticCode.LRN_SCHEMA_INVALID,
31338
31893
  level: "error",
31339
31894
  file: "root",