@financica/ubl 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,20 +1,5 @@
1
+ import { n as UblParseError, t as UblBuildError } from "./errors-C9YYJ1xR.js";
1
2
  import { DOMParser } from "@xmldom/xmldom";
2
- //#region src/errors.ts
3
- /**
4
- * Thrown by the parse side of this package when input is broken: malformed
5
- * XML, or a UBL document missing an element EN 16931 makes mandatory. A parser
6
- * returns `null` instead when the input is well-formed but not the document
7
- * type it parses.
8
- */
9
- var UblParseError = class extends Error {
10
- cause;
11
- constructor(message, options) {
12
- super(message);
13
- this.name = "UblParseError";
14
- if (options && "cause" in options) this.cause = options.cause;
15
- }
16
- };
17
- //#endregion
18
3
  //#region src/xml-dom.ts
19
4
  const CBC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
20
5
  const CAC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
@@ -154,39 +139,66 @@ function parseParty(root, role) {
154
139
  const endpointEl = party.getElementsByTagNameNS(CBC_NS, "EndpointID")[0];
155
140
  const partyIdentifications = parsePartyIdentifications(party);
156
141
  const companyIdEl = legalEntity ? legalEntity.getElementsByTagNameNS(CBC_NS, "CompanyID")[0] : null;
142
+ const endpointValue = trimmed$1(endpointEl?.textContent);
143
+ const companyIdValue = companyIdEl ? trimmed$1(companyIdEl.textContent) : partyId ? cbcText$1(partyId, "ID") : void 0;
157
144
  return {
158
145
  name: partyName ? cbcText$1(partyName, "Name") : void 0,
159
146
  registrationName: legalEntity ? cbcText$1(legalEntity, "RegistrationName") : void 0,
160
147
  companyLegalForm: legalEntity ? cbcText$1(legalEntity, "CompanyLegalForm") : void 0,
161
148
  vatId: taxScheme ? cbcText$1(taxScheme, "CompanyID") : void 0,
162
149
  taxSchemeId: parseTaxSchemeId(taxScheme),
163
- companyId: companyIdEl ? trimmed$1(companyIdEl.textContent) : partyId ? cbcText$1(partyId, "ID") : void 0,
164
- companyIdSchemeId: attribute(companyIdEl, "schemeID"),
165
- endpointId: trimmed$1(endpointEl?.textContent),
166
- endpointSchemeId: attribute(endpointEl, "schemeID"),
150
+ companyId: companyIdValue !== void 0 ? {
151
+ value: companyIdValue,
152
+ scheme: attribute(companyIdEl, "schemeID")
153
+ } : void 0,
154
+ endpoint: endpointValue !== void 0 ? {
155
+ value: endpointValue,
156
+ scheme: attribute(endpointEl, "schemeID")
157
+ } : void 0,
167
158
  partyIdentifications: partyIdentifications.length > 0 ? partyIdentifications : void 0,
168
159
  address: parseAddress(party),
169
160
  contact: parseContact(party)
170
161
  };
171
162
  }
163
+ /**
164
+ * `cac:TaxCategory` / `cac:ClassifiedTaxCategory`. Emitted whenever the
165
+ * element states anything; `percentFallback` covers the E-FFF habit of putting
166
+ * `cbc:Percent` on the subtotal instead of inside the category.
167
+ */
168
+ function parseTaxCategory(cat, percentFallback) {
169
+ const percentFromParent = percentFallback ? cbcDirectNumber(percentFallback, "Percent") : void 0;
170
+ if (!cat) return percentFromParent !== void 0 ? { percent: percentFromParent } : void 0;
171
+ const category = {
172
+ id: cbcText$1(cat, "ID"),
173
+ percent: cbcNumber(cat, "Percent") ?? percentFromParent,
174
+ schemeId: parseTaxSchemeId(cat),
175
+ exemptionReason: cbcText$1(cat, "TaxExemptionReason"),
176
+ exemptionReasonCode: cbcText$1(cat, "TaxExemptionReasonCode")
177
+ };
178
+ return Object.values(category).some((value) => value !== void 0) ? category : void 0;
179
+ }
172
180
  function parseTaxSubtotal(sub) {
173
- const cat = cacElement$1(sub, "TaxCategory");
174
181
  return {
175
182
  taxableAmount: cbcNumber(sub, "TaxableAmount"),
176
183
  taxAmount: cbcNumber(sub, "TaxAmount"),
177
- taxPercent: (cat ? cbcNumber(cat, "Percent") : void 0) ?? cbcNumber(sub, "Percent"),
178
- taxCategoryId: cat ? cbcText$1(cat, "ID") : void 0,
179
- taxSchemeId: parseTaxSchemeId(cat),
180
- taxExemptionReason: cat ? cbcText$1(cat, "TaxExemptionReason") : void 0
184
+ category: parseTaxCategory(cacElement$1(sub, "TaxCategory"), sub)
181
185
  };
182
186
  }
183
187
  function parseTaxSubtotalsFromTaxTotal(taxTotal) {
184
188
  return cacDirectElements(taxTotal, "TaxSubtotal").map(parseTaxSubtotal);
185
189
  }
186
- function parseTaxSubtotals(root) {
190
+ /**
191
+ * `cac:TaxTotal` (BG-22). BT-110 is read from the first `cac:TaxTotal` as
192
+ * stated, never summed from the subtotals; the subtotals of every `TaxTotal`
193
+ * (a second one carries the accounting-currency figure) are concatenated.
194
+ */
195
+ function parseTaxTotal(root) {
187
196
  const taxTotals = cacDirectElements(root, "TaxTotal");
188
- if (taxTotals.length === 0) return [];
189
- return taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal);
197
+ const first = taxTotals[0];
198
+ return {
199
+ taxAmount: first ? cbcDirectNumber(first, "TaxAmount") : void 0,
200
+ subtotals: taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal)
201
+ };
190
202
  }
191
203
  function parseAllowanceCharge(charge) {
192
204
  const taxCategory = cacElement$1(charge, "TaxCategory");
@@ -198,21 +210,30 @@ function parseAllowanceCharge(charge) {
198
210
  multiplierFactorNumeric: cbcDirectNumber(charge, "MultiplierFactorNumeric"),
199
211
  reason: cbcText$1(charge, "AllowanceChargeReason"),
200
212
  reasonCode: cbcText$1(charge, "AllowanceChargeReasonCode"),
201
- taxPercent: taxCategory ? cbcNumber(taxCategory, "Percent") : void 0,
202
- taxCategoryId: taxCategory ? cbcText$1(taxCategory, "ID") : void 0,
203
- taxSchemeId: parseTaxSchemeId(taxCategory)
213
+ taxCategory: parseTaxCategory(taxCategory)
204
214
  };
205
215
  }
206
216
  function parseAllowanceCharges(parent) {
207
217
  return cacDirectElements(parent, "AllowanceCharge").map(parseAllowanceCharge);
208
218
  }
219
+ function mergeTaxCategories(preferred, fallback) {
220
+ if (!preferred) return fallback;
221
+ if (!fallback) return preferred;
222
+ return {
223
+ id: preferred.id ?? fallback.id,
224
+ percent: preferred.percent ?? fallback.percent,
225
+ schemeId: preferred.schemeId ?? fallback.schemeId,
226
+ exemptionReason: preferred.exemptionReason ?? fallback.exemptionReason,
227
+ exemptionReasonCode: preferred.exemptionReasonCode ?? fallback.exemptionReasonCode
228
+ };
229
+ }
209
230
  function parseLines(root, isCreditNote) {
210
231
  const qtyTag = isCreditNote ? "CreditedQuantity" : "InvoicedQuantity";
211
232
  const lineTag = isCreditNote ? "CreditNoteLine" : "InvoiceLine";
212
233
  return cacElements(root, lineTag).map((line) => {
213
234
  const item = cacElement$1(line, "Item");
214
235
  const price = cacElement$1(line, "Price");
215
- const taxCategory = item ? cacElement$1(item, "ClassifiedTaxCategory") : null;
236
+ const classifiedCategory = parseTaxCategory(item ? cacElement$1(item, "ClassifiedTaxCategory") : null);
216
237
  const sellersId = item ? cacElement$1(item, "SellersItemIdentification") : null;
217
238
  const buyersId = item ? cacElement$1(item, "BuyersItemIdentification") : null;
218
239
  const qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];
@@ -221,7 +242,9 @@ function parseLines(root, isCreditNote) {
221
242
  const lineTaxSubtotals = lineTaxTotal ? parseTaxSubtotalsFromTaxTotal(lineTaxTotal) : [];
222
243
  const taxAmountFromSubtotals = lineTaxSubtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0);
223
244
  const taxAmountFromLineTotal = lineTaxTotal ? cbcDirectNumber(lineTaxTotal, "TaxAmount") : void 0;
224
- const taxPercent = lineTaxSubtotals[0]?.taxPercent ?? (taxCategory ? cbcNumber(taxCategory, "Percent") : void 0);
245
+ const subtotalCategory = lineTaxSubtotals[0]?.category;
246
+ const taxCategory = mergeTaxCategories(subtotalCategory, classifiedCategory);
247
+ const taxPercent = taxCategory?.percent;
225
248
  const computedTaxAmount = taxPercent !== void 0 && lineExtensionAmount !== void 0 ? Number((lineExtensionAmount * taxPercent / 100).toFixed(2)) : void 0;
226
249
  const lineAllowanceCharges = parseAllowanceCharges(line);
227
250
  const priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];
@@ -247,10 +270,9 @@ function parseLines(root, isCreditNote) {
247
270
  unitCode: attribute(qtyEl, "unitCode"),
248
271
  unitPrice,
249
272
  lineExtensionAmount,
250
- taxPercent,
273
+ baseQuantity: priceBaseQuantity,
274
+ taxCategory,
251
275
  taxAmount: taxAmountFromLineTotal ?? (lineTaxSubtotals.length > 0 ? taxAmountFromSubtotals : computedTaxAmount),
252
- taxCategoryId: lineTaxSubtotals[0]?.taxCategoryId ?? (taxCategory ? cbcText$1(taxCategory, "ID") : void 0),
253
- taxSchemeId: lineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),
254
276
  taxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : void 0,
255
277
  allowanceCharges: allowanceCharges.length > 0 ? allowanceCharges : void 0,
256
278
  discountAmount: discountAmount > 0 ? discountAmount : void 0,
@@ -455,7 +477,7 @@ function parseUblInvoice(xml) {
455
477
  buyer: parseParty(root, "AccountingCustomerParty"),
456
478
  delivery: parseDelivery(root),
457
479
  lines: parseLines(root, isCreditNote),
458
- taxSubtotals: parseTaxSubtotals(root),
480
+ taxTotal: parseTaxTotal(root),
459
481
  monetaryTotal: parseMonetaryTotal(root),
460
482
  paymentMeansList,
461
483
  paymentMeans: paymentMeansList?.[0],
@@ -685,9 +707,9 @@ const sanitizeAllowanceCharges = (charges) => (charges ?? []).map((charge) => ({
685
707
  multiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),
686
708
  reason: normalizeText(charge.reason),
687
709
  reason_code: normalizeText(charge.reasonCode),
688
- tax_percent: toNumberOrNull(charge.taxPercent),
689
- tax_category_id: normalizeText(charge.taxCategoryId),
690
- tax_scheme_id: normalizeText(charge.taxSchemeId)
710
+ tax_percent: toNumberOrNull(charge.taxCategory?.percent),
711
+ tax_category_id: normalizeText(charge.taxCategory?.id),
712
+ tax_scheme_id: normalizeText(charge.taxCategory?.schemeId)
691
713
  }));
692
714
  const sanitizeRawUbl = (ubl) => ({
693
715
  ...ubl,
@@ -695,8 +717,9 @@ const sanitizeRawUbl = (ubl) => ({
695
717
  documentReferences: ubl.documentReferences ?? []
696
718
  });
697
719
  const sumTaxTotal = (ubl) => {
698
- const subtotalSum = ubl.taxSubtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0);
699
- if (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) return subtotalSum;
720
+ const { subtotals } = ubl.taxTotal;
721
+ const subtotalSum = subtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0);
722
+ if (subtotals.length > 0 && Number.isFinite(subtotalSum)) return subtotalSum;
700
723
  const { taxInclusiveAmount, taxExclusiveAmount } = ubl.monetaryTotal;
701
724
  if (taxInclusiveAmount === void 0 || taxExclusiveAmount === void 0) return null;
702
725
  return taxInclusiveAmount - taxExclusiveAmount;
@@ -743,7 +766,7 @@ const normalizeUblResponse = (xml, documentId) => {
743
766
  unit_price: toNumberOrNull(line.unitPrice),
744
767
  amount: toNumberOrNull(line.lineExtensionAmount),
745
768
  tax_amount: toNumberOrNull(line.taxAmount),
746
- tax_rate: toNumberOrNull(line.taxPercent),
769
+ tax_rate: toNumberOrNull(line.taxCategory?.percent),
747
770
  product_code: normalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),
748
771
  discount_amount: toNumberOrNull(line.discountAmount),
749
772
  period_start: parseDate(line.invoicePeriod?.startDate),
@@ -753,8 +776,8 @@ const normalizeUblResponse = (xml, documentId) => {
753
776
  item_name: normalizeText(line.itemName),
754
777
  sellers_item_id: normalizeText(line.sellersItemId),
755
778
  buyers_item_id: normalizeText(line.buyersItemId),
756
- tax_category_id: normalizeText(line.taxCategoryId),
757
- tax_scheme_id: normalizeText(line.taxSchemeId),
779
+ tax_category_id: normalizeText(line.taxCategory?.id),
780
+ tax_scheme_id: normalizeText(line.taxCategory?.schemeId),
758
781
  tax_subtotals: line.taxSubtotals ?? [],
759
782
  allowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),
760
783
  charge_amount: toNumberOrNull(line.chargeAmount),
@@ -791,14 +814,14 @@ const normalizeUblResponse = (xml, documentId) => {
791
814
  supplier: {
792
815
  name: normalizeText(ubl.seller.name) ?? normalizeText(ubl.seller.registrationName),
793
816
  address: supplierAddress,
794
- tax_id: normalizeText(ubl.seller.vatId) ?? normalizeText(ubl.seller.companyId),
817
+ tax_id: normalizeText(ubl.seller.vatId) ?? normalizeText(ubl.seller.companyId?.value),
795
818
  iban: normalizeText(ubl.paymentMeans?.iban),
796
819
  bic: normalizeText(ubl.paymentMeans?.bic)
797
820
  },
798
821
  receiver: {
799
822
  name: normalizeText(ubl.buyer.name) ?? normalizeText(ubl.buyer.registrationName),
800
823
  address: receiverAddress,
801
- tax_id: normalizeText(ubl.buyer.vatId) ?? normalizeText(ubl.buyer.companyId)
824
+ tax_id: normalizeText(ubl.buyer.vatId) ?? normalizeText(ubl.buyer.companyId?.value)
802
825
  },
803
826
  extra: {
804
827
  document_type: ubl.documentType,
@@ -824,11 +847,11 @@ const normalizeUblResponse = (xml, documentId) => {
824
847
  address: addressToStructured(ubl.delivery.address)
825
848
  } : null,
826
849
  supplier: {
827
- endpoint_id: normalizeText(ubl.seller.endpointId),
828
- endpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),
850
+ endpoint_id: normalizeText(ubl.seller.endpoint?.value),
851
+ endpoint_scheme_id: normalizeText(ubl.seller.endpoint?.scheme),
829
852
  registration_name: normalizeText(ubl.seller.registrationName),
830
853
  company_legal_form: normalizeText(ubl.seller.companyLegalForm),
831
- company_id_scheme_id: normalizeText(ubl.seller.companyIdSchemeId),
854
+ company_id_scheme_id: normalizeText(ubl.seller.companyId?.scheme),
832
855
  tax_scheme_id: normalizeText(ubl.seller.taxSchemeId),
833
856
  party_identifications: ubl.seller.partyIdentifications ?? [],
834
857
  contact_name: normalizeText(ubl.seller.contact?.name),
@@ -836,11 +859,11 @@ const normalizeUblResponse = (xml, documentId) => {
836
859
  contact_email: normalizeText(ubl.seller.contact?.email)
837
860
  },
838
861
  receiver: {
839
- endpoint_id: normalizeText(ubl.buyer.endpointId),
840
- endpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),
862
+ endpoint_id: normalizeText(ubl.buyer.endpoint?.value),
863
+ endpoint_scheme_id: normalizeText(ubl.buyer.endpoint?.scheme),
841
864
  registration_name: normalizeText(ubl.buyer.registrationName),
842
865
  company_legal_form: normalizeText(ubl.buyer.companyLegalForm),
843
- company_id_scheme_id: normalizeText(ubl.buyer.companyIdSchemeId),
866
+ company_id_scheme_id: normalizeText(ubl.buyer.companyId?.scheme),
844
867
  tax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),
845
868
  party_identifications: ubl.buyer.partyIdentifications ?? [],
846
869
  contact_name: normalizeText(ubl.buyer.contact?.name),
@@ -849,7 +872,7 @@ const normalizeUblResponse = (xml, documentId) => {
849
872
  },
850
873
  supplier_address_structured: supplierAddressStructured,
851
874
  receiver_address_structured: receiverAddressStructured,
852
- tax_subtotals: ubl.taxSubtotals,
875
+ tax_subtotals: ubl.taxTotal.subtotals,
853
876
  allowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),
854
877
  attachments: attachmentMetadata,
855
878
  document_references: ubl.documentReferences ?? []
@@ -889,6 +912,6 @@ const parseUblInvoiceDocument = (params) => {
889
912
  };
890
913
  };
891
914
  //#endregion
892
- export { PEPPOL_MLR_DOCUMENT_TYPE_VALUE, PEPPOL_MLR_PROCESS_VALUE, UblParseError, decodeXmlBytes, extractUblEmbeddedAttachments, isPdfLikeAttachment, isPeppolMessageLevelResponse, normalizeCurrency, normalizeUblResponse, parseDate, parsePeppolMessageLevelResponse, parseUblInvoice, parseUblInvoiceDocument };
915
+ export { PEPPOL_MLR_DOCUMENT_TYPE_VALUE, PEPPOL_MLR_PROCESS_VALUE, UblBuildError, UblParseError, decodeXmlBytes, extractUblEmbeddedAttachments, isPdfLikeAttachment, isPeppolMessageLevelResponse, normalizeCurrency, normalizeUblResponse, parseDate, parsePeppolMessageLevelResponse, parseUblInvoice, parseUblInvoiceDocument };
893
916
 
894
917
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["XmlDomParser","trimmed","cbcText","cacElement","cbcDirectText"],"sources":["../src/errors.ts","../src/xml-dom.ts","../src/parser.ts","../src/attachments.ts","../src/mlr.ts","../src/normalize.ts"],"sourcesContent":["/**\n * Thrown by the parse side of this package when input is broken: malformed\n * XML, or a UBL document missing an element EN 16931 makes mandatory. A parser\n * returns `null` instead when the input is well-formed but not the document\n * type it parses.\n */\nexport class UblParseError extends Error {\n\toverride readonly cause?: unknown;\n\n\tconstructor(message: string, options?: { cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = \"UblParseError\";\n\t\tif (options && \"cause\" in options) this.cause = options.cause;\n\t}\n}\n","import { type Document, DOMParser as XmlDomParser } from \"@xmldom/xmldom\";\nimport { UblParseError } from \"./errors.js\";\n\nexport const CBC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nexport const CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove DOCTYPE\n * blocks (including inline DTD subsets) before parsing.\n */\nexport const stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\n/**\n * Parse XML into a DOM, preferring the host's `DOMParser` (browsers) and\n * falling back to @xmldom/xmldom. Throws {@link UblParseError} when the XML\n * is malformed.\n */\nexport const parseXmlDocument = (xml: string): Document => {\n\tconst safeXml = stripDoctype(xml);\n\tconst BrowserDomParser = (globalThis as { DOMParser?: typeof XmlDomParser })\n\t\t.DOMParser;\n\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\tlet doc: Document;\n\ttry {\n\t\tdoc = parser.parseFromString(safeXml, \"text/xml\");\n\t} catch (cause) {\n\t\tthrow new UblParseError(\"Malformed XML\", { cause });\n\t}\n\tif (doc.getElementsByTagName(\"parsererror\").length > 0 || !doc.documentElement) {\n\t\tthrow new UblParseError(\"Malformed XML\");\n\t}\n\treturn doc;\n};\n","import type { Element } from \"@xmldom/xmldom\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\n\tUblContact,\n\tUblDelivery,\n\tUblDocumentReference,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblItemProperty,\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblParty,\n\tUblPartyIdentification,\n\tUblPaymentMeans,\n\tUblTaxSubtotal,\n} from \"./types.js\";\nimport { UblParseError } from \"./errors.js\";\nimport { CAC_NS, CBC_NS, parseXmlDocument } from \"./xml-dom.js\";\n\n// --- DOM helpers ---\n\nconst trimmed = (value: string | null | undefined): string | undefined => {\n\tconst text = value?.trim();\n\treturn text ? text : undefined;\n};\n\n/** First descendant CBC element's trimmed text; absent or blank is `undefined`. */\nfunction cbcText(parent: Element, tag: string): string | undefined {\n\treturn trimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);\n}\n\n/** Like {@link cbcText} but throws: the element is mandatory in EN 16931. */\nfunction requiredCbcText(parent: Element, tag: string, what: string): string {\n\tconst value = cbcText(parent, tag);\n\tif (value === undefined) throw new UblParseError(`Missing ${what} (cbc:${tag})`);\n\treturn value;\n}\n\nconst toNumber = (value: string | undefined): number | undefined => {\n\tif (value === undefined) return undefined;\n\tconst parsed = Number.parseFloat(value);\n\treturn Number.isNaN(parsed) ? undefined : parsed;\n};\n\nfunction cacElement(parent: Element, tag: string): Element | null {\n\treturn parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacElements(parent: Element, tag: string): Element[] {\n\treturn Array.from(parent.getElementsByTagNameNS(CAC_NS, tag));\n}\n\n/** First descendant CBC element as a number; absent or non-numeric is `undefined`. */\nfunction cbcNumber(parent: Element, tag: string): number | undefined {\n\treturn toNumber(cbcText(parent, tag));\n}\n\nfunction childElementsByTagNs(\n\tparent: Element,\n\tnamespace: string,\n\ttag: string,\n): Element[] {\n\tconst elements: Element[] = [];\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst element = node as Element;\n\t\tif (element.namespaceURI === namespace && element.localName === tag) {\n\t\t\telements.push(element);\n\t\t}\n\t}\n\treturn elements;\n}\n\nfunction cbcDirectText(parent: Element, tag: string): string | undefined {\n\treturn trimmed(childElementsByTagNs(parent, CBC_NS, tag)[0]?.textContent);\n}\n\nfunction cbcDirectNumber(parent: Element, tag: string): number | undefined {\n\treturn toNumber(cbcDirectText(parent, tag));\n}\n\nconst attribute = (el: Element | null | undefined, name: string): string | undefined =>\n\ttrimmed(el?.getAttribute(name));\n\nfunction cacDirectElement(parent: Element, tag: string): Element | null {\n\treturn childElementsByTagNs(parent, CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacDirectElements(parent: Element, tag: string): Element[] {\n\treturn childElementsByTagNs(parent, CAC_NS, tag);\n}\n\n// --- Section parsers ---\n\nfunction parseAddressFromElement(address: Element | null): UblAddress | undefined {\n\tif (!address) return undefined;\n\tconst country = cacElement(address, \"Country\");\n\treturn {\n\t\tstreet: cbcText(address, \"StreetName\"),\n\t\tadditionalStreet: cbcText(address, \"AdditionalStreetName\"),\n\t\tcity: cbcText(address, \"CityName\"),\n\t\tpostalZone: cbcText(address, \"PostalZone\"),\n\t\tcountrySubentity: cbcText(address, \"CountrySubentity\"),\n\t\tcountryCode: country ? cbcText(country, \"IdentificationCode\") : undefined,\n\t};\n}\n\nfunction parseAddress(party: Element): UblAddress | undefined {\n\tconst postal = cacElement(party, \"PostalAddress\");\n\treturn parseAddressFromElement(postal);\n}\n\nfunction parseTaxSchemeId(parent: Element | null): string | undefined {\n\tif (!parent) return undefined;\n\tconst taxScheme = cacElement(parent, \"TaxScheme\");\n\tif (!taxScheme) return undefined;\n\treturn cbcText(taxScheme, \"ID\");\n}\n\nfunction parseContact(party: Element): UblContact | undefined {\n\tconst contact = cacElement(party, \"Contact\");\n\tif (!contact) return undefined;\n\tconst name = cbcText(contact, \"Name\");\n\tconst phone = cbcText(contact, \"Telephone\");\n\tconst email = cbcText(contact, \"ElectronicMail\");\n\tif (!name && !phone && !email) return undefined;\n\treturn { name, phone, email };\n}\n\nfunction parsePartyIdentifications(party: Element): UblPartyIdentification[] {\n\tconst ids = cacElements(party, \"PartyIdentification\");\n\tconst result: UblPartyIdentification[] = [];\n\tfor (const idEl of ids) {\n\t\tconst idValue = cbcText(idEl, \"ID\");\n\t\tif (!idValue) continue;\n\t\tresult.push({\n\t\t\tid: idValue,\n\t\t\tschemeId: attribute(\n\t\t\t\tidEl.getElementsByTagNameNS(CBC_NS, \"ID\")[0],\n\t\t\t\t\"schemeID\",\n\t\t\t),\n\t\t});\n\t}\n\treturn result;\n}\n\nfunction parseParty(root: Element, role: string): UblParty {\n\tconst wrapper = cacElement(root, role);\n\tconst party = wrapper ? cacElement(wrapper, \"Party\") : null;\n\tif (!party) return {};\n\n\tconst partyName = cacElement(party, \"PartyName\");\n\tconst legalEntity = cacElement(party, \"PartyLegalEntity\");\n\tconst taxScheme = cacElement(party, \"PartyTaxScheme\");\n\tconst partyId = cacElement(party, \"PartyIdentification\");\n\tconst endpointEl = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tconst partyIdentifications = parsePartyIdentifications(party);\n\tconst companyIdEl = legalEntity\n\t\t? legalEntity.getElementsByTagNameNS(CBC_NS, \"CompanyID\")[0]\n\t\t: null;\n\n\treturn {\n\t\tname: partyName ? cbcText(partyName, \"Name\") : undefined,\n\t\tregistrationName: legalEntity\n\t\t\t? cbcText(legalEntity, \"RegistrationName\")\n\t\t\t: undefined,\n\t\tcompanyLegalForm: legalEntity\n\t\t\t? cbcText(legalEntity, \"CompanyLegalForm\")\n\t\t\t: undefined,\n\t\tvatId: taxScheme ? cbcText(taxScheme, \"CompanyID\") : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxScheme),\n\t\tcompanyId: companyIdEl\n\t\t\t? trimmed(companyIdEl.textContent)\n\t\t\t: partyId\n\t\t\t\t? cbcText(partyId, \"ID\")\n\t\t\t\t: undefined,\n\t\tcompanyIdSchemeId: attribute(companyIdEl, \"schemeID\"),\n\t\tendpointId: trimmed(endpointEl?.textContent),\n\t\tendpointSchemeId: attribute(endpointEl, \"schemeID\"),\n\t\tpartyIdentifications:\n\t\t\tpartyIdentifications.length > 0 ? partyIdentifications : undefined,\n\t\taddress: parseAddress(party),\n\t\tcontact: parseContact(party),\n\t};\n}\n\nfunction parseTaxSubtotal(sub: Element): UblTaxSubtotal {\n\tconst cat = cacElement(sub, \"TaxCategory\");\n\treturn {\n\t\ttaxableAmount: cbcNumber(sub, \"TaxableAmount\"),\n\t\ttaxAmount: cbcNumber(sub, \"TaxAmount\"),\n\t\ttaxPercent:\n\t\t\t(cat ? cbcNumber(cat, \"Percent\") : undefined) ?? cbcNumber(sub, \"Percent\"),\n\t\ttaxCategoryId: cat ? cbcText(cat, \"ID\") : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(cat),\n\t\ttaxExemptionReason: cat ? cbcText(cat, \"TaxExemptionReason\") : undefined,\n\t};\n}\n\nfunction parseTaxSubtotalsFromTaxTotal(taxTotal: Element): UblTaxSubtotal[] {\n\treturn cacDirectElements(taxTotal, \"TaxSubtotal\").map(parseTaxSubtotal);\n}\n\nfunction parseTaxSubtotals(root: Element): UblTaxSubtotal[] {\n\tconst taxTotals = cacDirectElements(root, \"TaxTotal\");\n\tif (taxTotals.length === 0) return [];\n\treturn taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal);\n}\n\nfunction parseAllowanceCharge(charge: Element): UblAllowanceCharge {\n\tconst taxCategory = cacElement(charge, \"TaxCategory\");\n\tconst indicatorRaw = cbcDirectText(charge, \"ChargeIndicator\")?.toLowerCase();\n\tconst chargeIndicator = indicatorRaw === \"true\" || indicatorRaw === \"1\";\n\treturn {\n\t\tchargeIndicator,\n\t\tamount: cbcNumber(charge, \"Amount\"),\n\t\tbaseAmount: cbcDirectNumber(charge, \"BaseAmount\"),\n\t\tmultiplierFactorNumeric: cbcDirectNumber(charge, \"MultiplierFactorNumeric\"),\n\t\treason: cbcText(charge, \"AllowanceChargeReason\"),\n\t\treasonCode: cbcText(charge, \"AllowanceChargeReasonCode\"),\n\t\ttaxPercent: taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined,\n\t\ttaxCategoryId: taxCategory ? cbcText(taxCategory, \"ID\") : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxCategory),\n\t};\n}\n\nfunction parseAllowanceCharges(parent: Element): UblAllowanceCharge[] {\n\treturn cacDirectElements(parent, \"AllowanceCharge\").map(parseAllowanceCharge);\n}\n\nfunction parseLines(root: Element, isCreditNote: boolean): UblLine[] {\n\tconst qtyTag = isCreditNote ? \"CreditedQuantity\" : \"InvoicedQuantity\";\n\tconst lineTag = isCreditNote ? \"CreditNoteLine\" : \"InvoiceLine\";\n\n\treturn cacElements(root, lineTag).map((line) => {\n\t\tconst item = cacElement(line, \"Item\");\n\t\tconst price = cacElement(line, \"Price\");\n\t\tconst taxCategory = item ? cacElement(item, \"ClassifiedTaxCategory\") : null;\n\t\tconst sellersId = item ? cacElement(item, \"SellersItemIdentification\") : null;\n\t\tconst buyersId = item ? cacElement(item, \"BuyersItemIdentification\") : null;\n\t\tconst qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];\n\t\tconst lineExtensionAmount = cbcNumber(line, \"LineExtensionAmount\");\n\t\tconst lineTaxTotal = cacDirectElement(line, \"TaxTotal\");\n\t\tconst lineTaxSubtotals = lineTaxTotal\n\t\t\t? parseTaxSubtotalsFromTaxTotal(lineTaxTotal)\n\t\t\t: [];\n\t\tconst taxAmountFromSubtotals = lineTaxSubtotals.reduce(\n\t\t\t(sum, subtotal) => sum + (subtotal.taxAmount ?? 0),\n\t\t\t0,\n\t\t);\n\t\tconst taxAmountFromLineTotal = lineTaxTotal\n\t\t\t? cbcDirectNumber(lineTaxTotal, \"TaxAmount\")\n\t\t\t: undefined;\n\t\tconst taxPercent =\n\t\t\tlineTaxSubtotals[0]?.taxPercent ??\n\t\t\t(taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined);\n\t\tconst computedTaxAmount =\n\t\t\ttaxPercent !== undefined && lineExtensionAmount !== undefined\n\t\t\t\t? Number(((lineExtensionAmount * taxPercent) / 100).toFixed(2))\n\t\t\t\t: undefined;\n\t\tconst lineAllowanceCharges = parseAllowanceCharges(line);\n\t\tconst priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];\n\t\tconst allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];\n\t\tconst discountAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0),\n\t\t\t0,\n\t\t);\n\t\tconst chargeAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum + Math.abs(charge.amount ?? 0) : sum,\n\t\t\t0,\n\t\t);\n\n\t\tconst additionalItemProperties: UblItemProperty[] = [];\n\t\tif (item) {\n\t\t\tfor (const prop of cacElements(item, \"AdditionalItemProperty\")) {\n\t\t\t\tconst propName = cbcText(prop, \"Name\");\n\t\t\t\tconst propValue = cbcText(prop, \"Value\");\n\t\t\t\tif (propName) {\n\t\t\t\t\tadditionalItemProperties.push({\n\t\t\t\t\t\tname: propName,\n\t\t\t\t\t\tvalue: propValue,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// EN16931 BT-146 (PriceAmount) is the price for BT-149 (BaseQuantity) units\n\t\t// of the item, not necessarily for one unit. Effective unit price is\n\t\t// PriceAmount / BaseQuantity, with BaseQuantity defaulting to 1 when absent.\n\t\tconst priceAmount = price ? cbcNumber(price, \"PriceAmount\") : undefined;\n\t\tconst priceBaseQuantity = price\n\t\t\t? cbcDirectNumber(price, \"BaseQuantity\")\n\t\t\t: undefined;\n\t\tconst unitPrice =\n\t\t\tpriceAmount !== undefined && priceBaseQuantity && priceBaseQuantity > 0\n\t\t\t\t? priceAmount / priceBaseQuantity\n\t\t\t\t: priceAmount;\n\n\t\treturn {\n\t\t\tid: requiredCbcText(line, \"ID\", `${lineTag} identifier`),\n\t\t\tdescription: item ? cbcText(item, \"Description\") : undefined,\n\t\t\tquantity: cbcNumber(line, qtyTag),\n\t\t\tunitCode: attribute(qtyEl, \"unitCode\"),\n\t\t\tunitPrice,\n\t\t\tlineExtensionAmount,\n\t\t\ttaxPercent,\n\t\t\ttaxAmount:\n\t\t\t\ttaxAmountFromLineTotal ??\n\t\t\t\t(lineTaxSubtotals.length > 0\n\t\t\t\t\t? taxAmountFromSubtotals\n\t\t\t\t\t: computedTaxAmount),\n\t\t\ttaxCategoryId:\n\t\t\t\tlineTaxSubtotals[0]?.taxCategoryId ??\n\t\t\t\t(taxCategory ? cbcText(taxCategory, \"ID\") : undefined),\n\t\t\ttaxSchemeId:\n\t\t\t\tlineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),\n\t\t\ttaxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : undefined,\n\t\t\tallowanceCharges:\n\t\t\t\tallowanceCharges.length > 0 ? allowanceCharges : undefined,\n\t\t\tdiscountAmount: discountAmount > 0 ? discountAmount : undefined,\n\t\t\tchargeAmount: chargeAmount > 0 ? chargeAmount : undefined,\n\t\t\titemName: item ? cbcText(item, \"Name\") : undefined,\n\t\t\tsellersItemId: sellersId ? cbcText(sellersId, \"ID\") : undefined,\n\t\t\tbuyersItemId: buyersId ? cbcText(buyersId, \"ID\") : undefined,\n\t\t\tadditionalItemProperties:\n\t\t\t\tadditionalItemProperties.length > 0\n\t\t\t\t\t? additionalItemProperties\n\t\t\t\t\t: undefined,\n\t\t\tinvoicePeriod: parseInvoicePeriod(line),\n\t\t};\n\t});\n}\n\nfunction parseMonetaryTotal(root: Element): UblMonetaryTotal {\n\tconst total = cacDirectElement(root, \"LegalMonetaryTotal\");\n\tif (!total) return {};\n\treturn {\n\t\tlineExtensionAmount: cbcNumber(total, \"LineExtensionAmount\"),\n\t\ttaxExclusiveAmount: cbcNumber(total, \"TaxExclusiveAmount\"),\n\t\ttaxInclusiveAmount: cbcNumber(total, \"TaxInclusiveAmount\"),\n\t\tallowanceTotalAmount: cbcNumber(total, \"AllowanceTotalAmount\"),\n\t\tchargeTotalAmount: cbcNumber(total, \"ChargeTotalAmount\"),\n\t\tprepaidAmount: cbcNumber(total, \"PrepaidAmount\"),\n\t\tpayableRoundingAmount: cbcNumber(total, \"PayableRoundingAmount\"),\n\t\tpayableAmount: cbcNumber(total, \"PayableAmount\"),\n\t};\n}\n\nfunction parsePaymentMeansElement(pm: Element): UblPaymentMeans {\n\tconst account = cacElement(pm, \"PayeeFinancialAccount\");\n\tconst branch = account ? cacElement(account, \"FinancialInstitutionBranch\") : null;\n\tconst paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, \"PaymentMeansCode\")[0];\n\tconst mandate = cacElement(pm, \"PaymentMandate\");\n\n\treturn {\n\t\tcode: cbcText(pm, \"PaymentMeansCode\"),\n\t\tcodeName: attribute(paymentMeansCodeEl, \"name\"),\n\t\tpaymentId: cbcText(pm, \"PaymentID\"),\n\t\tiban: account ? cbcText(account, \"ID\") : undefined,\n\t\tbic: branch ? cbcText(branch, \"ID\") : undefined,\n\t\taccountName: account ? cbcText(account, \"Name\") : undefined,\n\t\tmandateId: mandate ? cbcText(mandate, \"ID\") : undefined,\n\t};\n}\n\nfunction parsePaymentMeansList(root: Element): UblPaymentMeans[] | undefined {\n\tconst list = cacElements(root, \"PaymentMeans\").map(parsePaymentMeansElement);\n\treturn list.length > 0 ? list : undefined;\n}\n\n/**\n * BT-73/BT-74 on a document, BT-134/BT-135 on a line. Direct children only:\n * a descendant search on the document root would report the first line's\n * period as the document's whenever the document states none of its own.\n */\nfunction parseInvoicePeriod(parent: Element): UblInvoicePeriod | undefined {\n\tconst period = cacDirectElement(parent, \"InvoicePeriod\");\n\tif (!period) return undefined;\n\n\tconst start = cbcText(period, \"StartDate\");\n\tconst end = cbcText(period, \"EndDate\");\n\tif (!start && !end) return undefined;\n\n\treturn {\n\t\tstartDate: start,\n\t\tendDate: end,\n\t\tdescriptionCode: cbcText(period, \"DescriptionCode\"),\n\t};\n}\n\nfunction parseDelivery(root: Element): UblDelivery | undefined {\n\tconst delivery = cacElement(root, \"Delivery\");\n\tif (!delivery) return undefined;\n\tconst actualDeliveryDate = cbcText(delivery, \"ActualDeliveryDate\");\n\tconst deliveryLocation = cacElement(delivery, \"DeliveryLocation\");\n\tconst address = parseAddressFromElement(\n\t\tdeliveryLocation ? cacElement(deliveryLocation, \"Address\") : null,\n\t);\n\tif (!actualDeliveryDate && !address) return undefined;\n\treturn {\n\t\tactualDeliveryDate,\n\t\taddress,\n\t};\n}\n\nfunction parsePaymentTermsNote(root: Element): string | undefined {\n\tconst paymentTerms = cacElement(root, \"PaymentTerms\");\n\tif (!paymentTerms) return undefined;\n\treturn cbcText(paymentTerms, \"Note\");\n}\n\nfunction parseNotes(root: Element): string | undefined {\n\tconst noteEls = root.getElementsByTagNameNS(CBC_NS, \"Note\");\n\tconst notes: string[] = [];\n\tfor (let i = 0; i < noteEls.length; i++) {\n\t\tconst el = noteEls[i];\n\t\tif (!el) continue;\n\t\tif (el.parentElement === root || el.parentNode === root) {\n\t\t\tconst text = el.textContent?.trim();\n\t\t\tif (text) notes.push(text);\n\t\t}\n\t}\n\treturn notes.length > 0 ? notes.join(\"\\n\") : undefined;\n}\n\nfunction parseAttachments(root: Element): {\n\tattachments: UblAttachment[] | undefined;\n\tdocumentReferences: UblDocumentReference[] | undefined;\n} {\n\tconst refs = cacElements(root, \"AdditionalDocumentReference\");\n\tconst attachments: UblAttachment[] = [];\n\tconst documentReferences: UblDocumentReference[] = [];\n\n\tfor (const ref of refs) {\n\t\tconst attachment = cacElement(ref, \"Attachment\");\n\t\tconst refId = cbcText(ref, \"ID\");\n\t\tconst description = cbcText(ref, \"DocumentDescription\");\n\n\t\tif (!attachment) {\n\t\t\t// Text-only document reference (e.g. terms & conditions, notices)\n\t\t\tif (refId || description) {\n\t\t\t\tdocumentReferences.push({ id: refId, description });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst binaryEl = attachment.getElementsByTagNameNS(\n\t\t\tCBC_NS,\n\t\t\t\"EmbeddedDocumentBinaryObject\",\n\t\t)[0];\n\t\tconst externalRef = cacElement(attachment, \"ExternalReference\");\n\n\t\tif (binaryEl) {\n\t\t\tconst content = binaryEl.textContent?.trim();\n\t\t\tif (content) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tfilename: attribute(binaryEl, \"filename\"),\n\t\t\t\t\tmimeCode: attribute(binaryEl, \"mimeCode\"),\n\t\t\t\t\tdescription,\n\t\t\t\t\tbase64Content: content,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (externalRef) {\n\t\t\tconst uri = cbcText(externalRef, \"URI\");\n\t\t\tif (uri) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tdescription,\n\t\t\t\t\texternalUri: uri,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tattachments: attachments.length > 0 ? attachments : undefined,\n\t\tdocumentReferences:\n\t\t\tdocumentReferences.length > 0 ? documentReferences : undefined,\n\t};\n}\n\nfunction parseBillingReference(root: Element): UblBillingReference | undefined {\n\tconst billingRef = cacElement(root, \"BillingReference\");\n\tif (!billingRef) return undefined;\n\tconst invoiceRef = cacElement(billingRef, \"InvoiceDocumentReference\");\n\tif (!invoiceRef) return undefined;\n\tconst invoiceId = cbcText(invoiceRef, \"ID\");\n\tconst invoiceIssueDate = cbcText(invoiceRef, \"IssueDate\");\n\tif (!invoiceId && !invoiceIssueDate) return undefined;\n\treturn { invoiceId, invoiceIssueDate };\n}\n\n// --- Main parser ---\n\n/**\n * Drop `undefined`-valued keys recursively so an absent field is an absent\n * key, not a key holding `undefined`. Arrays keep their order and length.\n */\nfunction omitUndefined<T>(value: T): T {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(omitUndefined) as T;\n\t}\n\tif (value !== null && typeof value === \"object\") {\n\t\tconst out: Record<string, unknown> = {};\n\t\tfor (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n\t\t\tif (entry !== undefined) out[key] = omitUndefined(entry);\n\t\t}\n\t\treturn out as T;\n\t}\n\treturn value;\n}\n\nconst INVOICE_NS = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nconst CREDIT_NOTE_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\n\n/**\n * Parse a UBL 2.1 Invoice or CreditNote.\n *\n * Returns `null` when the XML is well-formed but its root is not a UBL\n * `Invoice`/`CreditNote`. Throws {@link UblParseError} when the XML is\n * malformed or the document lacks an element EN 16931 makes mandatory\n * (document id, issue date, currency, line id).\n */\nexport function parseUblInvoice(xml: string): UblInvoice | null {\n\tconst doc = parseXmlDocument(xml);\n\tconst root = doc.documentElement;\n\tif (!root) return null;\n\n\tlet documentType: \"Invoice\" | \"CreditNote\";\n\tif (root.localName === \"Invoice\" && root.namespaceURI === INVOICE_NS) {\n\t\tdocumentType = \"Invoice\";\n\t} else if (\n\t\troot.localName === \"CreditNote\" &&\n\t\troot.namespaceURI === CREDIT_NOTE_NS\n\t) {\n\t\tdocumentType = \"CreditNote\";\n\t} else {\n\t\treturn null;\n\t}\n\n\tconst isCreditNote = documentType === \"CreditNote\";\n\tconst id = requiredCbcText(root, \"ID\", \"document identifier\");\n\tconst issueDate = requiredCbcText(root, \"IssueDate\", \"issue date\");\n\tconst currency = requiredCbcText(root, \"DocumentCurrencyCode\", \"currency code\");\n\tconst paymentMeansList = parsePaymentMeansList(root);\n\tconst orderReference = cacElement(root, \"OrderReference\");\n\tconst contractReference = cacElement(root, \"ContractDocumentReference\");\n\tconst projectReference = cacElement(root, \"ProjectReference\");\n\tconst { attachments, documentReferences } = parseAttachments(root);\n\n\treturn omitUndefined<UblInvoice>({\n\t\tdocumentType,\n\t\tcustomizationId: cbcText(root, \"CustomizationID\"),\n\t\tprofileId: cbcText(root, \"ProfileID\"),\n\t\tid,\n\t\tinvoiceTypeCode:\n\t\t\tcbcText(root, \"InvoiceTypeCode\") ?? cbcText(root, \"CreditNoteTypeCode\"),\n\t\tissueDate,\n\t\tdueDate: cbcText(root, \"DueDate\"),\n\t\ttaxPointDate: cbcText(root, \"TaxPointDate\"),\n\t\tcurrency,\n\t\tbuyerReference: cbcText(root, \"BuyerReference\"),\n\t\torderReference: orderReference ? cbcText(orderReference, \"ID\") : undefined,\n\t\tsalesOrderId: orderReference\n\t\t\t? cbcText(orderReference, \"SalesOrderID\")\n\t\t\t: undefined,\n\t\tcontractReference: contractReference\n\t\t\t? cbcText(contractReference, \"ID\")\n\t\t\t: undefined,\n\t\tprojectReference: projectReference\n\t\t\t? cbcText(projectReference, \"ID\")\n\t\t\t: undefined,\n\t\tbillingReference: parseBillingReference(root),\n\t\tseller: parseParty(root, \"AccountingSupplierParty\"),\n\t\tbuyer: parseParty(root, \"AccountingCustomerParty\"),\n\t\tdelivery: parseDelivery(root),\n\t\tlines: parseLines(root, isCreditNote),\n\t\ttaxSubtotals: parseTaxSubtotals(root),\n\t\tmonetaryTotal: parseMonetaryTotal(root),\n\t\tpaymentMeansList,\n\t\tpaymentMeans: paymentMeansList?.[0],\n\t\tinvoicePeriod: parseInvoicePeriod(root),\n\t\tnote: parseNotes(root),\n\t\tpaymentTermsNote: parsePaymentTermsNote(root),\n\t\tattachments,\n\t\tdocumentReferences,\n\t\tallowanceCharges: parseAllowanceCharges(root),\n\t});\n}\n","import { UblParseError } from \"./errors.js\";\nimport { parseUblInvoice } from \"./parser.js\";\nimport type { UblAttachment } from \"./types.js\";\n\n/**\n * An embedded attachment extracted from a UBL document's\n * `AdditionalDocumentReference` entries, with its binary content still\n * base64-encoded. `sizeBytes` is the decoded size.\n */\nexport interface UblEmbeddedAttachment {\n\tid?: string | undefined;\n\tfilename: string;\n\tmimeCode: string;\n\tsizeBytes: number;\n\t/** Zero-based position among the document's embedded attachments. */\n\tlineOrder: number;\n\tbase64Content: string;\n}\n\n/** Decoded byte length of a base64 string, accounting for `=` padding. */\nexport const base64DecodedSize = (base64: string): number => {\n\tconst sanitized = base64.replace(/\\s+/g, \"\");\n\tif (!sanitized) return 0;\n\tconst padding = sanitized.endsWith(\"==\") ? 2 : sanitized.endsWith(\"=\") ? 1 : 0;\n\treturn Math.floor((sanitized.length * 3) / 4) - padding;\n};\n\n/**\n * Extract the embedded attachments (typically the human-readable PDF) from a\n * UBL invoice or credit note XML. Attachments referenced only by external URI\n * (no `EmbeddedDocumentBinaryObject`) are skipped; use {@link parseUblInvoice}\n * directly when those matter.\n *\n * @throws {UblParseError} when the XML is malformed or not a UBL invoice.\n */\nexport const extractUblEmbeddedAttachments = (xml: string): UblEmbeddedAttachment[] => {\n\tconst parsed = parseUblInvoice(xml);\n\tif (!parsed) throw new UblParseError(\"Document is not a UBL Invoice or CreditNote\");\n\tif (!parsed.attachments || parsed.attachments.length === 0) return [];\n\n\treturn parsed.attachments\n\t\t.map((attachment, index): UblEmbeddedAttachment | null => {\n\t\t\tconst base64Content = attachment.base64Content?.trim();\n\t\t\tif (!base64Content) return null;\n\t\t\treturn {\n\t\t\t\tid: attachment.id,\n\t\t\t\tfilename: attachment.filename ?? `attachment-${index + 1}`,\n\t\t\t\tmimeCode: attachment.mimeCode ?? \"application/octet-stream\",\n\t\t\t\tsizeBytes: base64DecodedSize(base64Content),\n\t\t\t\tlineOrder: index,\n\t\t\t\tbase64Content,\n\t\t\t};\n\t\t})\n\t\t.filter((entry): entry is UblEmbeddedAttachment => entry !== null);\n};\n\n/**\n * Whether an attachment looks like a PDF, by MIME type first and filename\n * extension as a fallback.\n */\nexport const isPdfLikeAttachment = (\n\tattachment: Pick<UblAttachment, \"filename\" | \"mimeCode\">,\n): boolean => {\n\tconst mimeCode = attachment.mimeCode?.toLowerCase() ?? \"\";\n\tif (mimeCode === \"application/pdf\" || mimeCode.endsWith(\"/pdf\")) return true;\n\treturn attachment.filename?.toLowerCase().endsWith(\".pdf\") ?? false;\n};\n","import type { Element } from \"@xmldom/xmldom\";\nimport { UblParseError } from \"./errors.js\";\nimport { CAC_NS, CBC_NS, parseXmlDocument } from \"./xml-dom.js\";\n\n/**\n * Peppol BIS MLR (Message Level Response) document-type identifier value\n * (Peppol `busdox-docid-qns` scheme).\n */\nexport const PEPPOL_MLR_DOCUMENT_TYPE_VALUE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1\";\n\n/** Peppol BIS MLR process identifier value. */\nexport const PEPPOL_MLR_PROCESS_VALUE = \"urn:fdc:peppol.eu:poacc:bis:mlr:3\";\n\n/**\n * A parsed Peppol Message Level Response (a UBL `ApplicationResponse`). Every\n * field is optional: a given MLR may omit any of them, and an omitted field is\n * an absent key.\n */\nexport interface PeppolMessageLevelResponse {\n\tcustomizationId?: string | undefined;\n\tprofileId?: string | undefined;\n\tresponseId?: string | undefined;\n\tissueDate?: string | undefined;\n\tissueTime?: string | undefined;\n\treferencedDocumentId?: string | undefined;\n\tresponseCode?: string | undefined;\n\tdescription?: string | undefined;\n\t/** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */\n\tsenderIdentifier?: string | undefined;\n\t/** Receiver participant id as `schemeID:value`. */\n\treceiverIdentifier?: string | undefined;\n}\n\nconst trimmed = (value: string | null | undefined): string | undefined => {\n\tconst text = value?.trim();\n\treturn text ? text : undefined;\n};\n\n/** First descendant CBC element's trimmed text, or undefined. */\nconst cbcText = (parent: Element, tag: string): string | undefined =>\n\ttrimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);\n\n/**\n * First direct-child CBC element's trimmed text, or null. Used for the\n * top-level scalars so a nested `cbc:ID` (e.g. inside DocumentReference) cannot\n * shadow the ApplicationResponse's own id.\n */\nconst cbcDirectText = (parent: Element, tag: string): string | undefined => {\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst el = node as Element;\n\t\tif (el.namespaceURI === CBC_NS && el.localName === tag) {\n\t\t\treturn trimmed(el.textContent);\n\t\t}\n\t}\n\treturn undefined;\n};\n\n/** First descendant CAC element, or null. */\nconst cacElement = (parent: Element, tag: string): Element | null =>\n\tparent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n\n/**\n * The Peppol participant identifier of a SenderParty / ReceiverParty, rendered\n * as `schemeID:value` when the EndpointID carries a scheme and the value does\n * not already include one, otherwise the raw value.\n */\nconst endpointIdentifier = (party: Element | null): string | undefined => {\n\tif (!party) return undefined;\n\tconst endpoint = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tif (!endpoint) return undefined;\n\tconst id = trimmed(endpoint.textContent);\n\tconst scheme = endpoint.getAttribute(\"schemeID\");\n\tif (scheme && id && !id.includes(\":\")) return `${scheme}:${id}`;\n\treturn id;\n};\n\n/**\n * Locate the `ApplicationResponse` element, unwrapping a Standard Business\n * Document (SBDH) envelope when present. Returns null when the XML contains no\n * ApplicationResponse; throws {@link UblParseError} when it is malformed.\n */\nconst findApplicationResponse = (xml: string): Element | null => {\n\tconst doc = parseXmlDocument(xml);\n\tconst root = doc.documentElement;\n\tif (!root) return null;\n\tif (root.localName === \"ApplicationResponse\") return root;\n\tconst candidates = root.getElementsByTagName(\"*\");\n\tfor (let i = 0; i < candidates.length; i++) {\n\t\tconst el = candidates[i];\n\t\tif (el?.localName === \"ApplicationResponse\") return el;\n\t}\n\treturn null;\n};\n\n/**\n * Whether an inbound document is a Peppol Message Level Response, identified by\n * its document-type value, its process value, or by parsing the XML and finding\n * an `ApplicationResponse` root (SBDH-wrapped or not).\n */\nexport const isPeppolMessageLevelResponse = (params: {\n\tdocumentTypeValue?: string | null;\n\tprocessValue?: string | null;\n\txml?: string | null;\n}): boolean => {\n\tif (trimmed(params.documentTypeValue) === PEPPOL_MLR_DOCUMENT_TYPE_VALUE) {\n\t\treturn true;\n\t}\n\tif (trimmed(params.processValue) === PEPPOL_MLR_PROCESS_VALUE) return true;\n\tconst xml = trimmed(params.xml);\n\tif (!xml) return false;\n\ttry {\n\t\treturn findApplicationResponse(xml) !== null;\n\t} catch (error) {\n\t\t// A sniff answers \"is this an MLR?\"; malformed XML is simply \"no\".\n\t\tif (error instanceof UblParseError) return false;\n\t\tthrow error;\n\t}\n};\n\n/**\n * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping\n * an SBDH envelope when present. Throws {@link UblParseError} when the XML is\n * malformed or is not an ApplicationResponse.\n */\nexport const parsePeppolMessageLevelResponse = (\n\txml: string,\n): PeppolMessageLevelResponse => {\n\tconst root = findApplicationResponse(xml);\n\tif (!root) {\n\t\tthrow new UblParseError(\"Document is not a Peppol Message Level Response\");\n\t}\n\n\tconst documentResponse = cacElement(root, \"DocumentResponse\");\n\tconst response = documentResponse ? cacElement(documentResponse, \"Response\") : null;\n\tconst documentReference = documentResponse\n\t\t? cacElement(documentResponse, \"DocumentReference\")\n\t\t: null;\n\n\treturn {\n\t\tcustomizationId: cbcDirectText(root, \"CustomizationID\"),\n\t\tprofileId: cbcDirectText(root, \"ProfileID\"),\n\t\tresponseId: cbcDirectText(root, \"ID\"),\n\t\tissueDate: cbcDirectText(root, \"IssueDate\"),\n\t\tissueTime: cbcDirectText(root, \"IssueTime\"),\n\t\treferencedDocumentId: documentReference\n\t\t\t? cbcText(documentReference, \"ID\")\n\t\t\t: undefined,\n\t\tresponseCode: response ? cbcText(response, \"ResponseCode\") : undefined,\n\t\tdescription: response ? cbcText(response, \"Description\") : undefined,\n\t\tsenderIdentifier: endpointIdentifier(cacElement(root, \"SenderParty\")),\n\t\treceiverIdentifier: endpointIdentifier(cacElement(root, \"ReceiverParty\")),\n\t};\n};\n","import { base64DecodedSize } from \"./attachments.js\";\nimport { UblParseError } from \"./errors.js\";\nimport { parseUblInvoice } from \"./parser.js\";\nimport type {\n\tInvoiceExtractionDTO,\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblInvoice,\n\tUblPaymentMeans,\n} from \"./types.js\";\n\n// --- Utility helpers ---\n\nconst UTF8_BOM = 0xfeff;\n\n/** `null` for an absent value or an \"N/A\" placeholder written by the sender. */\nconst normalizeText = (value: string | undefined): string | null => {\n\tif (value === undefined) return null;\n\tconst upper = value.toUpperCase();\n\tif (upper === \"NA\" || upper === \"N/A\") return null;\n\treturn value;\n};\n\nconst toNumberOrNull = (value: number | undefined): number | null =>\n\tvalue !== undefined && Number.isFinite(value) ? value : null;\n\nconst roundToCents = (value: number): number => Math.round(value * 100) / 100;\n\nexport const normalizeCurrency = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\treturn trimmed.toUpperCase();\n};\n\nexport const parseDate = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst timestamp = Date.parse(trimmed);\n\tif (Number.isNaN(timestamp)) return null;\n\tconst iso = new Date(timestamp).toISOString();\n\treturn iso.slice(0, 10);\n};\n\nconst sanitizePaymentMeans = (pm: UblPaymentMeans) => ({\n\tcode: normalizeText(pm.code),\n\tcode_name: normalizeText(pm.codeName),\n\tpayment_id: normalizeText(pm.paymentId),\n\tiban: normalizeText(pm.iban),\n\tbic: normalizeText(pm.bic),\n\taccount_name: normalizeText(pm.accountName),\n\tmandate_id: normalizeText(pm.mandateId),\n});\n\n// --- Address helpers ---\n\nconst present = (part: string | undefined): part is string => part !== undefined;\n\nconst joinStreet = (address: UblAddress): string =>\n\t[address.street, address.additionalStreet].filter(present).join(\" \");\n\nconst addressToString = (address?: UblAddress): string | null => {\n\tif (!address) return null;\n\tconst street = joinStreet(address);\n\tconst cityLine = [address.postalZone, address.city].filter(present).join(\" \");\n\tconst countryLine = [address.countrySubentity, address.countryCode]\n\t\t.filter(present)\n\t\t.join(\" \");\n\tconst lines = [street, cityLine, countryLine].filter((line) => line.length > 0);\n\treturn lines.length > 0 ? lines.join(\"\\n\") : null;\n};\n\nconst addressToStructured = (address?: UblAddress) => {\n\tif (!address) return null;\n\tconst line1 = joinStreet(address);\n\tconst result = {\n\t\tline1: line1 ? normalizeText(line1) : null,\n\t\tline2: null as string | null,\n\t\tcity: normalizeText(address.city),\n\t\tstate: normalizeText(address.countrySubentity),\n\t\tpostal_code: normalizeText(address.postalZone),\n\t\tcountry: normalizeText(address.countryCode),\n\t};\n\tconst hasValue = Object.values(result).some((value) => value);\n\treturn hasValue ? result : null;\n};\n\n// --- Attachment & charge sanitizers ---\n\nconst sanitizeAttachments = (attachments?: UblAttachment[]) =>\n\t(attachments ?? []).map((attachment) => ({\n\t\tid: normalizeText(attachment.id),\n\t\tfilename: normalizeText(attachment.filename),\n\t\tmime_code: normalizeText(attachment.mimeCode),\n\t\tdescription: normalizeText(attachment.description),\n\t\tsize_bytes:\n\t\t\tattachment.base64Content !== undefined\n\t\t\t\t? base64DecodedSize(attachment.base64Content)\n\t\t\t\t: null,\n\t\texternal_uri: normalizeText(attachment.externalUri),\n\t}));\n\nconst sanitizeAllowanceCharges = (charges?: UblAllowanceCharge[]) =>\n\t(charges ?? []).map((charge) => ({\n\t\tcharge_indicator: charge.chargeIndicator,\n\t\tamount: toNumberOrNull(charge.amount),\n\t\tbase_amount: toNumberOrNull(charge.baseAmount),\n\t\tmultiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),\n\t\treason: normalizeText(charge.reason),\n\t\treason_code: normalizeText(charge.reasonCode),\n\t\ttax_percent: toNumberOrNull(charge.taxPercent),\n\t\ttax_category_id: normalizeText(charge.taxCategoryId),\n\t\ttax_scheme_id: normalizeText(charge.taxSchemeId),\n\t}));\n\nconst sanitizeRawUbl = (ubl: UblInvoice) => ({\n\t...ubl,\n\tattachments: sanitizeAttachments(ubl.attachments),\n\tdocumentReferences: ubl.documentReferences ?? [],\n});\n\n// --- Summation helpers ---\n\nconst sumTaxTotal = (ubl: UblInvoice): number | null => {\n\tconst subtotalSum = ubl.taxSubtotals.reduce(\n\t\t(sum, subtotal) => sum + (subtotal.taxAmount ?? 0),\n\t\t0,\n\t);\n\tif (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) {\n\t\treturn subtotalSum;\n\t}\n\tconst { taxInclusiveAmount, taxExclusiveAmount } = ubl.monetaryTotal;\n\tif (taxInclusiveAmount === undefined || taxExclusiveAmount === undefined) {\n\t\treturn null;\n\t}\n\treturn taxInclusiveAmount - taxExclusiveAmount;\n};\n\nconst sumAllowanceChargesByType = (\n\tcharges: UblAllowanceCharge[] | undefined,\n\tchargeIndicator: boolean,\n) =>\n\t(charges ?? []).reduce((sum, charge) => {\n\t\tif (charge.chargeIndicator !== chargeIndicator) return sum;\n\t\treturn sum + Math.abs(charge.amount ?? 0);\n\t}, 0);\n\n// --- Public API ---\n\n/**\n * Decode raw XML bytes, stripping an optional UTF-8 BOM.\n */\nexport const decodeXmlBytes = (bytes: Uint8Array): string => {\n\tconst text = new TextDecoder(\"utf-8\").decode(bytes);\n\treturn text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;\n};\n\n/**\n * Parse a UBL XML string and normalize it into a flat DTO suitable for\n * database storage or API responses.\n *\n * @throws {UblParseError} when the XML is malformed, not a UBL invoice, or\n * lacks a mandatory element.\n */\nexport const normalizeUblResponse = (\n\txml: string,\n\tdocumentId: string,\n): {\n\textracted: InvoiceExtractionDTO;\n\trawPayload: Record<string, unknown>;\n} => {\n\tconst ubl = parseUblInvoice(xml);\n\tif (!ubl) {\n\t\tthrow new UblParseError(\"Document is not a UBL Invoice or CreditNote\");\n\t}\n\n\tconst subtotal =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);\n\tconst total =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst prepaidAmount = toNumberOrNull(ubl.monetaryTotal.prepaidAmount);\n\tconst roundingAmount = toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount) ?? 0;\n\t// BR-CO-16: payable = total - prepaid + rounding. With no declared\n\t// PrepaidAmount we invert that to infer what was paid, but the rounding\n\t// term has to come out first — a cash-rounded payable (BT-114) is a\n\t// total-vs-payable gap by design, and reading it as a prepayment reports\n\t// an unpaid invoice as partially settled. Rounded before the sign test so\n\t// the float residue of undoing it cannot pass as a sub-cent prepayment.\n\tconst inferredPaid =\n\t\ttotal !== null && amountDue !== null\n\t\t\t? roundToCents(total - (amountDue - roundingAmount))\n\t\t\t: null;\n\tconst amountPaid =\n\t\tprepaidAmount ??\n\t\t(inferredPaid !== null && inferredPaid > 0 ? inferredPaid : null);\n\tconst taxTotal = toNumberOrNull(sumTaxTotal(ubl) ?? undefined);\n\tconst hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;\n\tconst headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);\n\tconst headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);\n\tconst currency = normalizeCurrency(ubl.currency);\n\tconst paymentTerms = normalizeText(ubl.paymentTermsNote);\n\tconst poNumber =\n\t\tnormalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);\n\n\tconst lineItems = ubl.lines.map((line) => ({\n\t\tdescription:\n\t\t\tnormalizeText(line.description) ??\n\t\t\tnormalizeText(line.itemName) ??\n\t\t\t\"Line item\",\n\t\tquantity: toNumberOrNull(line.quantity),\n\t\tunit: normalizeText(line.unitCode),\n\t\tunit_price: toNumberOrNull(line.unitPrice),\n\t\tamount: toNumberOrNull(line.lineExtensionAmount),\n\t\ttax_amount: toNumberOrNull(line.taxAmount),\n\t\ttax_rate: toNumberOrNull(line.taxPercent),\n\t\tproduct_code:\n\t\t\tnormalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),\n\t\tdiscount_amount: toNumberOrNull(line.discountAmount),\n\t\tperiod_start: parseDate(line.invoicePeriod?.startDate),\n\t\tperiod_end: parseDate(line.invoicePeriod?.endDate),\n\t\textra: {\n\t\t\tubl_line_id: normalizeText(line.id),\n\t\t\titem_name: normalizeText(line.itemName),\n\t\t\tsellers_item_id: normalizeText(line.sellersItemId),\n\t\t\tbuyers_item_id: normalizeText(line.buyersItemId),\n\t\t\ttax_category_id: normalizeText(line.taxCategoryId),\n\t\t\ttax_scheme_id: normalizeText(line.taxSchemeId),\n\t\t\ttax_subtotals: line.taxSubtotals ?? [],\n\t\t\tallowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),\n\t\t\tcharge_amount: toNumberOrNull(line.chargeAmount),\n\t\t\tmetadata: line.additionalItemProperties\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tline.additionalItemProperties.map((p) => [p.name, p.value]),\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t},\n\t}));\n\n\tconst supplierAddress = addressToString(ubl.seller.address);\n\tconst receiverAddress = addressToString(ubl.buyer.address);\n\tconst supplierAddressStructured = addressToStructured(ubl.seller.address);\n\tconst receiverAddressStructured = addressToStructured(ubl.buyer.address);\n\tconst attachmentMetadata = sanitizeAttachments(ubl.attachments);\n\tconst paymentMeansList =\n\t\tubl.paymentMeansList && ubl.paymentMeansList.length > 0\n\t\t\t? ubl.paymentMeansList\n\t\t\t: ubl.paymentMeans\n\t\t\t\t? [ubl.paymentMeans]\n\t\t\t\t: [];\n\n\tconst extracted: InvoiceExtractionDTO = {\n\t\tprovider: \"ubl_xml\",\n\t\tdocument_id: documentId,\n\t\tinvoice: {\n\t\t\tinvoice_number: normalizeText(ubl.id),\n\t\t\tinvoice_date: parseDate(ubl.issueDate),\n\t\t\tdue_date: parseDate(ubl.dueDate),\n\t\t\tperiod_start: parseDate(ubl.invoicePeriod?.startDate),\n\t\t\tperiod_end: parseDate(ubl.invoicePeriod?.endDate),\n\t\t\tcurrency,\n\t\t\tsubtotal,\n\t\t\ttax_total: taxTotal,\n\t\t\ttotal,\n\t\t\tamount_due: amountDue,\n\t\t\tamount_paid: amountPaid,\n\t\t\tdiscount_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges\n\t\t\t\t\t? toNumberOrNull(headerDiscountTotal)\n\t\t\t\t\t: null),\n\t\t\tshipping_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),\n\t\t\trounding_total: toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount),\n\t\t\tpayment_terms: paymentTerms,\n\t\t\tpo_number: poNumber,\n\t\t\tsupplier: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.seller.name) ??\n\t\t\t\t\tnormalizeText(ubl.seller.registrationName),\n\t\t\t\taddress: supplierAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.seller.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.seller.companyId),\n\t\t\t\tiban: normalizeText(ubl.paymentMeans?.iban),\n\t\t\t\tbic: normalizeText(ubl.paymentMeans?.bic),\n\t\t\t},\n\t\t\treceiver: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.buyer.name) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.registrationName),\n\t\t\t\taddress: receiverAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.buyer.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.companyId),\n\t\t\t},\n\t\t\textra: {\n\t\t\t\tdocument_type: ubl.documentType,\n\t\t\t\tcustomization_id: normalizeText(ubl.customizationId),\n\t\t\t\tprofile_id: normalizeText(ubl.profileId),\n\t\t\t\tinvoice_type_code: normalizeText(ubl.invoiceTypeCode),\n\t\t\t\tbuyer_reference: normalizeText(ubl.buyerReference),\n\t\t\t\torder_reference_id: normalizeText(ubl.orderReference),\n\t\t\t\tsales_order_id: normalizeText(ubl.salesOrderId),\n\t\t\t\tcontract_reference: normalizeText(ubl.contractReference),\n\t\t\t\tproject_reference: normalizeText(ubl.projectReference),\n\t\t\t\tbilling_reference: ubl.billingReference\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tinvoice_id: normalizeText(ubl.billingReference.invoiceId),\n\t\t\t\t\t\t\tinvoice_issue_date: parseDate(\n\t\t\t\t\t\t\t\tubl.billingReference.invoiceIssueDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\ttax_point_date: parseDate(ubl.taxPointDate),\n\t\t\t\tinvoice_period: ubl.invoicePeriod ?? null,\n\t\t\t\tnote: normalizeText(ubl.note),\n\t\t\t\tpayment_means: ubl.paymentMeans\n\t\t\t\t\t? sanitizePaymentMeans(ubl.paymentMeans)\n\t\t\t\t\t: null,\n\t\t\t\tpayment_means_list: paymentMeansList.map(sanitizePaymentMeans),\n\t\t\t\tdelivery: ubl.delivery\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tactual_delivery_date: parseDate(\n\t\t\t\t\t\t\t\tubl.delivery.actualDeliveryDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\taddress: addressToStructured(ubl.delivery.address),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tsupplier: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.seller.endpointId),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),\n\t\t\t\t\tregistration_name: normalizeText(ubl.seller.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.seller.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.seller.companyIdSchemeId),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.seller.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.seller.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.seller.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.seller.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.seller.contact?.email),\n\t\t\t\t},\n\t\t\t\treceiver: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.buyer.endpointId),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),\n\t\t\t\t\tregistration_name: normalizeText(ubl.buyer.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.buyer.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.buyer.companyIdSchemeId),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.buyer.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.buyer.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.buyer.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.buyer.contact?.email),\n\t\t\t\t},\n\t\t\t\tsupplier_address_structured: supplierAddressStructured,\n\t\t\t\treceiver_address_structured: receiverAddressStructured,\n\t\t\t\ttax_subtotals: ubl.taxSubtotals,\n\t\t\t\tallowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),\n\t\t\t\tattachments: attachmentMetadata,\n\t\t\t\tdocument_references: ubl.documentReferences ?? [],\n\t\t\t},\n\t\t},\n\t\tline_items: lineItems,\n\t\tconfidence: {\n\t\t\toverall: 1,\n\t\t\tfields: {\n\t\t\t\tinvoice_id: 1,\n\t\t\t\tinvoice_date: 1,\n\t\t\t\tdue_date: 1,\n\t\t\t\ttotal_amount: 1,\n\t\t\t\tsupplier_name: 1,\n\t\t\t},\n\t\t},\n\t};\n\n\treturn {\n\t\textracted,\n\t\trawPayload: {\n\t\t\tformat: \"ubl_xml\",\n\t\t\tinvoice: sanitizeRawUbl(ubl),\n\t\t},\n\t};\n};\n\n/**\n * Parse a UBL invoice from raw bytes and normalize it into a DTO.\n */\nexport const parseUblInvoiceDocument = (params: {\n\tbytes: Uint8Array;\n\tdocumentId: string;\n\tmimeType: string;\n}) => {\n\tconst xml = decodeXmlBytes(params.bytes);\n\tconst { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);\n\treturn {\n\t\trawPayload: {\n\t\t\t...rawPayload,\n\t\t\tmime_type: params.mimeType,\n\t\t},\n\t\textracted,\n\t\tproviderJobId: null as string | null,\n\t};\n};\n"],"mappings":";;;;;;;;AAMA,IAAa,gBAAb,cAAmC,MAAM;CACxC;CAEA,YAAY,SAAiB,SAA+B;EAC3D,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,IAAI,WAAW,WAAW,SAAS,KAAK,QAAQ,QAAQ;CACzD;AACD;;;ACXA,MAAa,SACZ;AACD,MAAa,SACZ;;;;;;AAOD,MAAa,gBAAgB,QAC5B,IAAI,QAAQ,uCAAuC,EAAE;;;;;;AAOtD,MAAa,oBAAoB,QAA0B;CAC1D,MAAM,UAAU,aAAa,GAAG;CAChC,MAAM,mBAAoB,WACxB;CACF,MAAM,SAAS,mBAAmB,IAAI,iBAAiB,IAAI,IAAIA,UAAa;CAC5E,IAAI;CACJ,IAAI;EACH,MAAM,OAAO,gBAAgB,SAAS,UAAU;CACjD,SAAS,OAAO;EACf,MAAM,IAA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;EACnB;EACA;EACA,eAAe;CAChB;AACD"}
1
+ {"version":3,"file":"index.js","names":["XmlDomParser","trimmed","cbcText","cacElement","cbcDirectText"],"sources":["../src/xml-dom.ts","../src/parser.ts","../src/attachments.ts","../src/mlr.ts","../src/normalize.ts"],"sourcesContent":["import { type Document, DOMParser as XmlDomParser } from \"@xmldom/xmldom\";\nimport { UblParseError } from \"./errors.js\";\n\nexport const CBC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nexport const CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove DOCTYPE\n * blocks (including inline DTD subsets) before parsing.\n */\nexport const stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\n/**\n * Parse XML into a DOM, preferring the host's `DOMParser` (browsers) and\n * falling back to @xmldom/xmldom. Throws {@link UblParseError} when the XML\n * is malformed.\n */\nexport const parseXmlDocument = (xml: string): Document => {\n\tconst safeXml = stripDoctype(xml);\n\tconst BrowserDomParser = (globalThis as { DOMParser?: typeof XmlDomParser })\n\t\t.DOMParser;\n\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\tlet doc: Document;\n\ttry {\n\t\tdoc = parser.parseFromString(safeXml, \"text/xml\");\n\t} catch (cause) {\n\t\tthrow new UblParseError(\"Malformed XML\", { cause });\n\t}\n\tif (doc.getElementsByTagName(\"parsererror\").length > 0 || !doc.documentElement) {\n\t\tthrow new UblParseError(\"Malformed XML\");\n\t}\n\treturn doc;\n};\n","import type { Element } from \"@xmldom/xmldom\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\n\tUblContact,\n\tUblDelivery,\n\tUblDocumentReference,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblItemProperty,\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblParty,\n\tUblPartyIdentification,\n\tUblPaymentMeans,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"./types.js\";\nimport { UblParseError } from \"./errors.js\";\nimport { CAC_NS, CBC_NS, parseXmlDocument } from \"./xml-dom.js\";\n\n// --- DOM helpers ---\n\nconst trimmed = (value: string | null | undefined): string | undefined => {\n\tconst text = value?.trim();\n\treturn text ? text : undefined;\n};\n\n/** First descendant CBC element's trimmed text; absent or blank is `undefined`. */\nfunction cbcText(parent: Element, tag: string): string | undefined {\n\treturn trimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);\n}\n\n/** Like {@link cbcText} but throws: the element is mandatory in EN 16931. */\nfunction requiredCbcText(parent: Element, tag: string, what: string): string {\n\tconst value = cbcText(parent, tag);\n\tif (value === undefined) throw new UblParseError(`Missing ${what} (cbc:${tag})`);\n\treturn value;\n}\n\nconst toNumber = (value: string | undefined): number | undefined => {\n\tif (value === undefined) return undefined;\n\tconst parsed = Number.parseFloat(value);\n\treturn Number.isNaN(parsed) ? undefined : parsed;\n};\n\nfunction cacElement(parent: Element, tag: string): Element | null {\n\treturn parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacElements(parent: Element, tag: string): Element[] {\n\treturn Array.from(parent.getElementsByTagNameNS(CAC_NS, tag));\n}\n\n/** First descendant CBC element as a number; absent or non-numeric is `undefined`. */\nfunction cbcNumber(parent: Element, tag: string): number | undefined {\n\treturn toNumber(cbcText(parent, tag));\n}\n\nfunction childElementsByTagNs(\n\tparent: Element,\n\tnamespace: string,\n\ttag: string,\n): Element[] {\n\tconst elements: Element[] = [];\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst element = node as Element;\n\t\tif (element.namespaceURI === namespace && element.localName === tag) {\n\t\t\telements.push(element);\n\t\t}\n\t}\n\treturn elements;\n}\n\nfunction cbcDirectText(parent: Element, tag: string): string | undefined {\n\treturn trimmed(childElementsByTagNs(parent, CBC_NS, tag)[0]?.textContent);\n}\n\nfunction cbcDirectNumber(parent: Element, tag: string): number | undefined {\n\treturn toNumber(cbcDirectText(parent, tag));\n}\n\nconst attribute = (el: Element | null | undefined, name: string): string | undefined =>\n\ttrimmed(el?.getAttribute(name));\n\nfunction cacDirectElement(parent: Element, tag: string): Element | null {\n\treturn childElementsByTagNs(parent, CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacDirectElements(parent: Element, tag: string): Element[] {\n\treturn childElementsByTagNs(parent, CAC_NS, tag);\n}\n\n// --- Section parsers ---\n\nfunction parseAddressFromElement(address: Element | null): UblAddress | undefined {\n\tif (!address) return undefined;\n\tconst country = cacElement(address, \"Country\");\n\treturn {\n\t\tstreet: cbcText(address, \"StreetName\"),\n\t\tadditionalStreet: cbcText(address, \"AdditionalStreetName\"),\n\t\tcity: cbcText(address, \"CityName\"),\n\t\tpostalZone: cbcText(address, \"PostalZone\"),\n\t\tcountrySubentity: cbcText(address, \"CountrySubentity\"),\n\t\tcountryCode: country ? cbcText(country, \"IdentificationCode\") : undefined,\n\t};\n}\n\nfunction parseAddress(party: Element): UblAddress | undefined {\n\tconst postal = cacElement(party, \"PostalAddress\");\n\treturn parseAddressFromElement(postal);\n}\n\nfunction parseTaxSchemeId(parent: Element | null): string | undefined {\n\tif (!parent) return undefined;\n\tconst taxScheme = cacElement(parent, \"TaxScheme\");\n\tif (!taxScheme) return undefined;\n\treturn cbcText(taxScheme, \"ID\");\n}\n\nfunction parseContact(party: Element): UblContact | undefined {\n\tconst contact = cacElement(party, \"Contact\");\n\tif (!contact) return undefined;\n\tconst name = cbcText(contact, \"Name\");\n\tconst phone = cbcText(contact, \"Telephone\");\n\tconst email = cbcText(contact, \"ElectronicMail\");\n\tif (!name && !phone && !email) return undefined;\n\treturn { name, phone, email };\n}\n\nfunction parsePartyIdentifications(party: Element): UblPartyIdentification[] {\n\tconst ids = cacElements(party, \"PartyIdentification\");\n\tconst result: UblPartyIdentification[] = [];\n\tfor (const idEl of ids) {\n\t\tconst idValue = cbcText(idEl, \"ID\");\n\t\tif (!idValue) continue;\n\t\tresult.push({\n\t\t\tid: idValue,\n\t\t\tschemeId: attribute(\n\t\t\t\tidEl.getElementsByTagNameNS(CBC_NS, \"ID\")[0],\n\t\t\t\t\"schemeID\",\n\t\t\t),\n\t\t});\n\t}\n\treturn result;\n}\n\nfunction parseParty(root: Element, role: string): UblParty {\n\tconst wrapper = cacElement(root, role);\n\tconst party = wrapper ? cacElement(wrapper, \"Party\") : null;\n\tif (!party) return {};\n\n\tconst partyName = cacElement(party, \"PartyName\");\n\tconst legalEntity = cacElement(party, \"PartyLegalEntity\");\n\tconst taxScheme = cacElement(party, \"PartyTaxScheme\");\n\tconst partyId = cacElement(party, \"PartyIdentification\");\n\tconst endpointEl = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tconst partyIdentifications = parsePartyIdentifications(party);\n\tconst companyIdEl = legalEntity\n\t\t? legalEntity.getElementsByTagNameNS(CBC_NS, \"CompanyID\")[0]\n\t\t: null;\n\n\tconst endpointValue = trimmed(endpointEl?.textContent);\n\tconst companyIdValue = companyIdEl\n\t\t? trimmed(companyIdEl.textContent)\n\t\t: partyId\n\t\t\t? cbcText(partyId, \"ID\")\n\t\t\t: undefined;\n\n\treturn {\n\t\tname: partyName ? cbcText(partyName, \"Name\") : undefined,\n\t\tregistrationName: legalEntity\n\t\t\t? cbcText(legalEntity, \"RegistrationName\")\n\t\t\t: undefined,\n\t\tcompanyLegalForm: legalEntity\n\t\t\t? cbcText(legalEntity, \"CompanyLegalForm\")\n\t\t\t: undefined,\n\t\tvatId: taxScheme ? cbcText(taxScheme, \"CompanyID\") : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxScheme),\n\t\tcompanyId:\n\t\t\tcompanyIdValue !== undefined\n\t\t\t\t? { value: companyIdValue, scheme: attribute(companyIdEl, \"schemeID\") }\n\t\t\t\t: undefined,\n\t\tendpoint:\n\t\t\tendpointValue !== undefined\n\t\t\t\t? { value: endpointValue, scheme: attribute(endpointEl, \"schemeID\") }\n\t\t\t\t: undefined,\n\t\tpartyIdentifications:\n\t\t\tpartyIdentifications.length > 0 ? partyIdentifications : undefined,\n\t\taddress: parseAddress(party),\n\t\tcontact: parseContact(party),\n\t};\n}\n\n/**\n * `cac:TaxCategory` / `cac:ClassifiedTaxCategory`. Emitted whenever the\n * element states anything; `percentFallback` covers the E-FFF habit of putting\n * `cbc:Percent` on the subtotal instead of inside the category.\n */\nfunction parseTaxCategory(\n\tcat: Element | null,\n\tpercentFallback?: Element,\n): UblTaxCategory | undefined {\n\tconst percentFromParent = percentFallback\n\t\t? cbcDirectNumber(percentFallback, \"Percent\")\n\t\t: undefined;\n\tif (!cat) {\n\t\treturn percentFromParent !== undefined\n\t\t\t? { percent: percentFromParent }\n\t\t\t: undefined;\n\t}\n\tconst category: UblTaxCategory = {\n\t\tid: cbcText(cat, \"ID\"),\n\t\tpercent: cbcNumber(cat, \"Percent\") ?? percentFromParent,\n\t\tschemeId: parseTaxSchemeId(cat),\n\t\texemptionReason: cbcText(cat, \"TaxExemptionReason\"),\n\t\texemptionReasonCode: cbcText(cat, \"TaxExemptionReasonCode\"),\n\t};\n\treturn Object.values(category).some((value) => value !== undefined)\n\t\t? category\n\t\t: undefined;\n}\n\nfunction parseTaxSubtotal(sub: Element): UblTaxSubtotal {\n\treturn {\n\t\ttaxableAmount: cbcNumber(sub, \"TaxableAmount\"),\n\t\ttaxAmount: cbcNumber(sub, \"TaxAmount\"),\n\t\tcategory: parseTaxCategory(cacElement(sub, \"TaxCategory\"), sub),\n\t};\n}\n\nfunction parseTaxSubtotalsFromTaxTotal(taxTotal: Element): UblTaxSubtotal[] {\n\treturn cacDirectElements(taxTotal, \"TaxSubtotal\").map(parseTaxSubtotal);\n}\n\n/**\n * `cac:TaxTotal` (BG-22). BT-110 is read from the first `cac:TaxTotal` as\n * stated, never summed from the subtotals; the subtotals of every `TaxTotal`\n * (a second one carries the accounting-currency figure) are concatenated.\n */\nfunction parseTaxTotal(root: Element): UblTaxTotal {\n\tconst taxTotals = cacDirectElements(root, \"TaxTotal\");\n\tconst first = taxTotals[0];\n\treturn {\n\t\ttaxAmount: first ? cbcDirectNumber(first, \"TaxAmount\") : undefined,\n\t\tsubtotals: taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal),\n\t};\n}\n\nfunction parseAllowanceCharge(charge: Element): UblAllowanceCharge {\n\tconst taxCategory = cacElement(charge, \"TaxCategory\");\n\tconst indicatorRaw = cbcDirectText(charge, \"ChargeIndicator\")?.toLowerCase();\n\tconst chargeIndicator = indicatorRaw === \"true\" || indicatorRaw === \"1\";\n\treturn {\n\t\tchargeIndicator,\n\t\tamount: cbcNumber(charge, \"Amount\"),\n\t\tbaseAmount: cbcDirectNumber(charge, \"BaseAmount\"),\n\t\tmultiplierFactorNumeric: cbcDirectNumber(charge, \"MultiplierFactorNumeric\"),\n\t\treason: cbcText(charge, \"AllowanceChargeReason\"),\n\t\treasonCode: cbcText(charge, \"AllowanceChargeReasonCode\"),\n\t\ttaxCategory: parseTaxCategory(taxCategory),\n\t};\n}\n\nfunction parseAllowanceCharges(parent: Element): UblAllowanceCharge[] {\n\treturn cacDirectElements(parent, \"AllowanceCharge\").map(parseAllowanceCharge);\n}\n\nfunction mergeTaxCategories(\n\tpreferred: UblTaxCategory | undefined,\n\tfallback: UblTaxCategory | undefined,\n): UblTaxCategory | undefined {\n\tif (!preferred) return fallback;\n\tif (!fallback) return preferred;\n\treturn {\n\t\tid: preferred.id ?? fallback.id,\n\t\tpercent: preferred.percent ?? fallback.percent,\n\t\tschemeId: preferred.schemeId ?? fallback.schemeId,\n\t\texemptionReason: preferred.exemptionReason ?? fallback.exemptionReason,\n\t\texemptionReasonCode:\n\t\t\tpreferred.exemptionReasonCode ?? fallback.exemptionReasonCode,\n\t};\n}\n\nfunction parseLines(root: Element, isCreditNote: boolean): UblLine[] {\n\tconst qtyTag = isCreditNote ? \"CreditedQuantity\" : \"InvoicedQuantity\";\n\tconst lineTag = isCreditNote ? \"CreditNoteLine\" : \"InvoiceLine\";\n\n\treturn cacElements(root, lineTag).map((line) => {\n\t\tconst item = cacElement(line, \"Item\");\n\t\tconst price = cacElement(line, \"Price\");\n\t\tconst classifiedCategory = parseTaxCategory(\n\t\t\titem ? cacElement(item, \"ClassifiedTaxCategory\") : null,\n\t\t);\n\t\tconst sellersId = item ? cacElement(item, \"SellersItemIdentification\") : null;\n\t\tconst buyersId = item ? cacElement(item, \"BuyersItemIdentification\") : null;\n\t\tconst qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];\n\t\tconst lineExtensionAmount = cbcNumber(line, \"LineExtensionAmount\");\n\t\tconst lineTaxTotal = cacDirectElement(line, \"TaxTotal\");\n\t\tconst lineTaxSubtotals = lineTaxTotal\n\t\t\t? parseTaxSubtotalsFromTaxTotal(lineTaxTotal)\n\t\t\t: [];\n\t\tconst taxAmountFromSubtotals = lineTaxSubtotals.reduce(\n\t\t\t(sum, subtotal) => sum + (subtotal.taxAmount ?? 0),\n\t\t\t0,\n\t\t);\n\t\tconst taxAmountFromLineTotal = lineTaxTotal\n\t\t\t? cbcDirectNumber(lineTaxTotal, \"TaxAmount\")\n\t\t\t: undefined;\n\t\t// A line-level TaxSubtotal (E-FFF) wins over the classified category,\n\t\t// field by field.\n\t\tconst subtotalCategory = lineTaxSubtotals[0]?.category;\n\t\tconst taxCategory = mergeTaxCategories(subtotalCategory, classifiedCategory);\n\t\tconst taxPercent = taxCategory?.percent;\n\t\tconst computedTaxAmount =\n\t\t\ttaxPercent !== undefined && lineExtensionAmount !== undefined\n\t\t\t\t? Number(((lineExtensionAmount * taxPercent) / 100).toFixed(2))\n\t\t\t\t: undefined;\n\t\tconst lineAllowanceCharges = parseAllowanceCharges(line);\n\t\tconst priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];\n\t\tconst allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];\n\t\tconst discountAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0),\n\t\t\t0,\n\t\t);\n\t\tconst chargeAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum + Math.abs(charge.amount ?? 0) : sum,\n\t\t\t0,\n\t\t);\n\n\t\tconst additionalItemProperties: UblItemProperty[] = [];\n\t\tif (item) {\n\t\t\tfor (const prop of cacElements(item, \"AdditionalItemProperty\")) {\n\t\t\t\tconst propName = cbcText(prop, \"Name\");\n\t\t\t\tconst propValue = cbcText(prop, \"Value\");\n\t\t\t\tif (propName) {\n\t\t\t\t\tadditionalItemProperties.push({\n\t\t\t\t\t\tname: propName,\n\t\t\t\t\t\tvalue: propValue,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// EN16931 BT-146 (PriceAmount) is the price for BT-149 (BaseQuantity) units\n\t\t// of the item, not necessarily for one unit. Effective unit price is\n\t\t// PriceAmount / BaseQuantity, with BaseQuantity defaulting to 1 when absent.\n\t\tconst priceAmount = price ? cbcNumber(price, \"PriceAmount\") : undefined;\n\t\tconst priceBaseQuantity = price\n\t\t\t? cbcDirectNumber(price, \"BaseQuantity\")\n\t\t\t: undefined;\n\t\tconst unitPrice =\n\t\t\tpriceAmount !== undefined && priceBaseQuantity && priceBaseQuantity > 0\n\t\t\t\t? priceAmount / priceBaseQuantity\n\t\t\t\t: priceAmount;\n\n\t\treturn {\n\t\t\tid: requiredCbcText(line, \"ID\", `${lineTag} identifier`),\n\t\t\tdescription: item ? cbcText(item, \"Description\") : undefined,\n\t\t\tquantity: cbcNumber(line, qtyTag),\n\t\t\tunitCode: attribute(qtyEl, \"unitCode\"),\n\t\t\tunitPrice,\n\t\t\tlineExtensionAmount,\n\t\t\tbaseQuantity: priceBaseQuantity,\n\t\t\ttaxCategory,\n\t\t\ttaxAmount:\n\t\t\t\ttaxAmountFromLineTotal ??\n\t\t\t\t(lineTaxSubtotals.length > 0\n\t\t\t\t\t? taxAmountFromSubtotals\n\t\t\t\t\t: computedTaxAmount),\n\t\t\ttaxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : undefined,\n\t\t\tallowanceCharges:\n\t\t\t\tallowanceCharges.length > 0 ? allowanceCharges : undefined,\n\t\t\tdiscountAmount: discountAmount > 0 ? discountAmount : undefined,\n\t\t\tchargeAmount: chargeAmount > 0 ? chargeAmount : undefined,\n\t\t\titemName: item ? cbcText(item, \"Name\") : undefined,\n\t\t\tsellersItemId: sellersId ? cbcText(sellersId, \"ID\") : undefined,\n\t\t\tbuyersItemId: buyersId ? cbcText(buyersId, \"ID\") : undefined,\n\t\t\tadditionalItemProperties:\n\t\t\t\tadditionalItemProperties.length > 0\n\t\t\t\t\t? additionalItemProperties\n\t\t\t\t\t: undefined,\n\t\t\tinvoicePeriod: parseInvoicePeriod(line),\n\t\t};\n\t});\n}\n\nfunction parseMonetaryTotal(root: Element): UblMonetaryTotal {\n\tconst total = cacDirectElement(root, \"LegalMonetaryTotal\");\n\tif (!total) return {};\n\treturn {\n\t\tlineExtensionAmount: cbcNumber(total, \"LineExtensionAmount\"),\n\t\ttaxExclusiveAmount: cbcNumber(total, \"TaxExclusiveAmount\"),\n\t\ttaxInclusiveAmount: cbcNumber(total, \"TaxInclusiveAmount\"),\n\t\tallowanceTotalAmount: cbcNumber(total, \"AllowanceTotalAmount\"),\n\t\tchargeTotalAmount: cbcNumber(total, \"ChargeTotalAmount\"),\n\t\tprepaidAmount: cbcNumber(total, \"PrepaidAmount\"),\n\t\tpayableRoundingAmount: cbcNumber(total, \"PayableRoundingAmount\"),\n\t\tpayableAmount: cbcNumber(total, \"PayableAmount\"),\n\t};\n}\n\nfunction parsePaymentMeansElement(pm: Element): UblPaymentMeans {\n\tconst account = cacElement(pm, \"PayeeFinancialAccount\");\n\tconst branch = account ? cacElement(account, \"FinancialInstitutionBranch\") : null;\n\tconst paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, \"PaymentMeansCode\")[0];\n\tconst mandate = cacElement(pm, \"PaymentMandate\");\n\n\treturn {\n\t\tcode: cbcText(pm, \"PaymentMeansCode\"),\n\t\tcodeName: attribute(paymentMeansCodeEl, \"name\"),\n\t\tpaymentId: cbcText(pm, \"PaymentID\"),\n\t\tiban: account ? cbcText(account, \"ID\") : undefined,\n\t\tbic: branch ? cbcText(branch, \"ID\") : undefined,\n\t\taccountName: account ? cbcText(account, \"Name\") : undefined,\n\t\tmandateId: mandate ? cbcText(mandate, \"ID\") : undefined,\n\t};\n}\n\nfunction parsePaymentMeansList(root: Element): UblPaymentMeans[] | undefined {\n\tconst list = cacElements(root, \"PaymentMeans\").map(parsePaymentMeansElement);\n\treturn list.length > 0 ? list : undefined;\n}\n\n/**\n * BT-73/BT-74 on a document, BT-134/BT-135 on a line. Direct children only:\n * a descendant search on the document root would report the first line's\n * period as the document's whenever the document states none of its own.\n */\nfunction parseInvoicePeriod(parent: Element): UblInvoicePeriod | undefined {\n\tconst period = cacDirectElement(parent, \"InvoicePeriod\");\n\tif (!period) return undefined;\n\n\tconst start = cbcText(period, \"StartDate\");\n\tconst end = cbcText(period, \"EndDate\");\n\tif (!start && !end) return undefined;\n\n\treturn {\n\t\tstartDate: start,\n\t\tendDate: end,\n\t\tdescriptionCode: cbcText(period, \"DescriptionCode\"),\n\t};\n}\n\nfunction parseDelivery(root: Element): UblDelivery | undefined {\n\tconst delivery = cacElement(root, \"Delivery\");\n\tif (!delivery) return undefined;\n\tconst actualDeliveryDate = cbcText(delivery, \"ActualDeliveryDate\");\n\tconst deliveryLocation = cacElement(delivery, \"DeliveryLocation\");\n\tconst address = parseAddressFromElement(\n\t\tdeliveryLocation ? cacElement(deliveryLocation, \"Address\") : null,\n\t);\n\tif (!actualDeliveryDate && !address) return undefined;\n\treturn {\n\t\tactualDeliveryDate,\n\t\taddress,\n\t};\n}\n\nfunction parsePaymentTermsNote(root: Element): string | undefined {\n\tconst paymentTerms = cacElement(root, \"PaymentTerms\");\n\tif (!paymentTerms) return undefined;\n\treturn cbcText(paymentTerms, \"Note\");\n}\n\nfunction parseNotes(root: Element): string | undefined {\n\tconst noteEls = root.getElementsByTagNameNS(CBC_NS, \"Note\");\n\tconst notes: string[] = [];\n\tfor (let i = 0; i < noteEls.length; i++) {\n\t\tconst el = noteEls[i];\n\t\tif (!el) continue;\n\t\tif (el.parentElement === root || el.parentNode === root) {\n\t\t\tconst text = el.textContent?.trim();\n\t\t\tif (text) notes.push(text);\n\t\t}\n\t}\n\treturn notes.length > 0 ? notes.join(\"\\n\") : undefined;\n}\n\nfunction parseAttachments(root: Element): {\n\tattachments: UblAttachment[] | undefined;\n\tdocumentReferences: UblDocumentReference[] | undefined;\n} {\n\tconst refs = cacElements(root, \"AdditionalDocumentReference\");\n\tconst attachments: UblAttachment[] = [];\n\tconst documentReferences: UblDocumentReference[] = [];\n\n\tfor (const ref of refs) {\n\t\tconst attachment = cacElement(ref, \"Attachment\");\n\t\tconst refId = cbcText(ref, \"ID\");\n\t\tconst description = cbcText(ref, \"DocumentDescription\");\n\n\t\tif (!attachment) {\n\t\t\t// Text-only document reference (e.g. terms & conditions, notices)\n\t\t\tif (refId || description) {\n\t\t\t\tdocumentReferences.push({ id: refId, description });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst binaryEl = attachment.getElementsByTagNameNS(\n\t\t\tCBC_NS,\n\t\t\t\"EmbeddedDocumentBinaryObject\",\n\t\t)[0];\n\t\tconst externalRef = cacElement(attachment, \"ExternalReference\");\n\n\t\tif (binaryEl) {\n\t\t\tconst content = binaryEl.textContent?.trim();\n\t\t\tif (content) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tfilename: attribute(binaryEl, \"filename\"),\n\t\t\t\t\tmimeCode: attribute(binaryEl, \"mimeCode\"),\n\t\t\t\t\tdescription,\n\t\t\t\t\tbase64Content: content,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (externalRef) {\n\t\t\tconst uri = cbcText(externalRef, \"URI\");\n\t\t\tif (uri) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tdescription,\n\t\t\t\t\texternalUri: uri,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tattachments: attachments.length > 0 ? attachments : undefined,\n\t\tdocumentReferences:\n\t\t\tdocumentReferences.length > 0 ? documentReferences : undefined,\n\t};\n}\n\nfunction parseBillingReference(root: Element): UblBillingReference | undefined {\n\tconst billingRef = cacElement(root, \"BillingReference\");\n\tif (!billingRef) return undefined;\n\tconst invoiceRef = cacElement(billingRef, \"InvoiceDocumentReference\");\n\tif (!invoiceRef) return undefined;\n\tconst invoiceId = cbcText(invoiceRef, \"ID\");\n\tconst invoiceIssueDate = cbcText(invoiceRef, \"IssueDate\");\n\tif (!invoiceId && !invoiceIssueDate) return undefined;\n\treturn { invoiceId, invoiceIssueDate };\n}\n\n// --- Main parser ---\n\n/**\n * Drop `undefined`-valued keys recursively so an absent field is an absent\n * key, not a key holding `undefined`. Arrays keep their order and length.\n */\nfunction omitUndefined<T>(value: T): T {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(omitUndefined) as T;\n\t}\n\tif (value !== null && typeof value === \"object\") {\n\t\tconst out: Record<string, unknown> = {};\n\t\tfor (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n\t\t\tif (entry !== undefined) out[key] = omitUndefined(entry);\n\t\t}\n\t\treturn out as T;\n\t}\n\treturn value;\n}\n\nconst INVOICE_NS = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nconst CREDIT_NOTE_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\n\n/**\n * Parse a UBL 2.1 Invoice or CreditNote.\n *\n * Returns `null` when the XML is well-formed but its root is not a UBL\n * `Invoice`/`CreditNote`. Throws {@link UblParseError} when the XML is\n * malformed or the document lacks an element EN 16931 makes mandatory\n * (document id, issue date, currency, line id).\n */\nexport function parseUblInvoice(xml: string): UblInvoice | null {\n\tconst doc = parseXmlDocument(xml);\n\tconst root = doc.documentElement;\n\tif (!root) return null;\n\n\tlet documentType: \"Invoice\" | \"CreditNote\";\n\tif (root.localName === \"Invoice\" && root.namespaceURI === INVOICE_NS) {\n\t\tdocumentType = \"Invoice\";\n\t} else if (\n\t\troot.localName === \"CreditNote\" &&\n\t\troot.namespaceURI === CREDIT_NOTE_NS\n\t) {\n\t\tdocumentType = \"CreditNote\";\n\t} else {\n\t\treturn null;\n\t}\n\n\tconst isCreditNote = documentType === \"CreditNote\";\n\tconst id = requiredCbcText(root, \"ID\", \"document identifier\");\n\tconst issueDate = requiredCbcText(root, \"IssueDate\", \"issue date\");\n\tconst currency = requiredCbcText(root, \"DocumentCurrencyCode\", \"currency code\");\n\tconst paymentMeansList = parsePaymentMeansList(root);\n\tconst orderReference = cacElement(root, \"OrderReference\");\n\tconst contractReference = cacElement(root, \"ContractDocumentReference\");\n\tconst projectReference = cacElement(root, \"ProjectReference\");\n\tconst { attachments, documentReferences } = parseAttachments(root);\n\n\treturn omitUndefined<UblInvoice>({\n\t\tdocumentType,\n\t\tcustomizationId: cbcText(root, \"CustomizationID\"),\n\t\tprofileId: cbcText(root, \"ProfileID\"),\n\t\tid,\n\t\tinvoiceTypeCode:\n\t\t\tcbcText(root, \"InvoiceTypeCode\") ?? cbcText(root, \"CreditNoteTypeCode\"),\n\t\tissueDate,\n\t\tdueDate: cbcText(root, \"DueDate\"),\n\t\ttaxPointDate: cbcText(root, \"TaxPointDate\"),\n\t\tcurrency,\n\t\tbuyerReference: cbcText(root, \"BuyerReference\"),\n\t\torderReference: orderReference ? cbcText(orderReference, \"ID\") : undefined,\n\t\tsalesOrderId: orderReference\n\t\t\t? cbcText(orderReference, \"SalesOrderID\")\n\t\t\t: undefined,\n\t\tcontractReference: contractReference\n\t\t\t? cbcText(contractReference, \"ID\")\n\t\t\t: undefined,\n\t\tprojectReference: projectReference\n\t\t\t? cbcText(projectReference, \"ID\")\n\t\t\t: undefined,\n\t\tbillingReference: parseBillingReference(root),\n\t\tseller: parseParty(root, \"AccountingSupplierParty\"),\n\t\tbuyer: parseParty(root, \"AccountingCustomerParty\"),\n\t\tdelivery: parseDelivery(root),\n\t\tlines: parseLines(root, isCreditNote),\n\t\ttaxTotal: parseTaxTotal(root),\n\t\tmonetaryTotal: parseMonetaryTotal(root),\n\t\tpaymentMeansList,\n\t\tpaymentMeans: paymentMeansList?.[0],\n\t\tinvoicePeriod: parseInvoicePeriod(root),\n\t\tnote: parseNotes(root),\n\t\tpaymentTermsNote: parsePaymentTermsNote(root),\n\t\tattachments,\n\t\tdocumentReferences,\n\t\tallowanceCharges: parseAllowanceCharges(root),\n\t});\n}\n","import { UblParseError } from \"./errors.js\";\nimport { parseUblInvoice } from \"./parser.js\";\nimport type { UblAttachment } from \"./types.js\";\n\n/**\n * An embedded attachment extracted from a UBL document's\n * `AdditionalDocumentReference` entries, with its binary content still\n * base64-encoded. `sizeBytes` is the decoded size.\n */\nexport interface UblEmbeddedAttachment {\n\tid?: string | undefined;\n\tfilename: string;\n\tmimeCode: string;\n\tsizeBytes: number;\n\t/** Zero-based position among the document's embedded attachments. */\n\tlineOrder: number;\n\tbase64Content: string;\n}\n\n/** Decoded byte length of a base64 string, accounting for `=` padding. */\nexport const base64DecodedSize = (base64: string): number => {\n\tconst sanitized = base64.replace(/\\s+/g, \"\");\n\tif (!sanitized) return 0;\n\tconst padding = sanitized.endsWith(\"==\") ? 2 : sanitized.endsWith(\"=\") ? 1 : 0;\n\treturn Math.floor((sanitized.length * 3) / 4) - padding;\n};\n\n/**\n * Extract the embedded attachments (typically the human-readable PDF) from a\n * UBL invoice or credit note XML. Attachments referenced only by external URI\n * (no `EmbeddedDocumentBinaryObject`) are skipped; use {@link parseUblInvoice}\n * directly when those matter.\n *\n * @throws {UblParseError} when the XML is malformed or not a UBL invoice.\n */\nexport const extractUblEmbeddedAttachments = (xml: string): UblEmbeddedAttachment[] => {\n\tconst parsed = parseUblInvoice(xml);\n\tif (!parsed) throw new UblParseError(\"Document is not a UBL Invoice or CreditNote\");\n\tif (!parsed.attachments || parsed.attachments.length === 0) return [];\n\n\treturn parsed.attachments\n\t\t.map((attachment, index): UblEmbeddedAttachment | null => {\n\t\t\tconst base64Content = attachment.base64Content?.trim();\n\t\t\tif (!base64Content) return null;\n\t\t\treturn {\n\t\t\t\tid: attachment.id,\n\t\t\t\tfilename: attachment.filename ?? `attachment-${index + 1}`,\n\t\t\t\tmimeCode: attachment.mimeCode ?? \"application/octet-stream\",\n\t\t\t\tsizeBytes: base64DecodedSize(base64Content),\n\t\t\t\tlineOrder: index,\n\t\t\t\tbase64Content,\n\t\t\t};\n\t\t})\n\t\t.filter((entry): entry is UblEmbeddedAttachment => entry !== null);\n};\n\n/**\n * Whether an attachment looks like a PDF, by MIME type first and filename\n * extension as a fallback.\n */\nexport const isPdfLikeAttachment = (\n\tattachment: Pick<UblAttachment, \"filename\" | \"mimeCode\">,\n): boolean => {\n\tconst mimeCode = attachment.mimeCode?.toLowerCase() ?? \"\";\n\tif (mimeCode === \"application/pdf\" || mimeCode.endsWith(\"/pdf\")) return true;\n\treturn attachment.filename?.toLowerCase().endsWith(\".pdf\") ?? false;\n};\n","import type { Element } from \"@xmldom/xmldom\";\nimport { UblParseError } from \"./errors.js\";\nimport { CAC_NS, CBC_NS, parseXmlDocument } from \"./xml-dom.js\";\n\n/**\n * Peppol BIS MLR (Message Level Response) document-type identifier value\n * (Peppol `busdox-docid-qns` scheme).\n */\nexport const PEPPOL_MLR_DOCUMENT_TYPE_VALUE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1\";\n\n/** Peppol BIS MLR process identifier value. */\nexport const PEPPOL_MLR_PROCESS_VALUE = \"urn:fdc:peppol.eu:poacc:bis:mlr:3\";\n\n/**\n * A parsed Peppol Message Level Response (a UBL `ApplicationResponse`). Every\n * field is optional: a given MLR may omit any of them, and an omitted field is\n * an absent key.\n */\nexport interface PeppolMessageLevelResponse {\n\tcustomizationId?: string | undefined;\n\tprofileId?: string | undefined;\n\tresponseId?: string | undefined;\n\tissueDate?: string | undefined;\n\tissueTime?: string | undefined;\n\treferencedDocumentId?: string | undefined;\n\tresponseCode?: string | undefined;\n\tdescription?: string | undefined;\n\t/** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */\n\tsenderIdentifier?: string | undefined;\n\t/** Receiver participant id as `schemeID:value`. */\n\treceiverIdentifier?: string | undefined;\n}\n\nconst trimmed = (value: string | null | undefined): string | undefined => {\n\tconst text = value?.trim();\n\treturn text ? text : undefined;\n};\n\n/** First descendant CBC element's trimmed text, or undefined. */\nconst cbcText = (parent: Element, tag: string): string | undefined =>\n\ttrimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);\n\n/**\n * First direct-child CBC element's trimmed text, or null. Used for the\n * top-level scalars so a nested `cbc:ID` (e.g. inside DocumentReference) cannot\n * shadow the ApplicationResponse's own id.\n */\nconst cbcDirectText = (parent: Element, tag: string): string | undefined => {\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst el = node as Element;\n\t\tif (el.namespaceURI === CBC_NS && el.localName === tag) {\n\t\t\treturn trimmed(el.textContent);\n\t\t}\n\t}\n\treturn undefined;\n};\n\n/** First descendant CAC element, or null. */\nconst cacElement = (parent: Element, tag: string): Element | null =>\n\tparent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n\n/**\n * The Peppol participant identifier of a SenderParty / ReceiverParty, rendered\n * as `schemeID:value` when the EndpointID carries a scheme and the value does\n * not already include one, otherwise the raw value.\n */\nconst endpointIdentifier = (party: Element | null): string | undefined => {\n\tif (!party) return undefined;\n\tconst endpoint = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tif (!endpoint) return undefined;\n\tconst id = trimmed(endpoint.textContent);\n\tconst scheme = endpoint.getAttribute(\"schemeID\");\n\tif (scheme && id && !id.includes(\":\")) return `${scheme}:${id}`;\n\treturn id;\n};\n\n/**\n * Locate the `ApplicationResponse` element, unwrapping a Standard Business\n * Document (SBDH) envelope when present. Returns null when the XML contains no\n * ApplicationResponse; throws {@link UblParseError} when it is malformed.\n */\nconst findApplicationResponse = (xml: string): Element | null => {\n\tconst doc = parseXmlDocument(xml);\n\tconst root = doc.documentElement;\n\tif (!root) return null;\n\tif (root.localName === \"ApplicationResponse\") return root;\n\tconst candidates = root.getElementsByTagName(\"*\");\n\tfor (let i = 0; i < candidates.length; i++) {\n\t\tconst el = candidates[i];\n\t\tif (el?.localName === \"ApplicationResponse\") return el;\n\t}\n\treturn null;\n};\n\n/**\n * Whether an inbound document is a Peppol Message Level Response, identified by\n * its document-type value, its process value, or by parsing the XML and finding\n * an `ApplicationResponse` root (SBDH-wrapped or not).\n */\nexport const isPeppolMessageLevelResponse = (params: {\n\tdocumentTypeValue?: string | null;\n\tprocessValue?: string | null;\n\txml?: string | null;\n}): boolean => {\n\tif (trimmed(params.documentTypeValue) === PEPPOL_MLR_DOCUMENT_TYPE_VALUE) {\n\t\treturn true;\n\t}\n\tif (trimmed(params.processValue) === PEPPOL_MLR_PROCESS_VALUE) return true;\n\tconst xml = trimmed(params.xml);\n\tif (!xml) return false;\n\ttry {\n\t\treturn findApplicationResponse(xml) !== null;\n\t} catch (error) {\n\t\t// A sniff answers \"is this an MLR?\"; malformed XML is simply \"no\".\n\t\tif (error instanceof UblParseError) return false;\n\t\tthrow error;\n\t}\n};\n\n/**\n * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping\n * an SBDH envelope when present. Throws {@link UblParseError} when the XML is\n * malformed or is not an ApplicationResponse.\n */\nexport const parsePeppolMessageLevelResponse = (\n\txml: string,\n): PeppolMessageLevelResponse => {\n\tconst root = findApplicationResponse(xml);\n\tif (!root) {\n\t\tthrow new UblParseError(\"Document is not a Peppol Message Level Response\");\n\t}\n\n\tconst documentResponse = cacElement(root, \"DocumentResponse\");\n\tconst response = documentResponse ? cacElement(documentResponse, \"Response\") : null;\n\tconst documentReference = documentResponse\n\t\t? cacElement(documentResponse, \"DocumentReference\")\n\t\t: null;\n\n\treturn {\n\t\tcustomizationId: cbcDirectText(root, \"CustomizationID\"),\n\t\tprofileId: cbcDirectText(root, \"ProfileID\"),\n\t\tresponseId: cbcDirectText(root, \"ID\"),\n\t\tissueDate: cbcDirectText(root, \"IssueDate\"),\n\t\tissueTime: cbcDirectText(root, \"IssueTime\"),\n\t\treferencedDocumentId: documentReference\n\t\t\t? cbcText(documentReference, \"ID\")\n\t\t\t: undefined,\n\t\tresponseCode: response ? cbcText(response, \"ResponseCode\") : undefined,\n\t\tdescription: response ? cbcText(response, \"Description\") : undefined,\n\t\tsenderIdentifier: endpointIdentifier(cacElement(root, \"SenderParty\")),\n\t\treceiverIdentifier: endpointIdentifier(cacElement(root, \"ReceiverParty\")),\n\t};\n};\n","import { base64DecodedSize } from \"./attachments.js\";\nimport { UblParseError } from \"./errors.js\";\nimport { parseUblInvoice } from \"./parser.js\";\nimport type {\n\tInvoiceExtractionDTO,\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblInvoice,\n\tUblPaymentMeans,\n} from \"./types.js\";\n\n// --- Utility helpers ---\n\nconst UTF8_BOM = 0xfeff;\n\n/** `null` for an absent value or an \"N/A\" placeholder written by the sender. */\nconst normalizeText = (value: string | undefined): string | null => {\n\tif (value === undefined) return null;\n\tconst upper = value.toUpperCase();\n\tif (upper === \"NA\" || upper === \"N/A\") return null;\n\treturn value;\n};\n\nconst toNumberOrNull = (value: number | undefined): number | null =>\n\tvalue !== undefined && Number.isFinite(value) ? value : null;\n\nconst roundToCents = (value: number): number => Math.round(value * 100) / 100;\n\nexport const normalizeCurrency = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\treturn trimmed.toUpperCase();\n};\n\nexport const parseDate = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst timestamp = Date.parse(trimmed);\n\tif (Number.isNaN(timestamp)) return null;\n\tconst iso = new Date(timestamp).toISOString();\n\treturn iso.slice(0, 10);\n};\n\nconst sanitizePaymentMeans = (pm: UblPaymentMeans) => ({\n\tcode: normalizeText(pm.code),\n\tcode_name: normalizeText(pm.codeName),\n\tpayment_id: normalizeText(pm.paymentId),\n\tiban: normalizeText(pm.iban),\n\tbic: normalizeText(pm.bic),\n\taccount_name: normalizeText(pm.accountName),\n\tmandate_id: normalizeText(pm.mandateId),\n});\n\n// --- Address helpers ---\n\nconst present = (part: string | undefined): part is string => part !== undefined;\n\nconst joinStreet = (address: UblAddress): string =>\n\t[address.street, address.additionalStreet].filter(present).join(\" \");\n\nconst addressToString = (address?: UblAddress): string | null => {\n\tif (!address) return null;\n\tconst street = joinStreet(address);\n\tconst cityLine = [address.postalZone, address.city].filter(present).join(\" \");\n\tconst countryLine = [address.countrySubentity, address.countryCode]\n\t\t.filter(present)\n\t\t.join(\" \");\n\tconst lines = [street, cityLine, countryLine].filter((line) => line.length > 0);\n\treturn lines.length > 0 ? lines.join(\"\\n\") : null;\n};\n\nconst addressToStructured = (address?: UblAddress) => {\n\tif (!address) return null;\n\tconst line1 = joinStreet(address);\n\tconst result = {\n\t\tline1: line1 ? normalizeText(line1) : null,\n\t\tline2: null as string | null,\n\t\tcity: normalizeText(address.city),\n\t\tstate: normalizeText(address.countrySubentity),\n\t\tpostal_code: normalizeText(address.postalZone),\n\t\tcountry: normalizeText(address.countryCode),\n\t};\n\tconst hasValue = Object.values(result).some((value) => value);\n\treturn hasValue ? result : null;\n};\n\n// --- Attachment & charge sanitizers ---\n\nconst sanitizeAttachments = (attachments?: UblAttachment[]) =>\n\t(attachments ?? []).map((attachment) => ({\n\t\tid: normalizeText(attachment.id),\n\t\tfilename: normalizeText(attachment.filename),\n\t\tmime_code: normalizeText(attachment.mimeCode),\n\t\tdescription: normalizeText(attachment.description),\n\t\tsize_bytes:\n\t\t\tattachment.base64Content !== undefined\n\t\t\t\t? base64DecodedSize(attachment.base64Content)\n\t\t\t\t: null,\n\t\texternal_uri: normalizeText(attachment.externalUri),\n\t}));\n\nconst sanitizeAllowanceCharges = (charges?: UblAllowanceCharge[]) =>\n\t(charges ?? []).map((charge) => ({\n\t\tcharge_indicator: charge.chargeIndicator,\n\t\tamount: toNumberOrNull(charge.amount),\n\t\tbase_amount: toNumberOrNull(charge.baseAmount),\n\t\tmultiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),\n\t\treason: normalizeText(charge.reason),\n\t\treason_code: normalizeText(charge.reasonCode),\n\t\ttax_percent: toNumberOrNull(charge.taxCategory?.percent),\n\t\ttax_category_id: normalizeText(charge.taxCategory?.id),\n\t\ttax_scheme_id: normalizeText(charge.taxCategory?.schemeId),\n\t}));\n\nconst sanitizeRawUbl = (ubl: UblInvoice) => ({\n\t...ubl,\n\tattachments: sanitizeAttachments(ubl.attachments),\n\tdocumentReferences: ubl.documentReferences ?? [],\n});\n\n// --- Summation helpers ---\n\nconst sumTaxTotal = (ubl: UblInvoice): number | null => {\n\tconst { subtotals } = ubl.taxTotal;\n\tconst subtotalSum = subtotals.reduce(\n\t\t(sum, subtotal) => sum + (subtotal.taxAmount ?? 0),\n\t\t0,\n\t);\n\tif (subtotals.length > 0 && Number.isFinite(subtotalSum)) {\n\t\treturn subtotalSum;\n\t}\n\tconst { taxInclusiveAmount, taxExclusiveAmount } = ubl.monetaryTotal;\n\tif (taxInclusiveAmount === undefined || taxExclusiveAmount === undefined) {\n\t\treturn null;\n\t}\n\treturn taxInclusiveAmount - taxExclusiveAmount;\n};\n\nconst sumAllowanceChargesByType = (\n\tcharges: UblAllowanceCharge[] | undefined,\n\tchargeIndicator: boolean,\n) =>\n\t(charges ?? []).reduce((sum, charge) => {\n\t\tif (charge.chargeIndicator !== chargeIndicator) return sum;\n\t\treturn sum + Math.abs(charge.amount ?? 0);\n\t}, 0);\n\n// --- Public API ---\n\n/**\n * Decode raw XML bytes, stripping an optional UTF-8 BOM.\n */\nexport const decodeXmlBytes = (bytes: Uint8Array): string => {\n\tconst text = new TextDecoder(\"utf-8\").decode(bytes);\n\treturn text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;\n};\n\n/**\n * Parse a UBL XML string and normalize it into a flat DTO suitable for\n * database storage or API responses.\n *\n * @throws {UblParseError} when the XML is malformed, not a UBL invoice, or\n * lacks a mandatory element.\n */\nexport const normalizeUblResponse = (\n\txml: string,\n\tdocumentId: string,\n): {\n\textracted: InvoiceExtractionDTO;\n\trawPayload: Record<string, unknown>;\n} => {\n\tconst ubl = parseUblInvoice(xml);\n\tif (!ubl) {\n\t\tthrow new UblParseError(\"Document is not a UBL Invoice or CreditNote\");\n\t}\n\n\tconst subtotal =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);\n\tconst total =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst prepaidAmount = toNumberOrNull(ubl.monetaryTotal.prepaidAmount);\n\tconst roundingAmount = toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount) ?? 0;\n\t// BR-CO-16: payable = total - prepaid + rounding. With no declared\n\t// PrepaidAmount we invert that to infer what was paid, but the rounding\n\t// term has to come out first — a cash-rounded payable (BT-114) is a\n\t// total-vs-payable gap by design, and reading it as a prepayment reports\n\t// an unpaid invoice as partially settled. Rounded before the sign test so\n\t// the float residue of undoing it cannot pass as a sub-cent prepayment.\n\tconst inferredPaid =\n\t\ttotal !== null && amountDue !== null\n\t\t\t? roundToCents(total - (amountDue - roundingAmount))\n\t\t\t: null;\n\tconst amountPaid =\n\t\tprepaidAmount ??\n\t\t(inferredPaid !== null && inferredPaid > 0 ? inferredPaid : null);\n\tconst taxTotal = toNumberOrNull(sumTaxTotal(ubl) ?? undefined);\n\tconst hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;\n\tconst headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);\n\tconst headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);\n\tconst currency = normalizeCurrency(ubl.currency);\n\tconst paymentTerms = normalizeText(ubl.paymentTermsNote);\n\tconst poNumber =\n\t\tnormalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);\n\n\tconst lineItems = ubl.lines.map((line) => ({\n\t\tdescription:\n\t\t\tnormalizeText(line.description) ??\n\t\t\tnormalizeText(line.itemName) ??\n\t\t\t\"Line item\",\n\t\tquantity: toNumberOrNull(line.quantity),\n\t\tunit: normalizeText(line.unitCode),\n\t\tunit_price: toNumberOrNull(line.unitPrice),\n\t\tamount: toNumberOrNull(line.lineExtensionAmount),\n\t\ttax_amount: toNumberOrNull(line.taxAmount),\n\t\ttax_rate: toNumberOrNull(line.taxCategory?.percent),\n\t\tproduct_code:\n\t\t\tnormalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),\n\t\tdiscount_amount: toNumberOrNull(line.discountAmount),\n\t\tperiod_start: parseDate(line.invoicePeriod?.startDate),\n\t\tperiod_end: parseDate(line.invoicePeriod?.endDate),\n\t\textra: {\n\t\t\tubl_line_id: normalizeText(line.id),\n\t\t\titem_name: normalizeText(line.itemName),\n\t\t\tsellers_item_id: normalizeText(line.sellersItemId),\n\t\t\tbuyers_item_id: normalizeText(line.buyersItemId),\n\t\t\ttax_category_id: normalizeText(line.taxCategory?.id),\n\t\t\ttax_scheme_id: normalizeText(line.taxCategory?.schemeId),\n\t\t\ttax_subtotals: line.taxSubtotals ?? [],\n\t\t\tallowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),\n\t\t\tcharge_amount: toNumberOrNull(line.chargeAmount),\n\t\t\tmetadata: line.additionalItemProperties\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tline.additionalItemProperties.map((p) => [p.name, p.value]),\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t},\n\t}));\n\n\tconst supplierAddress = addressToString(ubl.seller.address);\n\tconst receiverAddress = addressToString(ubl.buyer.address);\n\tconst supplierAddressStructured = addressToStructured(ubl.seller.address);\n\tconst receiverAddressStructured = addressToStructured(ubl.buyer.address);\n\tconst attachmentMetadata = sanitizeAttachments(ubl.attachments);\n\tconst paymentMeansList =\n\t\tubl.paymentMeansList && ubl.paymentMeansList.length > 0\n\t\t\t? ubl.paymentMeansList\n\t\t\t: ubl.paymentMeans\n\t\t\t\t? [ubl.paymentMeans]\n\t\t\t\t: [];\n\n\tconst extracted: InvoiceExtractionDTO = {\n\t\tprovider: \"ubl_xml\",\n\t\tdocument_id: documentId,\n\t\tinvoice: {\n\t\t\tinvoice_number: normalizeText(ubl.id),\n\t\t\tinvoice_date: parseDate(ubl.issueDate),\n\t\t\tdue_date: parseDate(ubl.dueDate),\n\t\t\tperiod_start: parseDate(ubl.invoicePeriod?.startDate),\n\t\t\tperiod_end: parseDate(ubl.invoicePeriod?.endDate),\n\t\t\tcurrency,\n\t\t\tsubtotal,\n\t\t\ttax_total: taxTotal,\n\t\t\ttotal,\n\t\t\tamount_due: amountDue,\n\t\t\tamount_paid: amountPaid,\n\t\t\tdiscount_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges\n\t\t\t\t\t? toNumberOrNull(headerDiscountTotal)\n\t\t\t\t\t: null),\n\t\t\tshipping_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),\n\t\t\trounding_total: toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount),\n\t\t\tpayment_terms: paymentTerms,\n\t\t\tpo_number: poNumber,\n\t\t\tsupplier: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.seller.name) ??\n\t\t\t\t\tnormalizeText(ubl.seller.registrationName),\n\t\t\t\taddress: supplierAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.seller.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.seller.companyId?.value),\n\t\t\t\tiban: normalizeText(ubl.paymentMeans?.iban),\n\t\t\t\tbic: normalizeText(ubl.paymentMeans?.bic),\n\t\t\t},\n\t\t\treceiver: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.buyer.name) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.registrationName),\n\t\t\t\taddress: receiverAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.buyer.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.companyId?.value),\n\t\t\t},\n\t\t\textra: {\n\t\t\t\tdocument_type: ubl.documentType,\n\t\t\t\tcustomization_id: normalizeText(ubl.customizationId),\n\t\t\t\tprofile_id: normalizeText(ubl.profileId),\n\t\t\t\tinvoice_type_code: normalizeText(ubl.invoiceTypeCode),\n\t\t\t\tbuyer_reference: normalizeText(ubl.buyerReference),\n\t\t\t\torder_reference_id: normalizeText(ubl.orderReference),\n\t\t\t\tsales_order_id: normalizeText(ubl.salesOrderId),\n\t\t\t\tcontract_reference: normalizeText(ubl.contractReference),\n\t\t\t\tproject_reference: normalizeText(ubl.projectReference),\n\t\t\t\tbilling_reference: ubl.billingReference\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tinvoice_id: normalizeText(ubl.billingReference.invoiceId),\n\t\t\t\t\t\t\tinvoice_issue_date: parseDate(\n\t\t\t\t\t\t\t\tubl.billingReference.invoiceIssueDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\ttax_point_date: parseDate(ubl.taxPointDate),\n\t\t\t\tinvoice_period: ubl.invoicePeriod ?? null,\n\t\t\t\tnote: normalizeText(ubl.note),\n\t\t\t\tpayment_means: ubl.paymentMeans\n\t\t\t\t\t? sanitizePaymentMeans(ubl.paymentMeans)\n\t\t\t\t\t: null,\n\t\t\t\tpayment_means_list: paymentMeansList.map(sanitizePaymentMeans),\n\t\t\t\tdelivery: ubl.delivery\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tactual_delivery_date: parseDate(\n\t\t\t\t\t\t\t\tubl.delivery.actualDeliveryDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\taddress: addressToStructured(ubl.delivery.address),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tsupplier: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.seller.endpoint?.value),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.seller.endpoint?.scheme),\n\t\t\t\t\tregistration_name: normalizeText(ubl.seller.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.seller.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.seller.companyId?.scheme),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.seller.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.seller.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.seller.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.seller.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.seller.contact?.email),\n\t\t\t\t},\n\t\t\t\treceiver: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.buyer.endpoint?.value),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.buyer.endpoint?.scheme),\n\t\t\t\t\tregistration_name: normalizeText(ubl.buyer.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.buyer.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.buyer.companyId?.scheme),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.buyer.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.buyer.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.buyer.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.buyer.contact?.email),\n\t\t\t\t},\n\t\t\t\tsupplier_address_structured: supplierAddressStructured,\n\t\t\t\treceiver_address_structured: receiverAddressStructured,\n\t\t\t\ttax_subtotals: ubl.taxTotal.subtotals,\n\t\t\t\tallowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),\n\t\t\t\tattachments: attachmentMetadata,\n\t\t\t\tdocument_references: ubl.documentReferences ?? [],\n\t\t\t},\n\t\t},\n\t\tline_items: lineItems,\n\t\tconfidence: {\n\t\t\toverall: 1,\n\t\t\tfields: {\n\t\t\t\tinvoice_id: 1,\n\t\t\t\tinvoice_date: 1,\n\t\t\t\tdue_date: 1,\n\t\t\t\ttotal_amount: 1,\n\t\t\t\tsupplier_name: 1,\n\t\t\t},\n\t\t},\n\t};\n\n\treturn {\n\t\textracted,\n\t\trawPayload: {\n\t\t\tformat: \"ubl_xml\",\n\t\t\tinvoice: sanitizeRawUbl(ubl),\n\t\t},\n\t};\n};\n\n/**\n * Parse a UBL invoice from raw bytes and normalize it into a DTO.\n */\nexport const parseUblInvoiceDocument = (params: {\n\tbytes: Uint8Array;\n\tdocumentId: string;\n\tmimeType: string;\n}) => {\n\tconst xml = decodeXmlBytes(params.bytes);\n\tconst { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);\n\treturn {\n\t\trawPayload: {\n\t\t\t...rawPayload,\n\t\t\tmime_type: params.mimeType,\n\t\t},\n\t\textracted,\n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