@financica/ubl 0.6.0 → 0.8.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/README.md CHANGED
@@ -1,11 +1,16 @@
1
- # @ingram-tech/ubl
1
+ # @financica/ubl
2
2
 
3
- TypeScript parser for [UBL (Universal Business Language)](https://www.oasis-open.org/committees/ubl/) invoice XML documents. Parses UBL 2.1 Invoice and CreditNote documents into typed objects, with an optional normalization layer that produces a flat DTO suitable for database storage or API responses.
3
+ TypeScript toolkit for [UBL (Universal Business Language)](https://www.oasis-open.org/committees/ubl/) invoice XML documents. Parses UBL 2.1 Invoice and CreditNote documents into typed objects, with an optional normalization layer that produces a flat DTO suitable for database storage or API responses, and builds Peppol BIS Billing 3.0 documents from a vendor-neutral model.
4
+
5
+ The package is split into two entry points:
6
+
7
+ - `@financica/ubl` — the parse side: read UBL XML into typed objects (`parseUblInvoice`, `normalizeUblResponse`, MLR parsing).
8
+ - `@financica/ubl/build` — the build side: assemble a `UblDocument` and serialize it to Peppol BIS Billing 3.0 XML.
4
9
 
5
10
  ## Installation
6
11
 
7
12
  ```bash
8
- npm install @ingram-tech/ubl
13
+ npm install @financica/ubl
9
14
  ```
10
15
 
11
16
  ## Usage
@@ -13,7 +18,7 @@ npm install @ingram-tech/ubl
13
18
  ### Parse UBL XML
14
19
 
15
20
  ```typescript
16
- import { parseUblInvoice } from "@ingram-tech/ubl";
21
+ import { parseUblInvoice } from "@financica/ubl";
17
22
 
18
23
  const xml = `<?xml version="1.0"?>
19
24
  <Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" ...>
@@ -33,7 +38,7 @@ Returns a typed `UblInvoice` object, or `null` if the XML is not a valid UBL Inv
33
38
  ### Normalize to DTO
34
39
 
35
40
  ```typescript
36
- import { normalizeUblResponse } from "@ingram-tech/ubl";
41
+ import { normalizeUblResponse } from "@financica/ubl";
37
42
 
38
43
  const { extracted, rawPayload } = normalizeUblResponse(xml, "doc-123");
39
44
  // extracted.invoice.invoice_number => "INV-001"
@@ -44,7 +49,7 @@ const { extracted, rawPayload } = normalizeUblResponse(xml, "doc-123");
44
49
  ### Parse from raw bytes
45
50
 
46
51
  ```typescript
47
- import { parseUblInvoiceDocument } from "@ingram-tech/ubl";
52
+ import { parseUblInvoiceDocument } from "@financica/ubl";
48
53
 
49
54
  const result = parseUblInvoiceDocument({
50
55
  bytes: new Uint8Array(buffer),
@@ -55,6 +60,90 @@ const result = parseUblInvoiceDocument({
55
60
 
56
61
  Handles UTF-8 BOM stripping automatically.
57
62
 
63
+ ### Build UBL XML
64
+
65
+ Construct a `UblDocument` — a thin, vendor-neutral mirror of the Peppol BIS
66
+ Billing 3.0 fields — and serialize it with `serializeUblDocument`. Builders and
67
+ helpers for parties, tax totals, identifiers, and attachments are exported from
68
+ the same subpath.
69
+
70
+ ```typescript
71
+ import { serializeUblDocument, type UblDocument } from "@financica/ubl/build";
72
+
73
+ const doc: UblDocument = {
74
+ documentType: "invoice",
75
+ id: "INV-001",
76
+ issueDate: "2026-01-15",
77
+ dueDate: "2026-02-14",
78
+ note: null,
79
+ currency: "EUR",
80
+ buyerReference: null,
81
+ precedingInvoiceId: null,
82
+ supplier: {
83
+ endpoint: { scheme: "0208", value: "0800279001" },
84
+ name: "Acme BV",
85
+ legalName: "Acme BV",
86
+ vatNumber: "BE0800279001",
87
+ companyId: { value: "0800279001", scheme: "0208" },
88
+ address: {
89
+ street: "Rue de la Loi 1",
90
+ additionalStreet: null,
91
+ city: "Brussels",
92
+ postalZone: "1000",
93
+ countrySubentity: null,
94
+ countryCode: "BE",
95
+ },
96
+ },
97
+ customer: {
98
+ endpoint: { scheme: "0208", value: "0123456789" },
99
+ name: "Globex SA",
100
+ legalName: "Globex SA",
101
+ vatNumber: "BE0123456789",
102
+ companyId: { value: "0123456789", scheme: "0208" },
103
+ address: {
104
+ street: "Avenue Louise 50",
105
+ additionalStreet: null,
106
+ city: "Brussels",
107
+ postalZone: "1050",
108
+ countrySubentity: null,
109
+ countryCode: "BE",
110
+ },
111
+ },
112
+ lines: [
113
+ {
114
+ id: "1",
115
+ name: "Consulting services",
116
+ quantity: 1,
117
+ unitCode: "C62",
118
+ lineExtensionAmount: 100,
119
+ priceAmount: 100,
120
+ taxCategory: { id: "S", percent: 21 },
121
+ },
122
+ ],
123
+ taxTotal: {
124
+ taxAmount: 21,
125
+ subtotals: [
126
+ { taxableAmount: 100, taxAmount: 21, category: { id: "S", percent: 21 } },
127
+ ],
128
+ },
129
+ monetaryTotal: {
130
+ lineExtensionAmount: 100,
131
+ taxExclusiveAmount: 100,
132
+ taxInclusiveAmount: 121,
133
+ payableAmount: 121,
134
+ },
135
+ attachments: [],
136
+ };
137
+
138
+ const xml = serializeUblDocument(doc);
139
+ ```
140
+
141
+ Set `documentType: "creditNote"` (with `precedingInvoiceId` referencing the
142
+ original invoice) to emit a `CreditNote` instead. The build subpath also exports
143
+ helpers such as `buildSupplierParty`, `buildTaxTotals`, `buildCompanyId`,
144
+ `buildPdfAttachment`, and Peppol identifier utilities (`resolveVatEndpoint`,
145
+ `parsePeppolEndpoint`, `listPeppolReceiverIdentifierCandidates`).
146
+
58
147
  ## Supported document types
59
148
 
60
149
  - UBL 2.1 Invoice
@@ -194,6 +194,46 @@ interface UblSupplier {
194
194
  }
195
195
  /** Convert a {@link UblSupplier} into the supplier (seller) party. */
196
196
  declare const buildSupplierParty: (supplier: UblSupplier) => UblParty;
197
+ /**
198
+ * Caller-provided customer (buyer) data, normalized into a stable shape.
199
+ *
200
+ * Each consumer (the Stripe adapter, app-specific row builders) resolves its
201
+ * own identifiers and address, then hands this generic shape to
202
+ * {@link buildCustomerParty}, so the Peppol routing logic lives in one place.
203
+ */
204
+ interface UblCustomer {
205
+ /** Display + legal name shown on the invoice. */
206
+ name: string;
207
+ /** Customer address, already normalized by the caller. */
208
+ address: UblAddress;
209
+ /**
210
+ * The customer's ISO 3166-1 alpha-2 country, used to resolve VAT/registration
211
+ * schemes for identifiers that don't carry a country prefix. Pass the
212
+ * customer's *own* country (never the supplier's) so the document is not
213
+ * mis-routed; falls back to the address country when omitted.
214
+ */
215
+ countryCode?: string | null;
216
+ /** Peppol participant identifier in `scheme:value` form (e.g. `"0208:0793904121"`). */
217
+ peppolID?: string | null;
218
+ /** Global Location Number (resolved under EAS `0088`). */
219
+ glnNumber?: string | null;
220
+ /** Generic tax/registration number (no VAT prefix). */
221
+ taxNumber?: string | null;
222
+ /** VAT number with country prefix (e.g. `"BE0793904121"`). */
223
+ vatNumber?: string | null;
224
+ }
225
+ /**
226
+ * Convert a {@link UblCustomer} into the customer (buyer) party.
227
+ *
228
+ * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in
229
+ * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered
230
+ * identifier), then an explicit Peppol ID, then a GLN (scheme `0088`), then the
231
+ * VAT number mapped to its country's VAT EAS scheme (e.g. BE → `9925`). That
232
+ * last step matters because most data stores hold a customer's VAT without a
233
+ * scheme, so without it a VAT-only customer would have no endpoint and the
234
+ * document would be unroutable.
235
+ */
236
+ declare const buildCustomerParty: (customer: UblCustomer, endpointOverride?: UblEndpoint | null) => UblParty;
197
237
 
198
238
  /**
199
239
  * Normalize a free-form address (Stripe shape, custom shape, or an internal
@@ -410,4 +450,4 @@ declare const el: (name: string, attrs?: XmlAttrs | null, content?: string | num
410
450
  /** Serialize a root element into a UTF-8 XML document string. */
411
451
  declare const serializeDocument: (root: XmlElement) => string;
412
452
 
413
- export { type BuildTaxTotalsResult, COUNTRY_CODE_LIST_ID, CREDIT_NOTE_TYPE_CODE, type CustomerTaxIdentifiers, DEFAULT_UNIT_CODE, EXEMPT_TAXABILITY_REASONS, INVOICE_TYPE_CODE, NS_CAC, NS_CBC, NS_CREDIT_NOTE, NS_INVOICE, type SupplierVatStatus, type TaxAmountInfo, UBL_CUSTOMIZATION_ID, UBL_PROFILE_ID, type UblAddress, type UblAttachment, type UblCompanyId, type UblDocument, type UblEndpoint, type UblLine, type UblMonetaryTotal, type UblParty, type UblSupplier, type UblTaxCategory, type UblTaxSubtotal, type UblTaxTotal, VAT_TAX_SCHEME_ID, type XmlAttrs, type XmlElement, buildCompanyId, buildPdfAttachment, buildSupplierParty, buildTaxTotals, centsToDecimal, el, extractCustomerTaxIdentifiers, listPeppolReceiverIdentifierCandidates, normalizeAddress, normalizeCompanyNumberForCountry, parsePeppolEndpoint, reconcileLinesToExclTotal, resolveCompanyIdScheme, resolveTaxCategoryFromTaxAmounts, resolveVatEndpoint, roundCurrency, sanitizeUblDocumentForAudit, serializeDocument, serializeUblDocument, taxCategoryFromReasonOrRate };
453
+ export { type BuildTaxTotalsResult, COUNTRY_CODE_LIST_ID, CREDIT_NOTE_TYPE_CODE, type CustomerTaxIdentifiers, DEFAULT_UNIT_CODE, EXEMPT_TAXABILITY_REASONS, INVOICE_TYPE_CODE, NS_CAC, NS_CBC, NS_CREDIT_NOTE, NS_INVOICE, type SupplierVatStatus, type TaxAmountInfo, UBL_CUSTOMIZATION_ID, UBL_PROFILE_ID, type UblAddress, type UblAttachment, type UblCompanyId, type UblCustomer, type UblDocument, type UblEndpoint, type UblLine, type UblMonetaryTotal, type UblParty, type UblSupplier, type UblTaxCategory, type UblTaxSubtotal, type UblTaxTotal, VAT_TAX_SCHEME_ID, type XmlAttrs, type XmlElement, buildCompanyId, buildCustomerParty, buildPdfAttachment, buildSupplierParty, buildTaxTotals, centsToDecimal, el, extractCustomerTaxIdentifiers, listPeppolReceiverIdentifierCandidates, normalizeAddress, normalizeCompanyNumberForCountry, parsePeppolEndpoint, reconcileLinesToExclTotal, resolveCompanyIdScheme, resolveTaxCategoryFromTaxAmounts, resolveVatEndpoint, roundCurrency, sanitizeUblDocumentForAudit, serializeDocument, serializeUblDocument, taxCategoryFromReasonOrRate };
@@ -426,6 +426,21 @@ var buildSupplierParty = (supplier) => {
426
426
  })
427
427
  };
428
428
  };
429
+ var buildCustomerParty = (customer, endpointOverride) => {
430
+ const countryCode = normalizeString(customer.countryCode) ?? customer.address.countryCode;
431
+ const endpoint = endpointOverride ?? parsePeppolEndpoint(customer.peppolID) ?? (customer.glnNumber ? { scheme: "0088", value: customer.glnNumber } : null) ?? resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });
432
+ return {
433
+ endpoint,
434
+ name: customer.name,
435
+ address: customer.address,
436
+ vatNumber: normalizeString(customer.vatNumber),
437
+ legalName: customer.name,
438
+ companyId: buildCompanyId({
439
+ countryCode,
440
+ companyNumber: customer.taxNumber ?? null
441
+ })
442
+ };
443
+ };
429
444
 
430
445
  // src/build/attachment.ts
431
446
  var buildPdfAttachment = (params) => ({
@@ -591,6 +606,7 @@ export {
591
606
  UBL_PROFILE_ID,
592
607
  VAT_TAX_SCHEME_ID,
593
608
  buildCompanyId,
609
+ buildCustomerParty,
594
610
  buildPdfAttachment,
595
611
  buildSupplierParty,
596
612
  buildTaxTotals,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/build/ubl/constants.ts","../../src/build/xml.ts","../../src/build/ubl/serialize.ts","../../src/build/utils.ts","../../src/build/address.ts","../../src/build/identifiers.ts","../../src/build/party.ts","../../src/build/attachment.ts","../../src/build/numeric.ts","../../src/build/tax-category.ts","../../src/build/tax-totals.ts"],"sourcesContent":["/** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */\n\n/** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */\nexport const UBL_CUSTOMIZATION_ID =\n\t\"urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0\";\n\n/** Peppol BIS Billing 3.0 process (BT-23). */\nexport const UBL_PROFILE_ID = \"urn:fdc:peppol.eu:2017:poacc:billing:01:1.0\";\n\n/** UNTDID 1001 — commercial invoice. */\nexport const INVOICE_TYPE_CODE = \"380\";\n/** UNTDID 1001 — credit note. */\nexport const CREDIT_NOTE_TYPE_CODE = \"381\";\n\n/** UN/ECE Recommendation 20 — \"one / piece\" (the default line unit). */\nexport const DEFAULT_UNIT_CODE = \"C62\";\n\n/** UNCL5153 — the VAT tax scheme identifier. */\nexport const VAT_TAX_SCHEME_ID = \"VAT\";\n\n/** ISO 3166-1 alpha-2 list identifier for `cbc:IdentificationCode`. */\nexport const COUNTRY_CODE_LIST_ID = \"ISO3166-1:Alpha2\";\n\nexport const NS_INVOICE = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nexport const NS_CREDIT_NOTE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\nexport const NS_CAC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\nexport const NS_CBC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\n","/**\n * Minimal, dependency-free XML builder + serializer.\n *\n * UBL is order-sensitive (every element sequence is fixed by the schema), so\n * children are always explicit, ordered arrays. There is no attribute or text\n * coercion magic beyond escaping — the UBL layer is responsible for emitting\n * elements in the right order.\n */\n\nexport type XmlAttrs = Record<string, string | number | null | undefined>;\n\nexport interface XmlElement {\n\tname: string;\n\tattrs?: XmlAttrs;\n\t/** Leaf text content. Mutually exclusive with `children`. */\n\ttext?: string | number | null;\n\t/** Child elements. Mutually exclusive with `text`. */\n\tchildren?: XmlElement[];\n}\n\n/** Falsy children are dropped, so callers can write `cond && el(...)`. */\ntype ChildSpec = XmlElement | null | undefined | false;\n\n/**\n * Build an XML element.\n *\n * el(\"cbc:ID\", null, \"INV-1\") → <cbc:ID>INV-1</cbc:ID>\n * el(\"cbc:Amount\", { currencyID: \"EUR\" }, \"10.00\") → <cbc:Amount currencyID=\"EUR\">10.00</cbc:Amount>\n * el(\"cac:Party\", null, [child, cond && child2]) → nested element\n */\nexport const el = (\n\tname: string,\n\tattrs?: XmlAttrs | null,\n\tcontent?: string | number | null | ChildSpec[],\n): XmlElement => {\n\tif (Array.isArray(content)) {\n\t\treturn {\n\t\t\tname,\n\t\t\tattrs: attrs ?? undefined,\n\t\t\tchildren: content.filter((c): c is XmlElement => Boolean(c)),\n\t\t};\n\t}\n\treturn { name, attrs: attrs ?? undefined, text: content ?? undefined };\n};\n\nconst escapeText = (value: string): string =>\n\tvalue.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\nconst escapeAttr = (value: string): string => escapeText(value).replace(/\"/g, \"&quot;\");\n\nconst serializeAttrs = (attrs: XmlAttrs | undefined): string => {\n\tif (!attrs) return \"\";\n\treturn Object.entries(attrs)\n\t\t.filter(([, value]) => value !== null && value !== undefined)\n\t\t.map(([key, value]) => ` ${key}=\"${escapeAttr(String(value))}\"`)\n\t\t.join(\"\");\n};\n\nconst serializeElement = (node: XmlElement, indentLevel: number): string => {\n\tconst pad = \" \".repeat(indentLevel);\n\tconst attrs = serializeAttrs(node.attrs);\n\n\tif (node.text !== undefined && node.text !== null) {\n\t\treturn `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;\n\t}\n\n\tconst children = node.children ?? [];\n\tif (children.length === 0) {\n\t\treturn `${pad}<${node.name}${attrs}/>`;\n\t}\n\n\tconst inner = children\n\t\t.map((child) => serializeElement(child, indentLevel + 1))\n\t\t.join(\"\\n\");\n\treturn `${pad}<${node.name}${attrs}>\\n${inner}\\n${pad}</${node.name}>`;\n};\n\n/** Serialize a root element into a UTF-8 XML document string. */\nexport const serializeDocument = (root: XmlElement): string =>\n\t`<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${serializeElement(root, 0)}\\n`;\n","import { el, serializeDocument, type XmlElement } from \"../xml\";\nimport {\n\tCOUNTRY_CODE_LIST_ID,\n\tCREDIT_NOTE_TYPE_CODE,\n\tINVOICE_TYPE_CODE,\n\tNS_CAC,\n\tNS_CBC,\n\tNS_CREDIT_NOTE,\n\tNS_INVOICE,\n\tUBL_CUSTOMIZATION_ID,\n\tUBL_PROFILE_ID,\n\tVAT_TAX_SCHEME_ID,\n} from \"./constants\";\nimport type {\n\tUblAddress,\n\tUblAttachment,\n\tUblDocument,\n\tUblLine,\n\tUblParty,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n} from \"./types\";\n\n/** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */\nconst amount = (value: number): string => value.toFixed(2);\n\n/** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */\nconst percent = (value: number): string => {\n\tconst rounded = Math.round(value * 100) / 100;\n\treturn Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);\n};\n\nconst money = (name: string, value: number, currency: string): XmlElement =>\n\tel(name, { currencyID: currency }, amount(value));\n\nconst vatTaxScheme = (): XmlElement =>\n\tel(\"cac:TaxScheme\", null, [el(\"cbc:ID\", null, VAT_TAX_SCHEME_ID)]);\n\n/**\n * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)\n * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption\n * reason for the non-charging categories (E/AE/O/K/G).\n */\nconst taxCategory = (name: string, category: UblTaxCategory): XmlElement =>\n\tel(name, null, [\n\t\tel(\"cbc:ID\", null, category.id),\n\t\tel(\"cbc:Percent\", null, percent(category.percent)),\n\t\tcategory.exemptionReason\n\t\t\t? el(\"cbc:TaxExemptionReason\", null, category.exemptionReason)\n\t\t\t: null,\n\t\tvatTaxScheme(),\n\t]);\n\nconst postalAddress = (address: UblAddress): XmlElement =>\n\tel(\"cac:PostalAddress\", null, [\n\t\taddress.street ? el(\"cbc:StreetName\", null, address.street) : null,\n\t\taddress.additionalStreet\n\t\t\t? el(\"cbc:AdditionalStreetName\", null, address.additionalStreet)\n\t\t\t: null,\n\t\taddress.city ? el(\"cbc:CityName\", null, address.city) : null,\n\t\taddress.postalZone ? el(\"cbc:PostalZone\", null, address.postalZone) : null,\n\t\taddress.countrySubentity\n\t\t\t? el(\"cbc:CountrySubentity\", null, address.countrySubentity)\n\t\t\t: null,\n\t\taddress.countryCode\n\t\t\t? el(\"cac:Country\", null, [\n\t\t\t\t\tel(\n\t\t\t\t\t\t\"cbc:IdentificationCode\",\n\t\t\t\t\t\t{ listID: COUNTRY_CODE_LIST_ID },\n\t\t\t\t\t\taddress.countryCode,\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t: null,\n\t]);\n\nconst party = (source: UblParty): XmlElement =>\n\tel(\"cac:Party\", null, [\n\t\tsource.endpoint\n\t\t\t? el(\n\t\t\t\t\t\"cbc:EndpointID\",\n\t\t\t\t\t{ schemeID: source.endpoint.scheme },\n\t\t\t\t\tsource.endpoint.value,\n\t\t\t\t)\n\t\t\t: null,\n\t\tel(\"cac:PartyName\", null, [el(\"cbc:Name\", null, source.name)]),\n\t\tpostalAddress(source.address),\n\t\tsource.vatNumber\n\t\t\t? el(\"cac:PartyTaxScheme\", null, [\n\t\t\t\t\tel(\"cbc:CompanyID\", null, source.vatNumber),\n\t\t\t\t\tvatTaxScheme(),\n\t\t\t\t])\n\t\t\t: null,\n\t\tel(\"cac:PartyLegalEntity\", null, [\n\t\t\tel(\"cbc:RegistrationName\", null, source.legalName ?? source.name),\n\t\t\tsource.companyId\n\t\t\t\t? el(\n\t\t\t\t\t\t\"cbc:CompanyID\",\n\t\t\t\t\t\tsource.companyId.scheme\n\t\t\t\t\t\t\t? { schemeID: source.companyId.scheme }\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\tsource.companyId.value,\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t]),\n\t]);\n\nconst taxSubtotal = (subtotal: UblTaxSubtotal, currency: string): XmlElement =>\n\tel(\"cac:TaxSubtotal\", null, [\n\t\tmoney(\"cbc:TaxableAmount\", subtotal.taxableAmount, currency),\n\t\tmoney(\"cbc:TaxAmount\", subtotal.taxAmount, currency),\n\t\ttaxCategory(\"cac:TaxCategory\", subtotal.category),\n\t]);\n\nconst line = (\n\tsource: UblLine,\n\tcurrency: string,\n\tdocumentType: UblDocument[\"documentType\"],\n): XmlElement => {\n\tconst lineElementName =\n\t\tdocumentType === \"creditNote\" ? \"cac:CreditNoteLine\" : \"cac:InvoiceLine\";\n\tconst quantityElementName =\n\t\tdocumentType === \"creditNote\" ? \"cbc:CreditedQuantity\" : \"cbc:InvoicedQuantity\";\n\n\treturn el(lineElementName, null, [\n\t\tel(\"cbc:ID\", null, source.id),\n\t\tel(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),\n\t\tmoney(\"cbc:LineExtensionAmount\", source.lineExtensionAmount, currency),\n\t\tel(\"cac:Item\", null, [\n\t\t\tel(\"cbc:Name\", null, source.name),\n\t\t\ttaxCategory(\"cac:ClassifiedTaxCategory\", source.taxCategory),\n\t\t]),\n\t\tel(\"cac:Price\", null, [money(\"cbc:PriceAmount\", source.priceAmount, currency)]),\n\t]);\n};\n\nconst attachmentReference = (attachment: UblAttachment): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tel(\"cbc:ID\", null, attachment.id),\n\t\tel(\"cac:Attachment\", null, [\n\t\t\tel(\n\t\t\t\t\"cbc:EmbeddedDocumentBinaryObject\",\n\t\t\t\t{ mimeCode: attachment.mimeCode, filename: attachment.filename },\n\t\t\t\tattachment.base64,\n\t\t\t),\n\t\t]),\n\t]);\n\nconst billingReference = (precedingInvoiceId: string): XmlElement =>\n\tel(\"cac:BillingReference\", null, [\n\t\tel(\"cac:InvoiceDocumentReference\", null, [\n\t\t\tel(\"cbc:ID\", null, precedingInvoiceId),\n\t\t]),\n\t]);\n\n/** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */\nexport const serializeUblDocument = (doc: UblDocument): string => {\n\tconst isCreditNote = doc.documentType === \"creditNote\";\n\tconst rootName = isCreditNote ? \"CreditNote\" : \"Invoice\";\n\tconst rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;\n\tconst typeCodeElement = isCreditNote\n\t\t? el(\"cbc:CreditNoteTypeCode\", null, CREDIT_NOTE_TYPE_CODE)\n\t\t: el(\"cbc:InvoiceTypeCode\", null, INVOICE_TYPE_CODE);\n\n\tconst children: (XmlElement | null | false)[] = [\n\t\tel(\"cbc:CustomizationID\", null, UBL_CUSTOMIZATION_ID),\n\t\tel(\"cbc:ProfileID\", null, UBL_PROFILE_ID),\n\t\tel(\"cbc:ID\", null, doc.id),\n\t\tel(\"cbc:IssueDate\", null, doc.issueDate),\n\t\t// CreditNote has no DueDate element in the UBL sequence.\n\t\t!isCreditNote && doc.dueDate ? el(\"cbc:DueDate\", null, doc.dueDate) : null,\n\t\ttypeCodeElement,\n\t\tdoc.note ? el(\"cbc:Note\", null, doc.note) : null,\n\t\tel(\"cbc:DocumentCurrencyCode\", null, doc.currency),\n\t\tdoc.buyerReference ? el(\"cbc:BuyerReference\", null, doc.buyerReference) : null,\n\t\tdoc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,\n\t\t...doc.attachments.map(attachmentReference),\n\t\tel(\"cac:AccountingSupplierParty\", null, [party(doc.supplier)]),\n\t\tel(\"cac:AccountingCustomerParty\", null, [party(doc.customer)]),\n\t\tel(\"cac:TaxTotal\", null, [\n\t\t\tmoney(\"cbc:TaxAmount\", doc.taxTotal.taxAmount, doc.currency),\n\t\t\t...doc.taxTotal.subtotals.map((subtotal) =>\n\t\t\t\ttaxSubtotal(subtotal, doc.currency),\n\t\t\t),\n\t\t]),\n\t\tel(\"cac:LegalMonetaryTotal\", null, [\n\t\t\tmoney(\n\t\t\t\t\"cbc:LineExtensionAmount\",\n\t\t\t\tdoc.monetaryTotal.lineExtensionAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\n\t\t\t\t\"cbc:TaxExclusiveAmount\",\n\t\t\t\tdoc.monetaryTotal.taxExclusiveAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\n\t\t\t\t\"cbc:TaxInclusiveAmount\",\n\t\t\t\tdoc.monetaryTotal.taxInclusiveAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\"cbc:PayableAmount\", doc.monetaryTotal.payableAmount, doc.currency),\n\t\t]),\n\t\t...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),\n\t];\n\n\tconst root = el(\n\t\trootName,\n\t\t{\n\t\t\txmlns: rootNamespace,\n\t\t\t\"xmlns:cac\": NS_CAC,\n\t\t\t\"xmlns:cbc\": NS_CBC,\n\t\t},\n\t\tchildren.filter((child): child is XmlElement => Boolean(child)),\n\t);\n\n\treturn serializeDocument(root);\n};\n","export const isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const normalizeString = (value: unknown): string | null => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\nexport const toNumber = (value: unknown): number => {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\tif (typeof value === \"string\") {\n\t\tconst parsed = Number(value);\n\t\tif (Number.isFinite(parsed)) return parsed;\n\t}\n\treturn 0;\n};\n","import type { UblAddress } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst normalizeCountryCode = (value: string | null | undefined): string | null => {\n\tconst trimmed = normalizeString(value);\n\tif (!trimmed) return null;\n\treturn trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;\n};\n\n/**\n * Normalize a free-form address (Stripe shape, custom shape, or an internal\n * shape) into a {@link UblAddress}.\n *\n * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`\n * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address\n * has no country, but never silently substitutes a caller's country — pass\n * `null` when \"no country\" is the right answer.\n */\nexport const normalizeAddress = (\n\taddress: unknown,\n\tfallbackCountryCode: string | null,\n\tfallbackLine?: string | null,\n): UblAddress => {\n\tconst record = isRecord(address) ? address : {};\n\tconst countryCode =\n\t\tnormalizeCountryCode(normalizeString(record.country)) ??\n\t\tnormalizeCountryCode(normalizeString(record.country_code)) ??\n\t\tnormalizeCountryCode(fallbackCountryCode);\n\treturn {\n\t\tstreet:\n\t\t\tnormalizeString(record.line1) ??\n\t\t\tnormalizeString(record.street) ??\n\t\t\tfallbackLine ??\n\t\t\tnull,\n\t\tadditionalStreet: normalizeString(record.line2),\n\t\tcity: normalizeString(record.city),\n\t\tpostalZone:\n\t\t\tnormalizeString(record.postal_code) ?? normalizeString(record.zip_code),\n\t\tcountrySubentity:\n\t\t\tnormalizeString(record.state) ?? normalizeString(record.country_subentity),\n\t\tcountryCode,\n\t};\n};\n","import type { UblCompanyId, UblEndpoint } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst cleanIdentifierValue = (value: string) =>\n\tvalue\n\t\t.trim()\n\t\t.replace(/\\s+/g, \"\")\n\t\t.replace(/[^A-Za-z0-9]/g, \"\");\n\nconst normalizeBelgianCompanyNumber = (value: string | null | undefined) => {\n\tif (!value) return \"\";\n\treturn cleanIdentifierValue(value).toUpperCase().replace(/^BE/, \"\");\n};\n\n/**\n * Strip whitespace/punctuation from a country-specific company number.\n * For Belgium, also strips an optional `BE` prefix.\n */\nexport const normalizeCompanyNumberForCountry = (\n\tcountryCode: string | null | undefined,\n\tcompanyNumber: string | null | undefined,\n) => {\n\tif (!companyNumber) return \"\";\n\tconst upper = countryCode?.trim().toUpperCase() ?? \"\";\n\tif (upper === \"BE\") return normalizeBelgianCompanyNumber(companyNumber);\n\treturn companyNumber.trim();\n};\n\n/**\n * Country code → Peppol/ISO 6523 ICD scheme for a legal registration number\n * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`).\n *\n * BE → 0208 (Belgian enterprise number, CBE/KBO/BCE)\n * NL → 0106 (Netherlands KvK)\n * FR → 0002 (France SIRENE)\n *\n * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).\n * Returns `null` when the scheme can't be determined, in which case the\n * CompanyID is emitted without a `schemeID` attribute.\n */\nexport const resolveCompanyIdScheme = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): string | null => {\n\tconst companyNumber = normalizeString(params.companyNumber);\n\tif (!companyNumber) return null;\n\n\tconst TABLE: Record<string, string> = {\n\t\tBE: \"0208\",\n\t\tNL: \"0106\",\n\t\tFR: \"0002\",\n\t};\n\n\tconst normalizedCountry =\n\t\tnormalizeString(params.countryCode)?.toUpperCase() ?? null;\n\tif (normalizedCountry && normalizedCountry in TABLE) {\n\t\treturn TABLE[normalizedCountry] ?? null;\n\t}\n\n\tconst countryPrefix = cleanIdentifierValue(companyNumber).toUpperCase().slice(0, 2);\n\treturn countryPrefix in TABLE ? (TABLE[countryPrefix] ?? null) : null;\n};\n\n/**\n * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the\n * country-appropriate ICD scheme when known. Returns `null` when there is no\n * company number.\n */\nexport const buildCompanyId = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): UblCompanyId | null => {\n\tconst normalized = normalizeString(\n\t\tnormalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),\n\t);\n\tif (!normalized) return null;\n\treturn {\n\t\tvalue: normalized,\n\t\tscheme: resolveCompanyIdScheme({\n\t\t\tcountryCode: params.countryCode,\n\t\t\tcompanyNumber: normalized,\n\t\t}),\n\t};\n};\n\n/**\n * Country code → Peppol EAS scheme for a *VAT* identifier, keyed by ISO 3166-1\n * alpha-2. Source: Peppol Code Lists – Participant Identifier Schemes (EAS),\n * Peppol BIS Billing 3.0 (November 2025 release).\n *\n * Only countries that publish a VAT-based EAS scheme appear here. Some (e.g.\n * SE/DK/NO) address Peppol participants by organisation number rather than VAT\n * and are intentionally absent — see {@link resolveCompanyIdScheme}.\n */\nconst VAT_SCHEME_BY_COUNTRY: Record<string, string> = {\n\tAD: \"9922\", // Andorra\n\tAL: \"9923\", // Albania\n\tAT: \"9914\", // Austria\n\tBA: \"9924\", // Bosnia and Herzegovina\n\tBE: \"9925\", // Belgium\n\tBG: \"9926\", // Bulgaria\n\tCH: \"9927\", // Switzerland\n\tCY: \"9928\", // Cyprus\n\tCZ: \"9929\", // Czech Republic\n\tDE: \"9930\", // Germany\n\tEE: \"9931\", // Estonia\n\tES: \"9920\", // Spain (Spanish Tax Administration)\n\tFI: \"0213\", // Finland (Finnish VAT Identifier)\n\tFR: \"9957\", // France\n\tGB: \"9932\", // United Kingdom\n\tGR: \"9933\", // Greece (VAT prefix \"EL\")\n\tHR: \"9934\", // Croatia\n\tHU: \"9910\", // Hungary\n\tIE: \"9935\", // Ireland\n\tLI: \"9936\", // Liechtenstein\n\tLT: \"9937\", // Lithuania\n\tLU: \"9938\", // Luxembourg\n\tLV: \"9939\", // Latvia\n\tMC: \"9940\", // Monaco\n\tME: \"9941\", // Montenegro\n\tMK: \"9942\", // North Macedonia\n\tMT: \"9943\", // Malta\n\tNL: \"9944\", // Netherlands\n\tPL: \"9945\", // Poland\n\tPT: \"9946\", // Portugal\n\tRO: \"9947\", // Romania\n\tRS: \"9948\", // Serbia\n\tSI: \"9949\", // Slovenia\n\tSK: \"9950\", // Slovakia\n\tSM: \"9951\", // San Marino\n\tTR: \"9952\", // Turkey\n\tVA: \"9953\", // Holy See / Vatican City\n};\n\n/**\n * VAT registration prefixes that differ from the ISO 3166-1 alpha-2 country\n * code, so a VAT number's leading two letters still resolve to the right scheme.\n */\nconst VAT_PREFIX_TO_COUNTRY: Record<string, string> = {\n\tEL: \"GR\", // Greece issues VAT numbers with the \"EL\" prefix\n\tXI: \"GB\", // Northern Ireland VAT is issued under the UK scheme\n};\n\n/**\n * Resolve the Peppol participant identifier for a VAT number, deriving the EAS\n * scheme from the number's own country prefix (falling back to `countryCode`).\n *\n * `BE0206582284` → `{ scheme: \"9925\", value: \"BE0206582284\" }`\n *\n * The value keeps its country prefix, matching how participants register (the\n * Peppol directory lists this party as `9925:be0206582284`). Returns `null`\n * when the country has no VAT EAS scheme or the input is empty.\n */\nexport const resolveVatEndpoint = (params: {\n\tvatNumber: string | null | undefined;\n\tcountryCode?: string | null;\n}): UblEndpoint | null => {\n\tconst value = normalizeString(params.vatNumber);\n\tif (!value) return null;\n\tconst cleaned = cleanIdentifierValue(value).toUpperCase();\n\tif (!cleaned) return null;\n\n\tconst prefix = cleaned.slice(0, 2);\n\tconst fromPrefix = /^[A-Z]{2}$/.test(prefix)\n\t\t? (VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix)\n\t\t: null;\n\tconst fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;\n\n\tconst country =\n\t\tfromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;\n\tconst scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : undefined;\n\tif (!scheme) return null;\n\n\treturn { scheme, value: cleaned };\n};\n\n/**\n * Parse a Peppol participant identifier into a {@link UblEndpoint}.\n *\n * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns\n * `null` for values without an explicit scheme, since `cbc:EndpointID` requires\n * a `schemeID` and guessing one would mis-route the document.\n */\nexport const parsePeppolEndpoint = (\n\tpeppolId: string | null | undefined,\n): UblEndpoint | null => {\n\tconst normalized = normalizeString(peppolId);\n\tif (!normalized) return null;\n\tconst separatorIndex = normalized.indexOf(\":\");\n\tif (separatorIndex <= 0) return null;\n\tconst scheme = normalized.slice(0, separatorIndex).trim();\n\tconst value = normalized.slice(separatorIndex + 1).trim();\n\tif (!scheme || !value) return null;\n\treturn { scheme, value };\n};\n\nexport interface CustomerTaxIdentifiers {\n\tpeppolID: string | null;\n\tglnNumber: string | null;\n\ttaxNumber: string | null;\n\tvatNumber: string | null;\n}\n\nconst normalizeIdentifierType = (value: string | null) =>\n\tvalue?.toLowerCase().replace(/[^a-z0-9]+/g, \"_\") ?? null;\n\n/**\n * Pick the first usable Peppol identifier, GLN, VAT number, and tax number\n * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).\n *\n * Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.\n * Peppol IDs are typically stored as a custom `peppol_id` type.\n */\nexport const extractCustomerTaxIdentifiers = (\n\ttaxIds: unknown,\n): CustomerTaxIdentifiers => {\n\tlet peppolID: string | null = null;\n\tlet glnNumber: string | null = null;\n\tlet taxNumber: string | null = null;\n\tlet vatNumber: string | null = null;\n\n\tif (!Array.isArray(taxIds)) {\n\t\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n\t}\n\n\tfor (const entry of taxIds) {\n\t\tif (!isRecord(entry)) continue;\n\n\t\tconst type = normalizeIdentifierType(normalizeString(entry.type));\n\t\tconst value = normalizeString(entry.value);\n\t\tif (!type || !value) continue;\n\n\t\tif (!peppolID && type.includes(\"peppol\")) {\n\t\t\tpeppolID = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!glnNumber && type.includes(\"gln\")) {\n\t\t\tglnNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!vatNumber && type.includes(\"vat\")) {\n\t\t\tvatNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!taxNumber && type.includes(\"tax\")) {\n\t\t\ttaxNumber = value;\n\t\t}\n\t}\n\n\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n};\n\n/**\n * Build the fully-qualified Peppol participant identifiers (`scheme:value`) a\n * receiver lookup will accept, in priority order, de-duplicated.\n *\n * Stripe stores a customer's VAT number without a Peppol scheme (e.g.\n * `BE0206582284`), but a participant lookup needs the qualified identifier\n * (`9925:BE0206582284`). This attaches the right scheme:\n *\n * 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;\n * 2. a GLN under EAS `0088`;\n * 3. the VAT number under its country's VAT EAS scheme (see\n * {@link resolveVatEndpoint});\n * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)\n * under EAS `0208` — many Belgian entities register only under that;\n * 5. a generic tax/registration number under its country's company-ID scheme.\n *\n * `countryCode` (the customer's country, when known) disambiguates schemes for\n * identifiers that don't carry a country prefix (GLN, plain tax numbers).\n */\nexport const listPeppolReceiverIdentifierCandidates = (\n\tcustomer: {\n\t\tpeppolID?: string | null;\n\t\tglnNumber?: string | null;\n\t\ttaxNumber?: string | null;\n\t\tvatNumber?: string | null;\n\t},\n\tcountryCode?: string | null,\n): string[] => {\n\tconst candidates: string[] = [];\n\tconst add = (id: { scheme?: string | null; value: string } | null) => {\n\t\tif (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);\n\t};\n\n\t// 1. An explicit Peppol ID already carries its own scheme.\n\tconst peppol = normalizeString(customer.peppolID);\n\tif (peppol) candidates.push(peppol);\n\n\t// 2. GLN → EAS 0088 (Global Location Number).\n\tconst gln = normalizeString(customer.glnNumber);\n\tif (gln) add({ scheme: \"0088\", value: cleanIdentifierValue(gln) });\n\n\t// 3. VAT number → the country's VAT EAS scheme (e.g. BE → 9925).\n\tconst vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\tadd(vat);\n\n\t// 4. Belgium also reaches parties by enterprise number under EAS 0208; it is\n\t// the VAT digits without the `BE` prefix, and some entities register only so.\n\tif (vat?.scheme === \"9925\") {\n\t\tadd(buildCompanyId({ countryCode: \"BE\", companyNumber: customer.vatNumber ?? null }));\n\t}\n\n\t// 5. A generic tax/registration number → its country's company-ID scheme.\n\tconst tax = normalizeString(customer.taxNumber);\n\tif (tax) add(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));\n\n\treturn Array.from(new Set(candidates));\n};\n","import { normalizeAddress } from \"./address\";\nimport { buildCompanyId, parsePeppolEndpoint } from \"./identifiers\";\nimport type { UblParty } from \"./ubl/types\";\nimport { normalizeString } from \"./utils\";\n\n/**\n * Supplier (seller) VAT status. Drives how zero-VAT lines are reported when the\n * seller does not charge VAT:\n *\n * 1 — Subject to VAT (the normal case): line categories come from the data.\n * 2 — Not subject to VAT.\n * 3 — Small business / franchise exemption (e.g. Belgian Article 56bis).\n *\n * For statuses 2 and 3, {@link ../build.ts} coerces all line categories to a\n * non-charging exempt category so no VAT is reported.\n */\nexport type SupplierVatStatus = 1 | 2 | 3;\n\n/**\n * Caller-provided supplier data, normalized into a stable shape.\n *\n * Each consumer builds this from its own data store. Once a `UblSupplier`\n * exists, the party builder no longer needs to know where it came from.\n */\nexport interface UblSupplier {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** ISO 3166-1 alpha-2 country code (e.g. `\"BE\"`). */\n\tcountryCode: string;\n\t/**\n\t * Free-form address. Stripe-style fields (`line1`, `postal_code`, `country`)\n\t * and legacy/internal fields (`street`, `zip_code`) are both accepted.\n\t */\n\taddress: unknown;\n\t/** Country-specific company/registration number (e.g. BE enterprise number). */\n\tcompanyNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n\t/** Whether the supplier charges VAT. See {@link SupplierVatStatus}. */\n\tvatStatus: SupplierVatStatus;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n}\n\n/** Convert a {@link UblSupplier} into the supplier (seller) party. */\nexport const buildSupplierParty = (supplier: UblSupplier): UblParty => {\n\tconst address = normalizeAddress(supplier.address, supplier.countryCode);\n\treturn {\n\t\tendpoint: parsePeppolEndpoint(supplier.peppolID),\n\t\tname: supplier.name,\n\t\taddress,\n\t\tvatNumber: normalizeString(supplier.vatNumber),\n\t\tlegalName: supplier.name,\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode: supplier.countryCode,\n\t\t\tcompanyNumber: supplier.companyNumber ?? null,\n\t\t}),\n\t};\n};\n\n// buildCustomerPartyFromStripeInvoice lives in @financica/stripe-ubl (it is\n// Stripe-specific); this module is the generic UBL build core.\n","import type { UblAttachment, UblDocument } from \"./ubl/types\";\n\n/**\n * Build a UBL embedded-document attachment (BG-24) from raw bytes — e.g. the\n * rendered PDF of the invoice. Emitted as a `cac:AdditionalDocumentReference`\n * with an inline base64 `cbc:EmbeddedDocumentBinaryObject`.\n */\nexport const buildPdfAttachment = (params: {\n\tfilename: string;\n\tbytes: Uint8Array;\n\t/** Document reference ID (BT-122). Defaults to the filename. */\n\tid?: string;\n}): UblAttachment => ({\n\tid: params.id ?? params.filename,\n\tfilename: params.filename,\n\tmimeCode: \"application/pdf\",\n\tbase64: Buffer.from(params.bytes).toString(\"base64\"),\n});\n\n/**\n * Replace each attachment's base64 payload with `[omitted]` plus a length, so a\n * {@link UblDocument} is safe to log or persist for audit.\n */\nexport const sanitizeUblDocumentForAudit = (doc: UblDocument): UblDocument => {\n\tif (doc.attachments.length === 0) return doc;\n\treturn {\n\t\t...doc,\n\t\tattachments: doc.attachments.map((attachment) => ({\n\t\t\t...attachment,\n\t\t\tbase64: `[omitted ${attachment.base64.length} chars]`,\n\t\t})),\n\t};\n};\n","/** Round a number to 2 decimal places (cents). */\nexport const roundCurrency = (value: number) =>\n\tMath.round((value + Number.EPSILON) * 100) / 100;\n\n/** Convert an integer cent amount into a 2-decimal currency value. */\nexport const centsToDecimal = (cents: number) => roundCurrency(cents / 100);\n","import type { UblTaxCategory } from \"./ubl/types\";\n\n/**\n * Stripe Tax `taxability_reason` values that map to a VAT-exempt UBL category\n * (`E`). Reverse charge is handled separately (category `AE`).\n */\nexport const EXEMPT_TAXABILITY_REASONS = new Set([\n\t\"customer_exempt\",\n\t\"product_exempt\",\n\t\"not_subject_to_tax\",\n\t\"not_collecting\",\n\t\"not_supported\",\n\t\"portion_product_exempt\",\n]);\n\n/** Human-readable EN 16931 exemption reasons (BR-E-10 / BR-AE-10 / …). */\nconst EXEMPTION_REASON_TEXT: Record<string, string> = {\n\treverse_charge: \"Reverse charge\",\n\tcustomer_exempt: \"Exempt based on customer status\",\n\tproduct_exempt: \"Exempt based on the supplied goods or services\",\n\tportion_product_exempt: \"Exempt based on the supplied goods or services\",\n\tnot_subject_to_tax: \"Not subject to VAT\",\n\tnot_collecting: \"VAT not collected\",\n\tnot_supported: \"VAT not applicable\",\n};\n\nexport interface TaxAmountInfo {\n\tamount: number;\n\ttaxability_reason?: string | null;\n\ttax_rate_percentage?: number | null;\n}\n\nconst normalizeTaxCategoryId = (value: unknown) => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim().toUpperCase();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\n/**\n * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a\n * numeric rate into a {@link UblTaxCategory}.\n *\n * - Reverse charge → `AE` (0%, with exemption reason)\n * - Any other exempt reason → `E` (0%, with exemption reason)\n * - Category `Z` / rate ≤ 0 → `Z` (zero-rated, 0%)\n * - Otherwise → `S` (standard, the line's rate)\n */\nexport const taxCategoryFromReasonOrRate = (params: {\n\ttaxCategoryId?: string | null;\n\ttaxabilityReason: string | null;\n\trate: number;\n}): UblTaxCategory => {\n\tconst categoryHint = normalizeTaxCategoryId(params.taxCategoryId);\n\tconst reason = params.taxabilityReason;\n\n\tif (categoryHint === \"AE\" || reason === \"reverse_charge\") {\n\t\treturn {\n\t\t\tid: \"AE\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.reverse_charge,\n\t\t};\n\t}\n\tif (categoryHint === \"E\" || (reason && EXEMPT_TAXABILITY_REASONS.has(reason))) {\n\t\treturn {\n\t\t\tid: \"E\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason:\n\t\t\t\t(reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? \"Exempt from VAT\",\n\t\t};\n\t}\n\tif (categoryHint === \"Z\" || reason === \"zero_rated\" || params.rate <= 0) {\n\t\treturn { id: \"Z\", percent: 0 };\n\t}\n\treturn { id: \"S\", percent: params.rate };\n};\n\n/**\n * Resolve a {@link UblTaxCategory} from a line's Stripe tax info.\n *\n * Exempt / reverse-charge / zero-rated reasons take precedence over the rate;\n * otherwise the rate decides standard (`S`) vs zero-rated (`Z`).\n */\nexport const resolveTaxCategoryFromTaxAmounts = (\n\ttaxAmounts: TaxAmountInfo[],\n\trate: number,\n): UblTaxCategory => {\n\tfor (const ta of taxAmounts) {\n\t\tif (!ta.taxability_reason) continue;\n\t\tif (ta.taxability_reason === \"reverse_charge\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"reverse_charge\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: ta.taxability_reason,\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (ta.taxability_reason === \"zero_rated\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"zero_rated\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t}\n\treturn taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });\n};\n","import { roundCurrency } from \"./numeric\";\nimport type {\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"./ubl/types\";\n\n/**\n * Adjust the largest line's net amount so the line nets sum to the\n * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).\n *\n * Reconciling at the *line* level — rather than directly on the VAT breakdown —\n * keeps the document consistent bottom-up: the VAT category taxable amounts\n * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the\n * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level\n * coupon; larger ones indicate a real upstream data problem.\n */\nexport const reconcileLinesToExclTotal = (\n\tlines: UblLine[],\n\tauthoritativeTotalExclVat: number,\n): UblLine[] => {\n\tif (lines.length === 0) return lines;\n\tconst computed = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst diff = roundCurrency(authoritativeTotalExclVat - computed);\n\tif (diff === 0) return lines;\n\n\tconst largestIdx = lines.reduce(\n\t\t(maxIdx, line, idx, arr) =>\n\t\t\tline.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0)\n\t\t\t\t? idx\n\t\t\t\t: maxIdx,\n\t\t0,\n\t);\n\n\treturn lines.map((line, idx) => {\n\t\tif (idx !== largestIdx) return line;\n\t\tconst adjusted = roundCurrency(line.lineExtensionAmount + diff);\n\t\treturn {\n\t\t\t...line,\n\t\t\tlineExtensionAmount: adjusted,\n\t\t\tpriceAmount: roundCurrency(adjusted / Math.max(line.quantity, 1)),\n\t\t};\n\t});\n};\n\nconst categoryKey = (category: UblTaxCategory): string =>\n\t`${category.id}:${category.percent}`;\n\nexport interface BuildTaxTotalsResult {\n\ttaxTotal: UblTaxTotal;\n\tmonetaryTotal: UblMonetaryTotal;\n}\n\n/**\n * Group lines by `(category, percent)` into a VAT breakdown and compute the\n * document monetary totals.\n *\n * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,\n * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the\n * upstream per-line tax cents. This guarantees the breakdown is internally\n * consistent and passes validation; it can differ by a cent from the figure a\n * payment processor reported, which is an unavoidable artifact of representing\n * a cents-rounded system as a rate-based VAT breakdown.\n */\nexport const buildTaxTotals = (lines: UblLine[]): BuildTaxTotalsResult => {\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ category: UblTaxCategory; taxableAmount: number }\n\t>();\n\n\tfor (const line of lines) {\n\t\tconst key = categoryKey(line.taxCategory);\n\t\tconst current = groups.get(key) ?? {\n\t\t\tcategory: line.taxCategory,\n\t\t\ttaxableAmount: 0,\n\t\t};\n\t\tcurrent.taxableAmount = roundCurrency(\n\t\t\tcurrent.taxableAmount + line.lineExtensionAmount,\n\t\t);\n\t\tgroups.set(key, current);\n\t}\n\n\tconst subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({\n\t\ttaxableAmount: group.taxableAmount,\n\t\ttaxAmount: roundCurrency((group.taxableAmount * group.category.percent) / 100),\n\t\tcategory: group.category,\n\t}));\n\n\tconst lineExtensionAmount = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst taxAmount = roundCurrency(\n\t\tsubtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0),\n\t);\n\tconst taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);\n\n\treturn {\n\t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EF,QAAM,sBAAsB;AAAA,IAC3B,MAAM,OAAO,CAAC,KAAKA,UAAS,MAAMA,MAAK,qBAAqB,CAAC;AAAA,EAC9D;AACA,QAAM,YAAY;AAAA,IACjB,UAAU,OAAO,CAAC,KAAK,aAAa,MAAM,SAAS,WAAW,CAAC;AAAA,EAChE;AACA,QAAM,qBAAqB,cAAc,sBAAsB,SAAS;AAExE,SAAO;AAAA,IACN,UAAU,EAAE,WAAW,UAAU;AAAA,IACjC,eAAe;AAAA,MACd;AAAA,MACA,oBAAoB;AAAA,MACpB;AAAA,MACA,eAAe;AAAA,IAChB;AAAA,EACD;AACD;","names":["line"]}
1
+ {"version":3,"sources":["../../src/build/ubl/constants.ts","../../src/build/xml.ts","../../src/build/ubl/serialize.ts","../../src/build/utils.ts","../../src/build/address.ts","../../src/build/identifiers.ts","../../src/build/party.ts","../../src/build/attachment.ts","../../src/build/numeric.ts","../../src/build/tax-category.ts","../../src/build/tax-totals.ts"],"sourcesContent":["/** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */\n\n/** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */\nexport const UBL_CUSTOMIZATION_ID =\n\t\"urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0\";\n\n/** Peppol BIS Billing 3.0 process (BT-23). */\nexport const UBL_PROFILE_ID = \"urn:fdc:peppol.eu:2017:poacc:billing:01:1.0\";\n\n/** UNTDID 1001 — commercial invoice. */\nexport const INVOICE_TYPE_CODE = \"380\";\n/** UNTDID 1001 — credit note. */\nexport const CREDIT_NOTE_TYPE_CODE = \"381\";\n\n/** UN/ECE Recommendation 20 — \"one / piece\" (the default line unit). */\nexport const DEFAULT_UNIT_CODE = \"C62\";\n\n/** UNCL5153 — the VAT tax scheme identifier. */\nexport const VAT_TAX_SCHEME_ID = \"VAT\";\n\n/** ISO 3166-1 alpha-2 list identifier for `cbc:IdentificationCode`. */\nexport const COUNTRY_CODE_LIST_ID = \"ISO3166-1:Alpha2\";\n\nexport const NS_INVOICE = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nexport const NS_CREDIT_NOTE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\nexport const NS_CAC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\nexport const NS_CBC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\n","/**\n * Minimal, dependency-free XML builder + serializer.\n *\n * UBL is order-sensitive (every element sequence is fixed by the schema), so\n * children are always explicit, ordered arrays. There is no attribute or text\n * coercion magic beyond escaping — the UBL layer is responsible for emitting\n * elements in the right order.\n */\n\nexport type XmlAttrs = Record<string, string | number | null | undefined>;\n\nexport interface XmlElement {\n\tname: string;\n\tattrs?: XmlAttrs;\n\t/** Leaf text content. Mutually exclusive with `children`. */\n\ttext?: string | number | null;\n\t/** Child elements. Mutually exclusive with `text`. */\n\tchildren?: XmlElement[];\n}\n\n/** Falsy children are dropped, so callers can write `cond && el(...)`. */\ntype ChildSpec = XmlElement | null | undefined | false;\n\n/**\n * Build an XML element.\n *\n * el(\"cbc:ID\", null, \"INV-1\") → <cbc:ID>INV-1</cbc:ID>\n * el(\"cbc:Amount\", { currencyID: \"EUR\" }, \"10.00\") → <cbc:Amount currencyID=\"EUR\">10.00</cbc:Amount>\n * el(\"cac:Party\", null, [child, cond && child2]) → nested element\n */\nexport const el = (\n\tname: string,\n\tattrs?: XmlAttrs | null,\n\tcontent?: string | number | null | ChildSpec[],\n): XmlElement => {\n\tif (Array.isArray(content)) {\n\t\treturn {\n\t\t\tname,\n\t\t\tattrs: attrs ?? undefined,\n\t\t\tchildren: content.filter((c): c is XmlElement => Boolean(c)),\n\t\t};\n\t}\n\treturn { name, attrs: attrs ?? undefined, text: content ?? undefined };\n};\n\nconst escapeText = (value: string): string =>\n\tvalue.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\nconst escapeAttr = (value: string): string => escapeText(value).replace(/\"/g, \"&quot;\");\n\nconst serializeAttrs = (attrs: XmlAttrs | undefined): string => {\n\tif (!attrs) return \"\";\n\treturn Object.entries(attrs)\n\t\t.filter(([, value]) => value !== null && value !== undefined)\n\t\t.map(([key, value]) => ` ${key}=\"${escapeAttr(String(value))}\"`)\n\t\t.join(\"\");\n};\n\nconst serializeElement = (node: XmlElement, indentLevel: number): string => {\n\tconst pad = \" \".repeat(indentLevel);\n\tconst attrs = serializeAttrs(node.attrs);\n\n\tif (node.text !== undefined && node.text !== null) {\n\t\treturn `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;\n\t}\n\n\tconst children = node.children ?? [];\n\tif (children.length === 0) {\n\t\treturn `${pad}<${node.name}${attrs}/>`;\n\t}\n\n\tconst inner = children\n\t\t.map((child) => serializeElement(child, indentLevel + 1))\n\t\t.join(\"\\n\");\n\treturn `${pad}<${node.name}${attrs}>\\n${inner}\\n${pad}</${node.name}>`;\n};\n\n/** Serialize a root element into a UTF-8 XML document string. */\nexport const serializeDocument = (root: XmlElement): string =>\n\t`<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${serializeElement(root, 0)}\\n`;\n","import { el, serializeDocument, type XmlElement } from \"../xml\";\nimport {\n\tCOUNTRY_CODE_LIST_ID,\n\tCREDIT_NOTE_TYPE_CODE,\n\tINVOICE_TYPE_CODE,\n\tNS_CAC,\n\tNS_CBC,\n\tNS_CREDIT_NOTE,\n\tNS_INVOICE,\n\tUBL_CUSTOMIZATION_ID,\n\tUBL_PROFILE_ID,\n\tVAT_TAX_SCHEME_ID,\n} from \"./constants\";\nimport type {\n\tUblAddress,\n\tUblAttachment,\n\tUblDocument,\n\tUblLine,\n\tUblParty,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n} from \"./types\";\n\n/** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */\nconst amount = (value: number): string => value.toFixed(2);\n\n/** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */\nconst percent = (value: number): string => {\n\tconst rounded = Math.round(value * 100) / 100;\n\treturn Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);\n};\n\nconst money = (name: string, value: number, currency: string): XmlElement =>\n\tel(name, { currencyID: currency }, amount(value));\n\nconst vatTaxScheme = (): XmlElement =>\n\tel(\"cac:TaxScheme\", null, [el(\"cbc:ID\", null, VAT_TAX_SCHEME_ID)]);\n\n/**\n * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)\n * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption\n * reason for the non-charging categories (E/AE/O/K/G).\n */\nconst taxCategory = (name: string, category: UblTaxCategory): XmlElement =>\n\tel(name, null, [\n\t\tel(\"cbc:ID\", null, category.id),\n\t\tel(\"cbc:Percent\", null, percent(category.percent)),\n\t\tcategory.exemptionReason\n\t\t\t? el(\"cbc:TaxExemptionReason\", null, category.exemptionReason)\n\t\t\t: null,\n\t\tvatTaxScheme(),\n\t]);\n\nconst postalAddress = (address: UblAddress): XmlElement =>\n\tel(\"cac:PostalAddress\", null, [\n\t\taddress.street ? el(\"cbc:StreetName\", null, address.street) : null,\n\t\taddress.additionalStreet\n\t\t\t? el(\"cbc:AdditionalStreetName\", null, address.additionalStreet)\n\t\t\t: null,\n\t\taddress.city ? el(\"cbc:CityName\", null, address.city) : null,\n\t\taddress.postalZone ? el(\"cbc:PostalZone\", null, address.postalZone) : null,\n\t\taddress.countrySubentity\n\t\t\t? el(\"cbc:CountrySubentity\", null, address.countrySubentity)\n\t\t\t: null,\n\t\taddress.countryCode\n\t\t\t? el(\"cac:Country\", null, [\n\t\t\t\t\tel(\n\t\t\t\t\t\t\"cbc:IdentificationCode\",\n\t\t\t\t\t\t{ listID: COUNTRY_CODE_LIST_ID },\n\t\t\t\t\t\taddress.countryCode,\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t: null,\n\t]);\n\nconst party = (source: UblParty): XmlElement =>\n\tel(\"cac:Party\", null, [\n\t\tsource.endpoint\n\t\t\t? el(\n\t\t\t\t\t\"cbc:EndpointID\",\n\t\t\t\t\t{ schemeID: source.endpoint.scheme },\n\t\t\t\t\tsource.endpoint.value,\n\t\t\t\t)\n\t\t\t: null,\n\t\tel(\"cac:PartyName\", null, [el(\"cbc:Name\", null, source.name)]),\n\t\tpostalAddress(source.address),\n\t\tsource.vatNumber\n\t\t\t? el(\"cac:PartyTaxScheme\", null, [\n\t\t\t\t\tel(\"cbc:CompanyID\", null, source.vatNumber),\n\t\t\t\t\tvatTaxScheme(),\n\t\t\t\t])\n\t\t\t: null,\n\t\tel(\"cac:PartyLegalEntity\", null, [\n\t\t\tel(\"cbc:RegistrationName\", null, source.legalName ?? source.name),\n\t\t\tsource.companyId\n\t\t\t\t? el(\n\t\t\t\t\t\t\"cbc:CompanyID\",\n\t\t\t\t\t\tsource.companyId.scheme\n\t\t\t\t\t\t\t? { schemeID: source.companyId.scheme }\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\tsource.companyId.value,\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t]),\n\t]);\n\nconst taxSubtotal = (subtotal: UblTaxSubtotal, currency: string): XmlElement =>\n\tel(\"cac:TaxSubtotal\", null, [\n\t\tmoney(\"cbc:TaxableAmount\", subtotal.taxableAmount, currency),\n\t\tmoney(\"cbc:TaxAmount\", subtotal.taxAmount, currency),\n\t\ttaxCategory(\"cac:TaxCategory\", subtotal.category),\n\t]);\n\nconst line = (\n\tsource: UblLine,\n\tcurrency: string,\n\tdocumentType: UblDocument[\"documentType\"],\n): XmlElement => {\n\tconst lineElementName =\n\t\tdocumentType === \"creditNote\" ? \"cac:CreditNoteLine\" : \"cac:InvoiceLine\";\n\tconst quantityElementName =\n\t\tdocumentType === \"creditNote\" ? \"cbc:CreditedQuantity\" : \"cbc:InvoicedQuantity\";\n\n\treturn el(lineElementName, null, [\n\t\tel(\"cbc:ID\", null, source.id),\n\t\tel(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),\n\t\tmoney(\"cbc:LineExtensionAmount\", source.lineExtensionAmount, currency),\n\t\tel(\"cac:Item\", null, [\n\t\t\tel(\"cbc:Name\", null, source.name),\n\t\t\ttaxCategory(\"cac:ClassifiedTaxCategory\", source.taxCategory),\n\t\t]),\n\t\tel(\"cac:Price\", null, [money(\"cbc:PriceAmount\", source.priceAmount, currency)]),\n\t]);\n};\n\nconst attachmentReference = (attachment: UblAttachment): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tel(\"cbc:ID\", null, attachment.id),\n\t\tel(\"cac:Attachment\", null, [\n\t\t\tel(\n\t\t\t\t\"cbc:EmbeddedDocumentBinaryObject\",\n\t\t\t\t{ mimeCode: attachment.mimeCode, filename: attachment.filename },\n\t\t\t\tattachment.base64,\n\t\t\t),\n\t\t]),\n\t]);\n\nconst billingReference = (precedingInvoiceId: string): XmlElement =>\n\tel(\"cac:BillingReference\", null, [\n\t\tel(\"cac:InvoiceDocumentReference\", null, [\n\t\t\tel(\"cbc:ID\", null, precedingInvoiceId),\n\t\t]),\n\t]);\n\n/** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */\nexport const serializeUblDocument = (doc: UblDocument): string => {\n\tconst isCreditNote = doc.documentType === \"creditNote\";\n\tconst rootName = isCreditNote ? \"CreditNote\" : \"Invoice\";\n\tconst rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;\n\tconst typeCodeElement = isCreditNote\n\t\t? el(\"cbc:CreditNoteTypeCode\", null, CREDIT_NOTE_TYPE_CODE)\n\t\t: el(\"cbc:InvoiceTypeCode\", null, INVOICE_TYPE_CODE);\n\n\tconst children: (XmlElement | null | false)[] = [\n\t\tel(\"cbc:CustomizationID\", null, UBL_CUSTOMIZATION_ID),\n\t\tel(\"cbc:ProfileID\", null, UBL_PROFILE_ID),\n\t\tel(\"cbc:ID\", null, doc.id),\n\t\tel(\"cbc:IssueDate\", null, doc.issueDate),\n\t\t// CreditNote has no DueDate element in the UBL sequence.\n\t\t!isCreditNote && doc.dueDate ? el(\"cbc:DueDate\", null, doc.dueDate) : null,\n\t\ttypeCodeElement,\n\t\tdoc.note ? el(\"cbc:Note\", null, doc.note) : null,\n\t\tel(\"cbc:DocumentCurrencyCode\", null, doc.currency),\n\t\tdoc.buyerReference ? el(\"cbc:BuyerReference\", null, doc.buyerReference) : null,\n\t\tdoc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,\n\t\t...doc.attachments.map(attachmentReference),\n\t\tel(\"cac:AccountingSupplierParty\", null, [party(doc.supplier)]),\n\t\tel(\"cac:AccountingCustomerParty\", null, [party(doc.customer)]),\n\t\tel(\"cac:TaxTotal\", null, [\n\t\t\tmoney(\"cbc:TaxAmount\", doc.taxTotal.taxAmount, doc.currency),\n\t\t\t...doc.taxTotal.subtotals.map((subtotal) =>\n\t\t\t\ttaxSubtotal(subtotal, doc.currency),\n\t\t\t),\n\t\t]),\n\t\tel(\"cac:LegalMonetaryTotal\", null, [\n\t\t\tmoney(\n\t\t\t\t\"cbc:LineExtensionAmount\",\n\t\t\t\tdoc.monetaryTotal.lineExtensionAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\n\t\t\t\t\"cbc:TaxExclusiveAmount\",\n\t\t\t\tdoc.monetaryTotal.taxExclusiveAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\n\t\t\t\t\"cbc:TaxInclusiveAmount\",\n\t\t\t\tdoc.monetaryTotal.taxInclusiveAmount,\n\t\t\t\tdoc.currency,\n\t\t\t),\n\t\t\tmoney(\"cbc:PayableAmount\", doc.monetaryTotal.payableAmount, doc.currency),\n\t\t]),\n\t\t...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),\n\t];\n\n\tconst root = el(\n\t\trootName,\n\t\t{\n\t\t\txmlns: rootNamespace,\n\t\t\t\"xmlns:cac\": NS_CAC,\n\t\t\t\"xmlns:cbc\": NS_CBC,\n\t\t},\n\t\tchildren.filter((child): child is XmlElement => Boolean(child)),\n\t);\n\n\treturn serializeDocument(root);\n};\n","export const isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const normalizeString = (value: unknown): string | null => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\nexport const toNumber = (value: unknown): number => {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\tif (typeof value === \"string\") {\n\t\tconst parsed = Number(value);\n\t\tif (Number.isFinite(parsed)) return parsed;\n\t}\n\treturn 0;\n};\n","import type { UblAddress } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst normalizeCountryCode = (value: string | null | undefined): string | null => {\n\tconst trimmed = normalizeString(value);\n\tif (!trimmed) return null;\n\treturn trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;\n};\n\n/**\n * Normalize a free-form address (Stripe shape, custom shape, or an internal\n * shape) into a {@link UblAddress}.\n *\n * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`\n * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address\n * has no country, but never silently substitutes a caller's country — pass\n * `null` when \"no country\" is the right answer.\n */\nexport const normalizeAddress = (\n\taddress: unknown,\n\tfallbackCountryCode: string | null,\n\tfallbackLine?: string | null,\n): UblAddress => {\n\tconst record = isRecord(address) ? address : {};\n\tconst countryCode =\n\t\tnormalizeCountryCode(normalizeString(record.country)) ??\n\t\tnormalizeCountryCode(normalizeString(record.country_code)) ??\n\t\tnormalizeCountryCode(fallbackCountryCode);\n\treturn {\n\t\tstreet:\n\t\t\tnormalizeString(record.line1) ??\n\t\t\tnormalizeString(record.street) ??\n\t\t\tfallbackLine ??\n\t\t\tnull,\n\t\tadditionalStreet: normalizeString(record.line2),\n\t\tcity: normalizeString(record.city),\n\t\tpostalZone:\n\t\t\tnormalizeString(record.postal_code) ?? normalizeString(record.zip_code),\n\t\tcountrySubentity:\n\t\t\tnormalizeString(record.state) ?? normalizeString(record.country_subentity),\n\t\tcountryCode,\n\t};\n};\n","import type { UblCompanyId, UblEndpoint } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst cleanIdentifierValue = (value: string) =>\n\tvalue\n\t\t.trim()\n\t\t.replace(/\\s+/g, \"\")\n\t\t.replace(/[^A-Za-z0-9]/g, \"\");\n\nconst normalizeBelgianCompanyNumber = (value: string | null | undefined) => {\n\tif (!value) return \"\";\n\treturn cleanIdentifierValue(value).toUpperCase().replace(/^BE/, \"\");\n};\n\n/**\n * Strip whitespace/punctuation from a country-specific company number.\n * For Belgium, also strips an optional `BE` prefix.\n */\nexport const normalizeCompanyNumberForCountry = (\n\tcountryCode: string | null | undefined,\n\tcompanyNumber: string | null | undefined,\n) => {\n\tif (!companyNumber) return \"\";\n\tconst upper = countryCode?.trim().toUpperCase() ?? \"\";\n\tif (upper === \"BE\") return normalizeBelgianCompanyNumber(companyNumber);\n\treturn companyNumber.trim();\n};\n\n/**\n * Country code → Peppol/ISO 6523 ICD scheme for a legal registration number\n * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`).\n *\n * BE → 0208 (Belgian enterprise number, CBE/KBO/BCE)\n * NL → 0106 (Netherlands KvK)\n * FR → 0002 (France SIRENE)\n *\n * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).\n * Returns `null` when the scheme can't be determined, in which case the\n * CompanyID is emitted without a `schemeID` attribute.\n */\nexport const resolveCompanyIdScheme = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): string | null => {\n\tconst companyNumber = normalizeString(params.companyNumber);\n\tif (!companyNumber) return null;\n\n\tconst TABLE: Record<string, string> = {\n\t\tBE: \"0208\",\n\t\tNL: \"0106\",\n\t\tFR: \"0002\",\n\t};\n\n\tconst normalizedCountry =\n\t\tnormalizeString(params.countryCode)?.toUpperCase() ?? null;\n\tif (normalizedCountry && normalizedCountry in TABLE) {\n\t\treturn TABLE[normalizedCountry] ?? null;\n\t}\n\n\tconst countryPrefix = cleanIdentifierValue(companyNumber).toUpperCase().slice(0, 2);\n\treturn countryPrefix in TABLE ? (TABLE[countryPrefix] ?? null) : null;\n};\n\n/**\n * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the\n * country-appropriate ICD scheme when known. Returns `null` when there is no\n * company number.\n */\nexport const buildCompanyId = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): UblCompanyId | null => {\n\tconst normalized = normalizeString(\n\t\tnormalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),\n\t);\n\tif (!normalized) return null;\n\treturn {\n\t\tvalue: normalized,\n\t\tscheme: resolveCompanyIdScheme({\n\t\t\tcountryCode: params.countryCode,\n\t\t\tcompanyNumber: normalized,\n\t\t}),\n\t};\n};\n\n/**\n * Country code → Peppol EAS scheme for a *VAT* identifier, keyed by ISO 3166-1\n * alpha-2. Source: Peppol Code Lists – Participant Identifier Schemes (EAS),\n * Peppol BIS Billing 3.0 (November 2025 release).\n *\n * Only countries that publish a VAT-based EAS scheme appear here. Some (e.g.\n * SE/DK/NO) address Peppol participants by organisation number rather than VAT\n * and are intentionally absent — see {@link resolveCompanyIdScheme}.\n */\nconst VAT_SCHEME_BY_COUNTRY: Record<string, string> = {\n\tAD: \"9922\", // Andorra\n\tAL: \"9923\", // Albania\n\tAT: \"9914\", // Austria\n\tBA: \"9924\", // Bosnia and Herzegovina\n\tBE: \"9925\", // Belgium\n\tBG: \"9926\", // Bulgaria\n\tCH: \"9927\", // Switzerland\n\tCY: \"9928\", // Cyprus\n\tCZ: \"9929\", // Czech Republic\n\tDE: \"9930\", // Germany\n\tEE: \"9931\", // Estonia\n\tES: \"9920\", // Spain (Spanish Tax Administration)\n\tFI: \"0213\", // Finland (Finnish VAT Identifier)\n\tFR: \"9957\", // France\n\tGB: \"9932\", // United Kingdom\n\tGR: \"9933\", // Greece (VAT prefix \"EL\")\n\tHR: \"9934\", // Croatia\n\tHU: \"9910\", // Hungary\n\tIE: \"9935\", // Ireland\n\tLI: \"9936\", // Liechtenstein\n\tLT: \"9937\", // Lithuania\n\tLU: \"9938\", // Luxembourg\n\tLV: \"9939\", // Latvia\n\tMC: \"9940\", // Monaco\n\tME: \"9941\", // Montenegro\n\tMK: \"9942\", // North Macedonia\n\tMT: \"9943\", // Malta\n\tNL: \"9944\", // Netherlands\n\tPL: \"9945\", // Poland\n\tPT: \"9946\", // Portugal\n\tRO: \"9947\", // Romania\n\tRS: \"9948\", // Serbia\n\tSI: \"9949\", // Slovenia\n\tSK: \"9950\", // Slovakia\n\tSM: \"9951\", // San Marino\n\tTR: \"9952\", // Turkey\n\tVA: \"9953\", // Holy See / Vatican City\n};\n\n/**\n * VAT registration prefixes that differ from the ISO 3166-1 alpha-2 country\n * code, so a VAT number's leading two letters still resolve to the right scheme.\n */\nconst VAT_PREFIX_TO_COUNTRY: Record<string, string> = {\n\tEL: \"GR\", // Greece issues VAT numbers with the \"EL\" prefix\n\tXI: \"GB\", // Northern Ireland VAT is issued under the UK scheme\n};\n\n/**\n * Resolve the Peppol participant identifier for a VAT number, deriving the EAS\n * scheme from the number's own country prefix (falling back to `countryCode`).\n *\n * `BE0206582284` → `{ scheme: \"9925\", value: \"BE0206582284\" }`\n *\n * The value keeps its country prefix, matching how participants register (the\n * Peppol directory lists this party as `9925:be0206582284`). Returns `null`\n * when the country has no VAT EAS scheme or the input is empty.\n */\nexport const resolveVatEndpoint = (params: {\n\tvatNumber: string | null | undefined;\n\tcountryCode?: string | null;\n}): UblEndpoint | null => {\n\tconst value = normalizeString(params.vatNumber);\n\tif (!value) return null;\n\tconst cleaned = cleanIdentifierValue(value).toUpperCase();\n\tif (!cleaned) return null;\n\n\tconst prefix = cleaned.slice(0, 2);\n\tconst fromPrefix = /^[A-Z]{2}$/.test(prefix)\n\t\t? (VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix)\n\t\t: null;\n\tconst fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;\n\n\tconst country =\n\t\tfromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;\n\tconst scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : undefined;\n\tif (!scheme) return null;\n\n\treturn { scheme, value: cleaned };\n};\n\n/**\n * Parse a Peppol participant identifier into a {@link UblEndpoint}.\n *\n * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns\n * `null` for values without an explicit scheme, since `cbc:EndpointID` requires\n * a `schemeID` and guessing one would mis-route the document.\n */\nexport const parsePeppolEndpoint = (\n\tpeppolId: string | null | undefined,\n): UblEndpoint | null => {\n\tconst normalized = normalizeString(peppolId);\n\tif (!normalized) return null;\n\tconst separatorIndex = normalized.indexOf(\":\");\n\tif (separatorIndex <= 0) return null;\n\tconst scheme = normalized.slice(0, separatorIndex).trim();\n\tconst value = normalized.slice(separatorIndex + 1).trim();\n\tif (!scheme || !value) return null;\n\treturn { scheme, value };\n};\n\nexport interface CustomerTaxIdentifiers {\n\tpeppolID: string | null;\n\tglnNumber: string | null;\n\ttaxNumber: string | null;\n\tvatNumber: string | null;\n}\n\nconst normalizeIdentifierType = (value: string | null) =>\n\tvalue?.toLowerCase().replace(/[^a-z0-9]+/g, \"_\") ?? null;\n\n/**\n * Pick the first usable Peppol identifier, GLN, VAT number, and tax number\n * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).\n *\n * Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.\n * Peppol IDs are typically stored as a custom `peppol_id` type.\n */\nexport const extractCustomerTaxIdentifiers = (\n\ttaxIds: unknown,\n): CustomerTaxIdentifiers => {\n\tlet peppolID: string | null = null;\n\tlet glnNumber: string | null = null;\n\tlet taxNumber: string | null = null;\n\tlet vatNumber: string | null = null;\n\n\tif (!Array.isArray(taxIds)) {\n\t\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n\t}\n\n\tfor (const entry of taxIds) {\n\t\tif (!isRecord(entry)) continue;\n\n\t\tconst type = normalizeIdentifierType(normalizeString(entry.type));\n\t\tconst value = normalizeString(entry.value);\n\t\tif (!type || !value) continue;\n\n\t\tif (!peppolID && type.includes(\"peppol\")) {\n\t\t\tpeppolID = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!glnNumber && type.includes(\"gln\")) {\n\t\t\tglnNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!vatNumber && type.includes(\"vat\")) {\n\t\t\tvatNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!taxNumber && type.includes(\"tax\")) {\n\t\t\ttaxNumber = value;\n\t\t}\n\t}\n\n\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n};\n\n/**\n * Build the fully-qualified Peppol participant identifiers (`scheme:value`) a\n * receiver lookup will accept, in priority order, de-duplicated.\n *\n * Stripe stores a customer's VAT number without a Peppol scheme (e.g.\n * `BE0206582284`), but a participant lookup needs the qualified identifier\n * (`9925:BE0206582284`). This attaches the right scheme:\n *\n * 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;\n * 2. a GLN under EAS `0088`;\n * 3. the VAT number under its country's VAT EAS scheme (see\n * {@link resolveVatEndpoint});\n * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)\n * under EAS `0208` — many Belgian entities register only under that;\n * 5. a generic tax/registration number under its country's company-ID scheme.\n *\n * `countryCode` (the customer's country, when known) disambiguates schemes for\n * identifiers that don't carry a country prefix (GLN, plain tax numbers).\n */\nexport const listPeppolReceiverIdentifierCandidates = (\n\tcustomer: {\n\t\tpeppolID?: string | null;\n\t\tglnNumber?: string | null;\n\t\ttaxNumber?: string | null;\n\t\tvatNumber?: string | null;\n\t},\n\tcountryCode?: string | null,\n): string[] => {\n\tconst candidates: string[] = [];\n\tconst add = (id: { scheme?: string | null; value: string } | null) => {\n\t\tif (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);\n\t};\n\n\t// 1. An explicit Peppol ID already carries its own scheme.\n\tconst peppol = normalizeString(customer.peppolID);\n\tif (peppol) candidates.push(peppol);\n\n\t// 2. GLN → EAS 0088 (Global Location Number).\n\tconst gln = normalizeString(customer.glnNumber);\n\tif (gln) add({ scheme: \"0088\", value: cleanIdentifierValue(gln) });\n\n\t// 3. VAT number → the country's VAT EAS scheme (e.g. BE → 9925).\n\tconst vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\tadd(vat);\n\n\t// 4. Belgium also reaches parties by enterprise number under EAS 0208; it is\n\t// the VAT digits without the `BE` prefix, and some entities register only so.\n\tif (vat?.scheme === \"9925\") {\n\t\tadd(buildCompanyId({ countryCode: \"BE\", companyNumber: customer.vatNumber ?? null }));\n\t}\n\n\t// 5. A generic tax/registration number → its country's company-ID scheme.\n\tconst tax = normalizeString(customer.taxNumber);\n\tif (tax) add(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));\n\n\treturn Array.from(new Set(candidates));\n};\n","import { normalizeAddress } from \"./address\";\nimport {\n\tbuildCompanyId,\n\tparsePeppolEndpoint,\n\tresolveVatEndpoint,\n} from \"./identifiers\";\nimport type { UblAddress, UblEndpoint, UblParty } from \"./ubl/types\";\nimport { normalizeString } from \"./utils\";\n\n/**\n * Supplier (seller) VAT status. Drives how zero-VAT lines are reported when the\n * seller does not charge VAT:\n *\n * 1 — Subject to VAT (the normal case): line categories come from the data.\n * 2 — Not subject to VAT.\n * 3 — Small business / franchise exemption (e.g. Belgian Article 56bis).\n *\n * For statuses 2 and 3, {@link ../build.ts} coerces all line categories to a\n * non-charging exempt category so no VAT is reported.\n */\nexport type SupplierVatStatus = 1 | 2 | 3;\n\n/**\n * Caller-provided supplier data, normalized into a stable shape.\n *\n * Each consumer builds this from its own data store. Once a `UblSupplier`\n * exists, the party builder no longer needs to know where it came from.\n */\nexport interface UblSupplier {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** ISO 3166-1 alpha-2 country code (e.g. `\"BE\"`). */\n\tcountryCode: string;\n\t/**\n\t * Free-form address. Stripe-style fields (`line1`, `postal_code`, `country`)\n\t * and legacy/internal fields (`street`, `zip_code`) are both accepted.\n\t */\n\taddress: unknown;\n\t/** Country-specific company/registration number (e.g. BE enterprise number). */\n\tcompanyNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n\t/** Whether the supplier charges VAT. See {@link SupplierVatStatus}. */\n\tvatStatus: SupplierVatStatus;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n}\n\n/** Convert a {@link UblSupplier} into the supplier (seller) party. */\nexport const buildSupplierParty = (supplier: UblSupplier): UblParty => {\n\tconst address = normalizeAddress(supplier.address, supplier.countryCode);\n\treturn {\n\t\tendpoint: parsePeppolEndpoint(supplier.peppolID),\n\t\tname: supplier.name,\n\t\taddress,\n\t\tvatNumber: normalizeString(supplier.vatNumber),\n\t\tlegalName: supplier.name,\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode: supplier.countryCode,\n\t\t\tcompanyNumber: supplier.companyNumber ?? null,\n\t\t}),\n\t};\n};\n\n/**\n * Caller-provided customer (buyer) data, normalized into a stable shape.\n *\n * Each consumer (the Stripe adapter, app-specific row builders) resolves its\n * own identifiers and address, then hands this generic shape to\n * {@link buildCustomerParty}, so the Peppol routing logic lives in one place.\n */\nexport interface UblCustomer {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** Customer address, already normalized by the caller. */\n\taddress: UblAddress;\n\t/**\n\t * The customer's ISO 3166-1 alpha-2 country, used to resolve VAT/registration\n\t * schemes for identifiers that don't carry a country prefix. Pass the\n\t * customer's *own* country (never the supplier's) so the document is not\n\t * mis-routed; falls back to the address country when omitted.\n\t */\n\tcountryCode?: string | null;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n\t/** Global Location Number (resolved under EAS `0088`). */\n\tglnNumber?: string | null;\n\t/** Generic tax/registration number (no VAT prefix). */\n\ttaxNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n}\n\n/**\n * Convert a {@link UblCustomer} into the customer (buyer) party.\n *\n * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in\n * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered\n * identifier), then an explicit Peppol ID, then a GLN (scheme `0088`), then the\n * VAT number mapped to its country's VAT EAS scheme (e.g. BE → `9925`). That\n * last step matters because most data stores hold a customer's VAT without a\n * scheme, so without it a VAT-only customer would have no endpoint and the\n * document would be unroutable.\n */\nexport const buildCustomerParty = (\n\tcustomer: UblCustomer,\n\tendpointOverride?: UblEndpoint | null,\n): UblParty => {\n\tconst countryCode =\n\t\tnormalizeString(customer.countryCode) ?? customer.address.countryCode;\n\tconst endpoint =\n\t\tendpointOverride ??\n\t\tparsePeppolEndpoint(customer.peppolID) ??\n\t\t(customer.glnNumber ? { scheme: \"0088\", value: customer.glnNumber } : null) ??\n\t\tresolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\n\treturn {\n\t\tendpoint,\n\t\tname: customer.name,\n\t\taddress: customer.address,\n\t\tvatNumber: normalizeString(customer.vatNumber),\n\t\tlegalName: customer.name,\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode,\n\t\t\tcompanyNumber: customer.taxNumber ?? null,\n\t\t}),\n\t};\n};\n","import type { UblAttachment, UblDocument } from \"./ubl/types\";\n\n/**\n * Build a UBL embedded-document attachment (BG-24) from raw bytes — e.g. the\n * rendered PDF of the invoice. Emitted as a `cac:AdditionalDocumentReference`\n * with an inline base64 `cbc:EmbeddedDocumentBinaryObject`.\n */\nexport const buildPdfAttachment = (params: {\n\tfilename: string;\n\tbytes: Uint8Array;\n\t/** Document reference ID (BT-122). Defaults to the filename. */\n\tid?: string;\n}): UblAttachment => ({\n\tid: params.id ?? params.filename,\n\tfilename: params.filename,\n\tmimeCode: \"application/pdf\",\n\tbase64: Buffer.from(params.bytes).toString(\"base64\"),\n});\n\n/**\n * Replace each attachment's base64 payload with `[omitted]` plus a length, so a\n * {@link UblDocument} is safe to log or persist for audit.\n */\nexport const sanitizeUblDocumentForAudit = (doc: UblDocument): UblDocument => {\n\tif (doc.attachments.length === 0) return doc;\n\treturn {\n\t\t...doc,\n\t\tattachments: doc.attachments.map((attachment) => ({\n\t\t\t...attachment,\n\t\t\tbase64: `[omitted ${attachment.base64.length} chars]`,\n\t\t})),\n\t};\n};\n","/** Round a number to 2 decimal places (cents). */\nexport const roundCurrency = (value: number) =>\n\tMath.round((value + Number.EPSILON) * 100) / 100;\n\n/** Convert an integer cent amount into a 2-decimal currency value. */\nexport const centsToDecimal = (cents: number) => roundCurrency(cents / 100);\n","import type { UblTaxCategory } from \"./ubl/types\";\n\n/**\n * Stripe Tax `taxability_reason` values that map to a VAT-exempt UBL category\n * (`E`). Reverse charge is handled separately (category `AE`).\n */\nexport const EXEMPT_TAXABILITY_REASONS = new Set([\n\t\"customer_exempt\",\n\t\"product_exempt\",\n\t\"not_subject_to_tax\",\n\t\"not_collecting\",\n\t\"not_supported\",\n\t\"portion_product_exempt\",\n]);\n\n/** Human-readable EN 16931 exemption reasons (BR-E-10 / BR-AE-10 / …). */\nconst EXEMPTION_REASON_TEXT: Record<string, string> = {\n\treverse_charge: \"Reverse charge\",\n\tcustomer_exempt: \"Exempt based on customer status\",\n\tproduct_exempt: \"Exempt based on the supplied goods or services\",\n\tportion_product_exempt: \"Exempt based on the supplied goods or services\",\n\tnot_subject_to_tax: \"Not subject to VAT\",\n\tnot_collecting: \"VAT not collected\",\n\tnot_supported: \"VAT not applicable\",\n};\n\nexport interface TaxAmountInfo {\n\tamount: number;\n\ttaxability_reason?: string | null;\n\ttax_rate_percentage?: number | null;\n}\n\nconst normalizeTaxCategoryId = (value: unknown) => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim().toUpperCase();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\n/**\n * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a\n * numeric rate into a {@link UblTaxCategory}.\n *\n * - Reverse charge → `AE` (0%, with exemption reason)\n * - Any other exempt reason → `E` (0%, with exemption reason)\n * - Category `Z` / rate ≤ 0 → `Z` (zero-rated, 0%)\n * - Otherwise → `S` (standard, the line's rate)\n */\nexport const taxCategoryFromReasonOrRate = (params: {\n\ttaxCategoryId?: string | null;\n\ttaxabilityReason: string | null;\n\trate: number;\n}): UblTaxCategory => {\n\tconst categoryHint = normalizeTaxCategoryId(params.taxCategoryId);\n\tconst reason = params.taxabilityReason;\n\n\tif (categoryHint === \"AE\" || reason === \"reverse_charge\") {\n\t\treturn {\n\t\t\tid: \"AE\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.reverse_charge,\n\t\t};\n\t}\n\tif (categoryHint === \"E\" || (reason && EXEMPT_TAXABILITY_REASONS.has(reason))) {\n\t\treturn {\n\t\t\tid: \"E\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason:\n\t\t\t\t(reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? \"Exempt from VAT\",\n\t\t};\n\t}\n\tif (categoryHint === \"Z\" || reason === \"zero_rated\" || params.rate <= 0) {\n\t\treturn { id: \"Z\", percent: 0 };\n\t}\n\treturn { id: \"S\", percent: params.rate };\n};\n\n/**\n * Resolve a {@link UblTaxCategory} from a line's Stripe tax info.\n *\n * Exempt / reverse-charge / zero-rated reasons take precedence over the rate;\n * otherwise the rate decides standard (`S`) vs zero-rated (`Z`).\n */\nexport const resolveTaxCategoryFromTaxAmounts = (\n\ttaxAmounts: TaxAmountInfo[],\n\trate: number,\n): UblTaxCategory => {\n\tfor (const ta of taxAmounts) {\n\t\tif (!ta.taxability_reason) continue;\n\t\tif (ta.taxability_reason === \"reverse_charge\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"reverse_charge\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: ta.taxability_reason,\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (ta.taxability_reason === \"zero_rated\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"zero_rated\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t}\n\treturn taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });\n};\n","import { roundCurrency } from \"./numeric\";\nimport type {\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"./ubl/types\";\n\n/**\n * Adjust the largest line's net amount so the line nets sum to the\n * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).\n *\n * Reconciling at the *line* level — rather than directly on the VAT breakdown —\n * keeps the document consistent bottom-up: the VAT category taxable amounts\n * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the\n * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level\n * coupon; larger ones indicate a real upstream data problem.\n */\nexport const reconcileLinesToExclTotal = (\n\tlines: UblLine[],\n\tauthoritativeTotalExclVat: number,\n): UblLine[] => {\n\tif (lines.length === 0) return lines;\n\tconst computed = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst diff = roundCurrency(authoritativeTotalExclVat - computed);\n\tif (diff === 0) return lines;\n\n\tconst largestIdx = lines.reduce(\n\t\t(maxIdx, line, idx, arr) =>\n\t\t\tline.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0)\n\t\t\t\t? idx\n\t\t\t\t: maxIdx,\n\t\t0,\n\t);\n\n\treturn lines.map((line, idx) => {\n\t\tif (idx !== largestIdx) return line;\n\t\tconst adjusted = roundCurrency(line.lineExtensionAmount + diff);\n\t\treturn {\n\t\t\t...line,\n\t\t\tlineExtensionAmount: adjusted,\n\t\t\tpriceAmount: roundCurrency(adjusted / Math.max(line.quantity, 1)),\n\t\t};\n\t});\n};\n\nconst categoryKey = (category: UblTaxCategory): string =>\n\t`${category.id}:${category.percent}`;\n\nexport interface BuildTaxTotalsResult {\n\ttaxTotal: UblTaxTotal;\n\tmonetaryTotal: UblMonetaryTotal;\n}\n\n/**\n * Group lines by `(category, percent)` into a VAT breakdown and compute the\n * document monetary totals.\n *\n * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,\n * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the\n * upstream per-line tax cents. This guarantees the breakdown is internally\n * consistent and passes validation; it can differ by a cent from the figure a\n * payment processor reported, which is an unavoidable artifact of representing\n * a cents-rounded system as a rate-based VAT breakdown.\n */\nexport const buildTaxTotals = (lines: UblLine[]): BuildTaxTotalsResult => {\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ category: UblTaxCategory; taxableAmount: number }\n\t>();\n\n\tfor (const line of lines) {\n\t\tconst key = categoryKey(line.taxCategory);\n\t\tconst current = groups.get(key) ?? {\n\t\t\tcategory: line.taxCategory,\n\t\t\ttaxableAmount: 0,\n\t\t};\n\t\tcurrent.taxableAmount = roundCurrency(\n\t\t\tcurrent.taxableAmount + line.lineExtensionAmount,\n\t\t);\n\t\tgroups.set(key, current);\n\t}\n\n\tconst subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({\n\t\ttaxableAmount: group.taxableAmount,\n\t\ttaxAmount: roundCurrency((group.taxableAmount * group.category.percent) / 100),\n\t\tcategory: group.category,\n\t}));\n\n\tconst lineExtensionAmount = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst taxAmount = roundCurrency(\n\t\tsubtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0),\n\t);\n\tconst taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);\n\n\treturn {\n\t\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AGjB;AAEF,aAAWA,SAAQ,OAAO;AACzB,UAAM,MAAM,YAAYA,MAAK,WAAW;AACxC,UAAM,UAAU,OAAO,IAAI,GAAG,KAAK;AAAA,MAClC,UAAUA,MAAK;AAAA,MACf,eAAe;AAAA,IAChB;AACA,YAAQ,gBAAgB;AAAA,MACvB,QAAQ,gBAAgBA,MAAK;AAAA,IAC9B;AACA,WAAO,IAAI,KAAK,OAAO;AAAA,EACxB;AAEA,QAAM,YAA8B,MAAM,KAAK,OAAO,OAAO,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,IAC/E,eAAe,MAAM;AAAA,IACrB,WAAW,cAAe,MAAM,gBAAgB,MAAM,SAAS,UAAW,GAAG;AAAA,IAC7E,UAAU,MAAM;AAAA,EACjB,EAAE;AAEF,QAAM,sBAAsB;AAAA,IAC3B,MAAM,OAAO,CAAC,KAAKA,UAAS,MAAMA,MAAK,qBAAqB,CAAC;AAAA,EAC9D;AACA,QAAM,YAAY;AAAA,IACjB,UAAU,OAAO,CAAC,KAAK,aAAa,MAAM,SAAS,WAAW,CAAC;AAAA,EAChE;AACA,QAAM,qBAAqB,cAAc,sBAAsB,SAAS;AAExE,SAAO;AAAA,IACN,UAAU,EAAE,WAAW,UAAU;AAAA,IACjC,eAAe;AAAA,MACd;AAAA,MACA,oBAAoB;AAAA,MACpB;AAAA,MACA,eAAe;AAAA,IAChB;AAAA,EACD;AACD;","names":["line"]}
package/dist/index.d.ts CHANGED
@@ -196,6 +196,33 @@ interface InvoiceExtractionDTO {
196
196
  };
197
197
  }
198
198
 
199
+ /**
200
+ * An embedded attachment extracted from a UBL document's
201
+ * `AdditionalDocumentReference` entries, with its binary content still
202
+ * base64-encoded. `sizeBytes` is the approximate decoded size.
203
+ */
204
+ interface UblEmbeddedAttachment {
205
+ id: string | null;
206
+ filename: string;
207
+ mimeCode: string;
208
+ sizeBytes: number;
209
+ /** Zero-based position among the document's embedded attachments. */
210
+ lineOrder: number;
211
+ base64Content: string;
212
+ }
213
+ /**
214
+ * Extract the embedded attachments (typically the human-readable PDF) from a
215
+ * UBL invoice or credit note XML. Attachments referenced only by external URI
216
+ * (no `EmbeddedDocumentBinaryObject`) are skipped; use {@link parseUblInvoice}
217
+ * directly when those matter.
218
+ */
219
+ declare const extractUblEmbeddedAttachments: (xml: string) => UblEmbeddedAttachment[];
220
+ /**
221
+ * Whether an attachment looks like a PDF, by MIME type first and filename
222
+ * extension as a fallback.
223
+ */
224
+ declare const isPdfLikeAttachment: (attachment: Pick<UblAttachment, "filename" | "mimeCode">) => boolean;
225
+
199
226
  declare function parseUblInvoice(xml: string): UblInvoice | null;
200
227
 
201
228
  /**
@@ -269,4 +296,4 @@ declare const parseUblInvoiceDocument: (params: {
269
296
  providerJobId: string | null;
270
297
  };
271
298
 
272
- export { type InvoiceExtractionDTO, PEPPOL_MLR_DOCUMENT_TYPE_VALUE, PEPPOL_MLR_PROCESS_VALUE, type PeppolMessageLevelResponse, type UblAddress, type UblAllowanceCharge, type UblAttachment, type UblBillingReference, type UblContact, type UblDelivery, type UblDocumentReference, type UblInvoice, type UblInvoicePeriod, type UblItemProperty, type UblLine, type UblMonetaryTotal, type UblParty, type UblPartyIdentification, type UblPaymentMeans, type UblTaxSubtotal, decodeXmlBytes, isPeppolMessageLevelResponse, normalizeCurrency, normalizeUblResponse, parseDate, parsePeppolMessageLevelResponse, parseUblInvoice, parseUblInvoiceDocument };
299
+ export { type InvoiceExtractionDTO, PEPPOL_MLR_DOCUMENT_TYPE_VALUE, PEPPOL_MLR_PROCESS_VALUE, type PeppolMessageLevelResponse, type UblAddress, type UblAllowanceCharge, type UblAttachment, type UblBillingReference, type UblContact, type UblDelivery, type UblDocumentReference, type UblEmbeddedAttachment, type UblInvoice, type UblInvoicePeriod, type UblItemProperty, type UblLine, type UblMonetaryTotal, type UblParty, type UblPartyIdentification, type UblPaymentMeans, type UblTaxSubtotal, decodeXmlBytes, extractUblEmbeddedAttachments, isPdfLikeAttachment, isPeppolMessageLevelResponse, normalizeCurrency, normalizeUblResponse, parseDate, parsePeppolMessageLevelResponse, parseUblInvoice, parseUblInvoiceDocument };
package/dist/index.js CHANGED
@@ -429,6 +429,30 @@ function parseUblInvoice(xml) {
429
429
  }
430
430
  }
431
431
 
432
+ // src/attachments.ts
433
+ var base64DecodedSize = (base64) => Math.round(base64.length * 3 / 4);
434
+ var extractUblEmbeddedAttachments = (xml) => {
435
+ const parsed = parseUblInvoice(xml);
436
+ if (!parsed?.attachments || parsed.attachments.length === 0) return [];
437
+ return parsed.attachments.map((attachment, index) => {
438
+ const base64Content = attachment.base64Content?.trim();
439
+ if (!base64Content) return null;
440
+ return {
441
+ id: attachment.id || null,
442
+ filename: attachment.filename || `attachment-${index + 1}`,
443
+ mimeCode: attachment.mimeCode || "application/octet-stream",
444
+ sizeBytes: base64DecodedSize(base64Content),
445
+ lineOrder: index,
446
+ base64Content
447
+ };
448
+ }).filter((entry) => entry !== null);
449
+ };
450
+ var isPdfLikeAttachment = (attachment) => {
451
+ const mimeCode = attachment.mimeCode?.toLowerCase() ?? "";
452
+ if (mimeCode === "application/pdf" || mimeCode.endsWith("/pdf")) return true;
453
+ return attachment.filename?.toLowerCase().endsWith(".pdf") ?? false;
454
+ };
455
+
432
456
  // src/mlr.ts
433
457
  import { DOMParser as XmlDomParser2 } from "@xmldom/xmldom";
434
458
  var CBC_NS2 = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
@@ -802,6 +826,8 @@ export {
802
826
  PEPPOL_MLR_DOCUMENT_TYPE_VALUE,
803
827
  PEPPOL_MLR_PROCESS_VALUE,
804
828
  decodeXmlBytes,
829
+ extractUblEmbeddedAttachments,
830
+ isPdfLikeAttachment,
805
831
  isPeppolMessageLevelResponse,
806
832
  normalizeCurrency,
807
833
  normalizeUblResponse,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/parser.ts","../src/mlr.ts","../src/normalize.ts"],"sourcesContent":["import { DOMParser as XmlDomParser } from \"@xmldom/xmldom\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\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\";\n\nconst CBC_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nconst CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n// --- DOM helpers ---\n\nfunction cbcText(parent: Element, tag: string): string {\n\tconst el = parent.getElementsByTagNameNS(CBC_NS, tag)[0];\n\treturn el?.textContent?.trim() ?? \"\";\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\nfunction cbcNumber(parent: Element, tag: string): number {\n\tconst n = Number.parseFloat(cbcText(parent, tag));\n\treturn Number.isNaN(n) ? 0 : n;\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 {\n\tconst el = childElementsByTagNs(parent, CBC_NS, tag)[0];\n\treturn el?.textContent?.trim() ?? \"\";\n}\n\nfunction cbcDirectNumber(parent: Element, tag: string): number | null {\n\tconst value = cbcDirectText(parent, tag);\n\tif (!value) return null;\n\tconst parsed = Number.parseFloat(value);\n\treturn Number.isNaN(parsed) ? null : parsed;\n}\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\") || undefined,\n\t\tcity: cbcText(address, \"CityName\"),\n\t\tpostalZone: cbcText(address, \"PostalZone\"),\n\t\tcountrySubentity: cbcText(address, \"CountrySubentity\") || undefined,\n\t\tcountryCode: country ? cbcText(country, \"IdentificationCode\") : \"\",\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\") || undefined;\n}\n\nfunction parseContact(party: Element): import(\"./types.js\").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 {\n\t\tname: name || undefined,\n\t\tphone: phone || undefined,\n\t\temail: email || undefined,\n\t};\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\tconst schemeIdAttr = idEl\n\t\t\t.getElementsByTagNameNS(CBC_NS, \"ID\")[0]\n\t\t\t?.getAttribute(\"schemeID\");\n\t\tresult.push({\n\t\t\tid: idValue,\n\t\t\tschemeId: schemeIdAttr || undefined,\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 { name: \"Unknown\" };\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\") : \"\",\n\t\tregistrationName: legalEntity\n\t\t\t? cbcText(legalEntity, \"RegistrationName\") || undefined\n\t\t\t: undefined,\n\t\tcompanyLegalForm: legalEntity\n\t\t\t? cbcText(legalEntity, \"CompanyLegalForm\") || undefined\n\t\t\t: undefined,\n\t\tvatId: taxScheme ? cbcText(taxScheme, \"CompanyID\") || undefined : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxScheme),\n\t\tcompanyId: companyIdEl\n\t\t\t? companyIdEl.textContent?.trim() || undefined\n\t\t\t: partyId\n\t\t\t\t? cbcText(partyId, \"ID\") || undefined\n\t\t\t\t: undefined,\n\t\tcompanyIdSchemeId: companyIdEl?.getAttribute(\"schemeID\") || undefined,\n\t\tendpointId: endpointEl?.textContent?.trim() || undefined,\n\t\tendpointSchemeId: endpointEl?.getAttribute(\"schemeID\") || 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\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: (cat ? cbcNumber(cat, \"Percent\") : 0) || cbcNumber(sub, \"Percent\"),\n\t\ttaxCategoryId: cat ? cbcText(cat, \"ID\") || undefined : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(cat),\n\t\ttaxExemptionReason: cat\n\t\t\t? cbcText(cat, \"TaxExemptionReason\") || undefined\n\t\t\t: 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\") ?? undefined,\n\t\tmultiplierFactorNumeric:\n\t\t\tcbcDirectNumber(charge, \"MultiplierFactorNumeric\") ?? undefined,\n\t\treason: cbcText(charge, \"AllowanceChargeReason\") || undefined,\n\t\treasonCode: cbcText(charge, \"AllowanceChargeReasonCode\") || undefined,\n\t\ttaxPercent: taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined,\n\t\ttaxCategoryId: taxCategory\n\t\t\t? cbcText(taxCategory, \"ID\") || undefined\n\t\t\t: 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,\n\t\t\t0,\n\t\t);\n\t\tconst taxAmountFromLineTotal = lineTaxTotal\n\t\t\t? cbcDirectNumber(lineTaxTotal, \"TaxAmount\")\n\t\t\t: null;\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\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),\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) : 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\") : 0;\n\t\tconst priceBaseQuantity = price ? cbcDirectNumber(price, \"BaseQuantity\") : null;\n\t\tconst unitPrice =\n\t\t\tpriceBaseQuantity && priceBaseQuantity > 0\n\t\t\t\t? priceAmount / priceBaseQuantity\n\t\t\t\t: priceAmount;\n\n\t\treturn {\n\t\t\tid: cbcText(line, \"ID\"),\n\t\t\tdescription: item ? cbcText(item, \"Description\") : \"\",\n\t\t\tquantity: cbcNumber(line, qtyTag),\n\t\t\tunitCode: qtyEl?.getAttribute(\"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 : 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 : undefined,\n\t\t\tsellersItemId: sellersId\n\t\t\t\t? cbcText(sellersId, \"ID\") || undefined\n\t\t\t\t: undefined,\n\t\t\tbuyersItemId: buyersId ? cbcText(buyersId, \"ID\") || undefined : 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};\n\t});\n}\n\nfunction parseMonetaryTotal(root: Element): UblMonetaryTotal {\n\tconst total = cacDirectElement(root, \"LegalMonetaryTotal\");\n\tif (!total) {\n\t\treturn {\n\t\t\tlineExtensionAmount: 0,\n\t\t\ttaxExclusiveAmount: 0,\n\t\t\ttaxInclusiveAmount: 0,\n\t\t\tpayableAmount: 0,\n\t\t};\n\t}\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\") || undefined,\n\t\tchargeTotalAmount: cbcNumber(total, \"ChargeTotalAmount\") || undefined,\n\t\tprepaidAmount: cbcNumber(total, \"PrepaidAmount\") || undefined,\n\t\tpayableRoundingAmount: cbcNumber(total, \"PayableRoundingAmount\") || undefined,\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: paymentMeansCodeEl?.getAttribute(\"name\") || undefined,\n\t\tpaymentId: cbcText(pm, \"PaymentID\") || undefined,\n\t\tiban: account ? cbcText(account, \"ID\") || undefined : undefined,\n\t\tbic: branch ? cbcText(branch, \"ID\") || undefined : undefined,\n\t\taccountName: (account && cbcText(account, \"Name\")) || undefined,\n\t\tmandateId: mandate ? cbcText(mandate, \"ID\") || undefined : 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\nfunction parseInvoicePeriod(root: Element): UblInvoicePeriod | undefined {\n\tconst period = cacElement(root, \"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 || undefined,\n\t\tendDate: end || undefined,\n\t\tdescriptionCode: cbcText(period, \"DescriptionCode\") || undefined,\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\") || undefined;\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\tconst note = cbcText(paymentTerms, \"Note\");\n\treturn note || undefined;\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\") || undefined;\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: binaryEl.getAttribute(\"filename\") || undefined,\n\t\t\t\t\tmimeCode: binaryEl.getAttribute(\"mimeCode\") || undefined,\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\") || undefined;\n\tconst invoiceIssueDate = cbcText(invoiceRef, \"IssueDate\") || undefined;\n\tif (!invoiceId && !invoiceIssueDate) return undefined;\n\treturn { invoiceId, invoiceIssueDate };\n}\n\n// --- Main parser ---\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove\n * DOCTYPE blocks (including inline DTD subsets) before parsing.\n */\nconst stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\nexport function parseUblInvoice(xml: string): UblInvoice | null {\n\ttry {\n\t\tconst safeXml = stripDoctype(xml);\n\t\tconst BrowserDomParser = globalThis.DOMParser as\n\t\t\t| typeof XmlDomParser\n\t\t\t| undefined;\n\t\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\t\tconst doc = parser.parseFromString(safeXml, \"text/xml\");\n\t\tif (doc.getElementsByTagName(\"parsererror\").length > 0) return null;\n\n\t\tconst root = doc.documentElement;\n\t\tconst localName = root.localName;\n\n\t\tlet documentType: \"Invoice\" | \"CreditNote\";\n\t\tif (localName === \"Invoice\") {\n\t\t\tdocumentType = \"Invoice\";\n\t\t} else if (localName === \"CreditNote\") {\n\t\t\tdocumentType = \"CreditNote\";\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst isCreditNote = documentType === \"CreditNote\";\n\t\tconst id = cbcText(root, \"ID\");\n\t\tif (!id) return null;\n\t\tconst paymentMeansList = parsePaymentMeansList(root);\n\t\tconst orderReference = cacElement(root, \"OrderReference\");\n\t\tconst contractReference = cacElement(root, \"ContractDocumentReference\");\n\t\tconst projectReference = cacElement(root, \"ProjectReference\");\n\t\tconst { attachments, documentReferences } = parseAttachments(root);\n\n\t\treturn {\n\t\t\tdocumentType,\n\t\t\tcustomizationId: cbcText(root, \"CustomizationID\") || undefined,\n\t\t\tprofileId: cbcText(root, \"ProfileID\") || undefined,\n\t\t\tid,\n\t\t\tinvoiceTypeCode:\n\t\t\t\tcbcText(root, \"InvoiceTypeCode\") ||\n\t\t\t\tcbcText(root, \"CreditNoteTypeCode\") ||\n\t\t\t\tundefined,\n\t\t\tissueDate: cbcText(root, \"IssueDate\"),\n\t\t\tdueDate: cbcText(root, \"DueDate\") || undefined,\n\t\t\ttaxPointDate: cbcText(root, \"TaxPointDate\") || undefined,\n\t\t\tcurrency: cbcText(root, \"DocumentCurrencyCode\"),\n\t\t\tbuyerReference: cbcText(root, \"BuyerReference\") || undefined,\n\t\t\torderReference: orderReference ? cbcText(orderReference, \"ID\") : undefined,\n\t\t\tsalesOrderId: orderReference\n\t\t\t\t? cbcText(orderReference, \"SalesOrderID\") || undefined\n\t\t\t\t: undefined,\n\t\t\tcontractReference: contractReference\n\t\t\t\t? cbcText(contractReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tprojectReference: projectReference\n\t\t\t\t? cbcText(projectReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tbillingReference: parseBillingReference(root),\n\t\t\tseller: parseParty(root, \"AccountingSupplierParty\"),\n\t\t\tbuyer: parseParty(root, \"AccountingCustomerParty\"),\n\t\t\tdelivery: parseDelivery(root),\n\t\t\tlines: parseLines(root, isCreditNote),\n\t\t\ttaxSubtotals: parseTaxSubtotals(root),\n\t\t\tmonetaryTotal: parseMonetaryTotal(root),\n\t\t\tpaymentMeansList,\n\t\t\tpaymentMeans: paymentMeansList?.[0],\n\t\t\tinvoicePeriod: parseInvoicePeriod(root),\n\t\t\tnote: parseNotes(root),\n\t\t\tpaymentTermsNote: parsePaymentTermsNote(root),\n\t\t\tattachments,\n\t\t\tdocumentReferences,\n\t\t\tallowanceCharges: parseAllowanceCharges(root),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import { DOMParser as XmlDomParser } from \"@xmldom/xmldom\";\n\nconst CBC_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nconst CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\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 nullable: a given MLR may omit any of them.\n */\nexport interface PeppolMessageLevelResponse {\n\tcustomizationId: string | null;\n\tprofileId: string | null;\n\tresponseId: string | null;\n\tissueDate: string | null;\n\tissueTime: string | null;\n\treferencedDocumentId: string | null;\n\tresponseCode: string | null;\n\tdescription: string | null;\n\t/** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */\n\tsenderIdentifier: string | null;\n\t/** Receiver participant id as `schemeID:value`. */\n\treceiverIdentifier: string | null;\n}\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 */\nconst stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\nconst parseXmlDocument = (xml: string): Document | null => {\n\tconst safeXml = stripDoctype(xml);\n\tconst BrowserDomParser = globalThis.DOMParser as typeof XmlDomParser | undefined;\n\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\tconst doc = parser.parseFromString(safeXml, \"text/xml\");\n\tif (doc.getElementsByTagName(\"parsererror\").length > 0) return null;\n\treturn doc;\n};\n\nconst trimmed = (value: string | null | undefined): string | null => {\n\tconst text = value?.trim();\n\treturn text ? text : null;\n};\n\n/** First descendant CBC element's trimmed text, or null. */\nconst cbcText = (parent: Element, tag: string): string | null =>\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 | null => {\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 null;\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 | null => {\n\tif (!party) return null;\n\tconst endpoint = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tif (!endpoint) return null;\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 is not\n * parseable or contains no ApplicationResponse.\n */\nconst findApplicationResponse = (xml: string): Element | null => {\n\tlet doc: Document | null;\n\ttry {\n\t\tdoc = parseXmlDocument(xml);\n\t} catch {\n\t\treturn null;\n\t}\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\treturn findApplicationResponse(xml) !== null;\n};\n\n/**\n * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping\n * an SBDH envelope when present. Throws when the XML is not an\n * ApplicationResponse.\n */\nexport const parsePeppolMessageLevelResponse = (\n\txml: string,\n): PeppolMessageLevelResponse => {\n\tconst root = findApplicationResponse(xml);\n\tif (!root) {\n\t\tthrow new Error(\"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: null,\n\t\tresponseCode: response ? cbcText(response, \"ResponseCode\") : null,\n\t\tdescription: response ? cbcText(response, \"Description\") : null,\n\t\tsenderIdentifier: endpointIdentifier(cacElement(root, \"SenderParty\")),\n\t\treceiverIdentifier: endpointIdentifier(cacElement(root, \"ReceiverParty\")),\n\t};\n};\n","import { parseUblInvoice } from \"./parser.js\";\nimport type {\n\tInvoiceExtractionDTO,\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblInvoice,\n} from \"./types.js\";\n\n// --- Utility helpers ---\n\nconst UTF8_BOM = 0xfeff;\n\nconst normalizeText = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst upper = trimmed.toUpperCase();\n\tif (upper === \"NA\" || upper === \"N/A\") return null;\n\treturn trimmed;\n};\n\nconst toNumberOrNull = (value: number | null | undefined): number | null =>\n\tNumber.isFinite(value ?? Number.NaN) ? (value as number) : null;\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\n// --- Address helpers ---\n\nconst addressToString = (address?: UblAddress): string | null => {\n\tif (!address) return null;\n\tconst street = [address.street, address.additionalStreet]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst cityLine = [address.postalZone, address.city]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst countryLine = [address.countrySubentity, address.countryCode]\n\t\t.filter((part) => part && part.trim().length > 0)\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 = [address.street, address.additionalStreet]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst result = {\n\t\tline1: normalizeText(line1),\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 base64ByteLength = (content: string) => {\n\tconst sanitized = content.replace(/\\s+/g, \"\");\n\tif (!sanitized) return 0;\n\tconst paddingLength = sanitized.endsWith(\"==\")\n\t\t? 2\n\t\t: sanitized.endsWith(\"=\")\n\t\t\t? 1\n\t\t\t: 0;\n\treturn Math.floor((sanitized.length * 3) / 4) - paddingLength;\n};\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: attachment.base64Content\n\t\t\t? base64ByteLength(attachment.base64Content)\n\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) => {\n\tconst subtotalSum = ubl.taxSubtotals.reduce(\n\t\t(sum, subtotal) => sum + subtotal.taxAmount,\n\t\t0,\n\t);\n\tif (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) {\n\t\treturn subtotalSum;\n\t}\n\treturn ubl.monetaryTotal.taxInclusiveAmount - ubl.monetaryTotal.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);\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 */\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 Error(\"Failed to parse UBL invoice XML\");\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 amountPaid =\n\t\tprepaidAmount ??\n\t\t(total !== null && amountDue !== null && total > amountDue\n\t\t\t? toNumberOrNull(total - amountDue)\n\t\t\t: null);\n\tconst taxTotal = toNumberOrNull(sumTaxTotal(ubl));\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\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\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\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? {\n\t\t\t\t\t\t\tcode: normalizeText(ubl.paymentMeans.code),\n\t\t\t\t\t\t\tcode_name: normalizeText(ubl.paymentMeans.codeName),\n\t\t\t\t\t\t\tpayment_id: normalizeText(ubl.paymentMeans.paymentId),\n\t\t\t\t\t\t\tiban: normalizeText(ubl.paymentMeans.iban),\n\t\t\t\t\t\t\tbic: normalizeText(ubl.paymentMeans.bic),\n\t\t\t\t\t\t\taccount_name: normalizeText(ubl.paymentMeans.accountName),\n\t\t\t\t\t\t\tmandate_id: normalizeText(ubl.paymentMeans.mandateId),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tpayment_means_list: paymentMeansList.map((item) => ({\n\t\t\t\t\tcode: normalizeText(item.code),\n\t\t\t\t\tcode_name: normalizeText(item.codeName),\n\t\t\t\t\tpayment_id: normalizeText(item.paymentId),\n\t\t\t\t\tiban: normalizeText(item.iban),\n\t\t\t\t\tbic: normalizeText(item.bic),\n\t\t\t\t\taccount_name: normalizeText(item.accountName),\n\t\t\t\t\tmandate_id: normalizeText(item.mandateId),\n\t\t\t\t})),\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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U;AAAA,QACV,cAAc;AAAA,QACd,eAAe;AAAA,MAChB;AAAA,IACD;AAAA,EACD;AAEA,SAAO;AAAA,IACN;AAAA,IACA,YAAY;AAAA,MACX,QAAQ;AAAA,MACR,SAAS,eAAe,GAAG;AAAA,IAC5B;AAAA,EACD;AACD;AAKO,IAAM,0BAA0B,CAAC,WAIlC;AACL,QAAM,MAAM,eAAe,OAAO,KAAK;AACvC,QAAM,EAAE,WAAW,WAAW,IAAI,qBAAqB,KAAK,OAAO,UAAU;AAC7E,SAAO;AAAA,IACN,YAAY;AAAA,MACX,GAAG;AAAA,MACH,WAAW,OAAO;AAAA,IACnB;AAAA,IACA;AAAA,IACA,eAAe;AAAA,EAChB;AACD;","names":["XmlDomParser","CBC_NS","CAC_NS","stripDoctype","cbcText","cbcDirectText","cacElement","trimmed"]}
1
+ {"version":3,"sources":["../src/parser.ts","../src/attachments.ts","../src/mlr.ts","../src/normalize.ts"],"sourcesContent":["import { DOMParser as XmlDomParser } from \"@xmldom/xmldom\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\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\";\n\nconst CBC_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nconst CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n// --- DOM helpers ---\n\nfunction cbcText(parent: Element, tag: string): string {\n\tconst el = parent.getElementsByTagNameNS(CBC_NS, tag)[0];\n\treturn el?.textContent?.trim() ?? \"\";\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\nfunction cbcNumber(parent: Element, tag: string): number {\n\tconst n = Number.parseFloat(cbcText(parent, tag));\n\treturn Number.isNaN(n) ? 0 : n;\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 {\n\tconst el = childElementsByTagNs(parent, CBC_NS, tag)[0];\n\treturn el?.textContent?.trim() ?? \"\";\n}\n\nfunction cbcDirectNumber(parent: Element, tag: string): number | null {\n\tconst value = cbcDirectText(parent, tag);\n\tif (!value) return null;\n\tconst parsed = Number.parseFloat(value);\n\treturn Number.isNaN(parsed) ? null : parsed;\n}\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\") || undefined,\n\t\tcity: cbcText(address, \"CityName\"),\n\t\tpostalZone: cbcText(address, \"PostalZone\"),\n\t\tcountrySubentity: cbcText(address, \"CountrySubentity\") || undefined,\n\t\tcountryCode: country ? cbcText(country, \"IdentificationCode\") : \"\",\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\") || undefined;\n}\n\nfunction parseContact(party: Element): import(\"./types.js\").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 {\n\t\tname: name || undefined,\n\t\tphone: phone || undefined,\n\t\temail: email || undefined,\n\t};\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\tconst schemeIdAttr = idEl\n\t\t\t.getElementsByTagNameNS(CBC_NS, \"ID\")[0]\n\t\t\t?.getAttribute(\"schemeID\");\n\t\tresult.push({\n\t\t\tid: idValue,\n\t\t\tschemeId: schemeIdAttr || undefined,\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 { name: \"Unknown\" };\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\") : \"\",\n\t\tregistrationName: legalEntity\n\t\t\t? cbcText(legalEntity, \"RegistrationName\") || undefined\n\t\t\t: undefined,\n\t\tcompanyLegalForm: legalEntity\n\t\t\t? cbcText(legalEntity, \"CompanyLegalForm\") || undefined\n\t\t\t: undefined,\n\t\tvatId: taxScheme ? cbcText(taxScheme, \"CompanyID\") || undefined : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxScheme),\n\t\tcompanyId: companyIdEl\n\t\t\t? companyIdEl.textContent?.trim() || undefined\n\t\t\t: partyId\n\t\t\t\t? cbcText(partyId, \"ID\") || undefined\n\t\t\t\t: undefined,\n\t\tcompanyIdSchemeId: companyIdEl?.getAttribute(\"schemeID\") || undefined,\n\t\tendpointId: endpointEl?.textContent?.trim() || undefined,\n\t\tendpointSchemeId: endpointEl?.getAttribute(\"schemeID\") || 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\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: (cat ? cbcNumber(cat, \"Percent\") : 0) || cbcNumber(sub, \"Percent\"),\n\t\ttaxCategoryId: cat ? cbcText(cat, \"ID\") || undefined : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(cat),\n\t\ttaxExemptionReason: cat\n\t\t\t? cbcText(cat, \"TaxExemptionReason\") || undefined\n\t\t\t: 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\") ?? undefined,\n\t\tmultiplierFactorNumeric:\n\t\t\tcbcDirectNumber(charge, \"MultiplierFactorNumeric\") ?? undefined,\n\t\treason: cbcText(charge, \"AllowanceChargeReason\") || undefined,\n\t\treasonCode: cbcText(charge, \"AllowanceChargeReasonCode\") || undefined,\n\t\ttaxPercent: taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined,\n\t\ttaxCategoryId: taxCategory\n\t\t\t? cbcText(taxCategory, \"ID\") || undefined\n\t\t\t: 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,\n\t\t\t0,\n\t\t);\n\t\tconst taxAmountFromLineTotal = lineTaxTotal\n\t\t\t? cbcDirectNumber(lineTaxTotal, \"TaxAmount\")\n\t\t\t: null;\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\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),\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) : 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\") : 0;\n\t\tconst priceBaseQuantity = price ? cbcDirectNumber(price, \"BaseQuantity\") : null;\n\t\tconst unitPrice =\n\t\t\tpriceBaseQuantity && priceBaseQuantity > 0\n\t\t\t\t? priceAmount / priceBaseQuantity\n\t\t\t\t: priceAmount;\n\n\t\treturn {\n\t\t\tid: cbcText(line, \"ID\"),\n\t\t\tdescription: item ? cbcText(item, \"Description\") : \"\",\n\t\t\tquantity: cbcNumber(line, qtyTag),\n\t\t\tunitCode: qtyEl?.getAttribute(\"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 : 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 : undefined,\n\t\t\tsellersItemId: sellersId\n\t\t\t\t? cbcText(sellersId, \"ID\") || undefined\n\t\t\t\t: undefined,\n\t\t\tbuyersItemId: buyersId ? cbcText(buyersId, \"ID\") || undefined : 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};\n\t});\n}\n\nfunction parseMonetaryTotal(root: Element): UblMonetaryTotal {\n\tconst total = cacDirectElement(root, \"LegalMonetaryTotal\");\n\tif (!total) {\n\t\treturn {\n\t\t\tlineExtensionAmount: 0,\n\t\t\ttaxExclusiveAmount: 0,\n\t\t\ttaxInclusiveAmount: 0,\n\t\t\tpayableAmount: 0,\n\t\t};\n\t}\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\") || undefined,\n\t\tchargeTotalAmount: cbcNumber(total, \"ChargeTotalAmount\") || undefined,\n\t\tprepaidAmount: cbcNumber(total, \"PrepaidAmount\") || undefined,\n\t\tpayableRoundingAmount: cbcNumber(total, \"PayableRoundingAmount\") || undefined,\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: paymentMeansCodeEl?.getAttribute(\"name\") || undefined,\n\t\tpaymentId: cbcText(pm, \"PaymentID\") || undefined,\n\t\tiban: account ? cbcText(account, \"ID\") || undefined : undefined,\n\t\tbic: branch ? cbcText(branch, \"ID\") || undefined : undefined,\n\t\taccountName: (account && cbcText(account, \"Name\")) || undefined,\n\t\tmandateId: mandate ? cbcText(mandate, \"ID\") || undefined : 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\nfunction parseInvoicePeriod(root: Element): UblInvoicePeriod | undefined {\n\tconst period = cacElement(root, \"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 || undefined,\n\t\tendDate: end || undefined,\n\t\tdescriptionCode: cbcText(period, \"DescriptionCode\") || undefined,\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\") || undefined;\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\tconst note = cbcText(paymentTerms, \"Note\");\n\treturn note || undefined;\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\") || undefined;\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: binaryEl.getAttribute(\"filename\") || undefined,\n\t\t\t\t\tmimeCode: binaryEl.getAttribute(\"mimeCode\") || undefined,\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\") || undefined;\n\tconst invoiceIssueDate = cbcText(invoiceRef, \"IssueDate\") || undefined;\n\tif (!invoiceId && !invoiceIssueDate) return undefined;\n\treturn { invoiceId, invoiceIssueDate };\n}\n\n// --- Main parser ---\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove\n * DOCTYPE blocks (including inline DTD subsets) before parsing.\n */\nconst stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\nexport function parseUblInvoice(xml: string): UblInvoice | null {\n\ttry {\n\t\tconst safeXml = stripDoctype(xml);\n\t\tconst BrowserDomParser = globalThis.DOMParser as\n\t\t\t| typeof XmlDomParser\n\t\t\t| undefined;\n\t\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\t\tconst doc = parser.parseFromString(safeXml, \"text/xml\");\n\t\tif (doc.getElementsByTagName(\"parsererror\").length > 0) return null;\n\n\t\tconst root = doc.documentElement;\n\t\tconst localName = root.localName;\n\n\t\tlet documentType: \"Invoice\" | \"CreditNote\";\n\t\tif (localName === \"Invoice\") {\n\t\t\tdocumentType = \"Invoice\";\n\t\t} else if (localName === \"CreditNote\") {\n\t\t\tdocumentType = \"CreditNote\";\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst isCreditNote = documentType === \"CreditNote\";\n\t\tconst id = cbcText(root, \"ID\");\n\t\tif (!id) return null;\n\t\tconst paymentMeansList = parsePaymentMeansList(root);\n\t\tconst orderReference = cacElement(root, \"OrderReference\");\n\t\tconst contractReference = cacElement(root, \"ContractDocumentReference\");\n\t\tconst projectReference = cacElement(root, \"ProjectReference\");\n\t\tconst { attachments, documentReferences } = parseAttachments(root);\n\n\t\treturn {\n\t\t\tdocumentType,\n\t\t\tcustomizationId: cbcText(root, \"CustomizationID\") || undefined,\n\t\t\tprofileId: cbcText(root, \"ProfileID\") || undefined,\n\t\t\tid,\n\t\t\tinvoiceTypeCode:\n\t\t\t\tcbcText(root, \"InvoiceTypeCode\") ||\n\t\t\t\tcbcText(root, \"CreditNoteTypeCode\") ||\n\t\t\t\tundefined,\n\t\t\tissueDate: cbcText(root, \"IssueDate\"),\n\t\t\tdueDate: cbcText(root, \"DueDate\") || undefined,\n\t\t\ttaxPointDate: cbcText(root, \"TaxPointDate\") || undefined,\n\t\t\tcurrency: cbcText(root, \"DocumentCurrencyCode\"),\n\t\t\tbuyerReference: cbcText(root, \"BuyerReference\") || undefined,\n\t\t\torderReference: orderReference ? cbcText(orderReference, \"ID\") : undefined,\n\t\t\tsalesOrderId: orderReference\n\t\t\t\t? cbcText(orderReference, \"SalesOrderID\") || undefined\n\t\t\t\t: undefined,\n\t\t\tcontractReference: contractReference\n\t\t\t\t? cbcText(contractReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tprojectReference: projectReference\n\t\t\t\t? cbcText(projectReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tbillingReference: parseBillingReference(root),\n\t\t\tseller: parseParty(root, \"AccountingSupplierParty\"),\n\t\t\tbuyer: parseParty(root, \"AccountingCustomerParty\"),\n\t\t\tdelivery: parseDelivery(root),\n\t\t\tlines: parseLines(root, isCreditNote),\n\t\t\ttaxSubtotals: parseTaxSubtotals(root),\n\t\t\tmonetaryTotal: parseMonetaryTotal(root),\n\t\t\tpaymentMeansList,\n\t\t\tpaymentMeans: paymentMeansList?.[0],\n\t\t\tinvoicePeriod: parseInvoicePeriod(root),\n\t\t\tnote: parseNotes(root),\n\t\t\tpaymentTermsNote: parsePaymentTermsNote(root),\n\t\t\tattachments,\n\t\t\tdocumentReferences,\n\t\t\tallowanceCharges: parseAllowanceCharges(root),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import { 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 approximate decoded size.\n */\nexport interface UblEmbeddedAttachment {\n\tid: string | null;\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/** Approximate decoded byte length of a base64 string. */\nconst base64DecodedSize = (base64: string) => Math.round((base64.length * 3) / 4);\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 */\nexport const extractUblEmbeddedAttachments = (xml: string): UblEmbeddedAttachment[] => {\n\tconst parsed = parseUblInvoice(xml);\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 || null,\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 { DOMParser as XmlDomParser } from \"@xmldom/xmldom\";\n\nconst CBC_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nconst CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\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 nullable: a given MLR may omit any of them.\n */\nexport interface PeppolMessageLevelResponse {\n\tcustomizationId: string | null;\n\tprofileId: string | null;\n\tresponseId: string | null;\n\tissueDate: string | null;\n\tissueTime: string | null;\n\treferencedDocumentId: string | null;\n\tresponseCode: string | null;\n\tdescription: string | null;\n\t/** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */\n\tsenderIdentifier: string | null;\n\t/** Receiver participant id as `schemeID:value`. */\n\treceiverIdentifier: string | null;\n}\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 */\nconst stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\nconst parseXmlDocument = (xml: string): Document | null => {\n\tconst safeXml = stripDoctype(xml);\n\tconst BrowserDomParser = globalThis.DOMParser as typeof XmlDomParser | undefined;\n\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\tconst doc = parser.parseFromString(safeXml, \"text/xml\");\n\tif (doc.getElementsByTagName(\"parsererror\").length > 0) return null;\n\treturn doc;\n};\n\nconst trimmed = (value: string | null | undefined): string | null => {\n\tconst text = value?.trim();\n\treturn text ? text : null;\n};\n\n/** First descendant CBC element's trimmed text, or null. */\nconst cbcText = (parent: Element, tag: string): string | null =>\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 | null => {\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 null;\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 | null => {\n\tif (!party) return null;\n\tconst endpoint = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tif (!endpoint) return null;\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 is not\n * parseable or contains no ApplicationResponse.\n */\nconst findApplicationResponse = (xml: string): Element | null => {\n\tlet doc: Document | null;\n\ttry {\n\t\tdoc = parseXmlDocument(xml);\n\t} catch {\n\t\treturn null;\n\t}\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\treturn findApplicationResponse(xml) !== null;\n};\n\n/**\n * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping\n * an SBDH envelope when present. Throws when the XML is not an\n * ApplicationResponse.\n */\nexport const parsePeppolMessageLevelResponse = (\n\txml: string,\n): PeppolMessageLevelResponse => {\n\tconst root = findApplicationResponse(xml);\n\tif (!root) {\n\t\tthrow new Error(\"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: null,\n\t\tresponseCode: response ? cbcText(response, \"ResponseCode\") : null,\n\t\tdescription: response ? cbcText(response, \"Description\") : null,\n\t\tsenderIdentifier: endpointIdentifier(cacElement(root, \"SenderParty\")),\n\t\treceiverIdentifier: endpointIdentifier(cacElement(root, \"ReceiverParty\")),\n\t};\n};\n","import { parseUblInvoice } from \"./parser.js\";\nimport type {\n\tInvoiceExtractionDTO,\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblInvoice,\n} from \"./types.js\";\n\n// --- Utility helpers ---\n\nconst UTF8_BOM = 0xfeff;\n\nconst normalizeText = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst upper = trimmed.toUpperCase();\n\tif (upper === \"NA\" || upper === \"N/A\") return null;\n\treturn trimmed;\n};\n\nconst toNumberOrNull = (value: number | null | undefined): number | null =>\n\tNumber.isFinite(value ?? Number.NaN) ? (value as number) : null;\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\n// --- Address helpers ---\n\nconst addressToString = (address?: UblAddress): string | null => {\n\tif (!address) return null;\n\tconst street = [address.street, address.additionalStreet]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst cityLine = [address.postalZone, address.city]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst countryLine = [address.countrySubentity, address.countryCode]\n\t\t.filter((part) => part && part.trim().length > 0)\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 = [address.street, address.additionalStreet]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst result = {\n\t\tline1: normalizeText(line1),\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 base64ByteLength = (content: string) => {\n\tconst sanitized = content.replace(/\\s+/g, \"\");\n\tif (!sanitized) return 0;\n\tconst paddingLength = sanitized.endsWith(\"==\")\n\t\t? 2\n\t\t: sanitized.endsWith(\"=\")\n\t\t\t? 1\n\t\t\t: 0;\n\treturn Math.floor((sanitized.length * 3) / 4) - paddingLength;\n};\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: attachment.base64Content\n\t\t\t? base64ByteLength(attachment.base64Content)\n\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) => {\n\tconst subtotalSum = ubl.taxSubtotals.reduce(\n\t\t(sum, subtotal) => sum + subtotal.taxAmount,\n\t\t0,\n\t);\n\tif (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) {\n\t\treturn subtotalSum;\n\t}\n\treturn ubl.monetaryTotal.taxInclusiveAmount - ubl.monetaryTotal.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);\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 */\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 Error(\"Failed to parse UBL invoice XML\");\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 amountPaid =\n\t\tprepaidAmount ??\n\t\t(total !== null && amountDue !== null && total > amountDue\n\t\t\t? toNumberOrNull(total - amountDue)\n\t\t\t: null);\n\tconst taxTotal = toNumberOrNull(sumTaxTotal(ubl));\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\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\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\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? {\n\t\t\t\t\t\t\tcode: normalizeText(ubl.paymentMeans.code),\n\t\t\t\t\t\t\tcode_name: normalizeText(ubl.paymentMeans.codeName),\n\t\t\t\t\t\t\tpayment_id: normalizeText(ubl.paymentMeans.paymentId),\n\t\t\t\t\t\t\tiban: normalizeText(ubl.paymentMeans.iban),\n\t\t\t\t\t\t\tbic: normalizeText(ubl.paymentMeans.bic),\n\t\t\t\t\t\t\taccount_name: normalizeText(ubl.paymentMeans.accountName),\n\t\t\t\t\t\t\tmandate_id: normalizeText(ubl.paymentMeans.mandateId),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tpayment_means_list: paymentMeansList.map((item) => ({\n\t\t\t\t\tcode: normalizeText(item.code),\n\t\t\t\t\tcode_name: normalizeText(item.codeName),\n\t\t\t\t\tpayment_id: normalizeText(item.paymentId),\n\t\t\t\t\tiban: normalizeText(item.iban),\n\t\t\t\t\tbic: normalizeText(item.bic),\n\t\t\t\t\taccount_name: normalizeText(item.accountName),\n\t\t\t\t\tmandate_id: normalizeText(item.mandateId),\n\t\t\t\t})),\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":";AAAA,SAAS,aAAa,oBAAoB;AAmB1C,IAAM,SAAS;AACf,IAAM,SACL;AAID,SAAS,QAAQ,QAAiB,KAAqB;AACtD,QAAM,KAAK,OAAO,uBAAuB,QAAQ,GAAG,EAAE,CAAC;AACvD,SAAO,IAAI,aAAa,KAAK,KAAK;AACnC;AAEA,SAAS,WAAW,QAAiB,KAA6B;AACjE,SAAO,OAAO,uBAAuB,QAAQ,GAAG,EAAE,CAAC,KAAK;AACzD;AAEA,SAAS,YAAY,QAAiB,KAAwB;AAC7D,SAAO,MAAM,KAAK,OAAO,uBAAuB,QAAQ,GAAG,CAAC;AAC7D;AAEA,SAAS,UAAU,QAAiB,KAAqB;AACxD,QAAM,IAAI,OAAO,WAAW,QAAQ,QAAQ,GAAG,CAAC;AAChD,SAAO,OAAO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gB;AAAA,QAChE,aAAa;AAAA,QACb,qBAAqB,IAAI,sBAAsB,CAAC;AAAA,MACjD;AAAA,IACD;AAAA,IACA,YAAY;AAAA,IACZ,YAAY;AAAA,MACX,SAAS;AAAA,MACT,QAAQ;AAAA,QACP,YAAY;AAAA,QACZ,cAAc;AAAA,QACd,UAAU;AAAA,QACV,cAAc;AAAA,QACd,eAAe;AAAA,MAChB;AAAA,IACD;AAAA,EACD;AAEA,SAAO;AAAA,IACN;AAAA,IACA,YAAY;AAAA,MACX,QAAQ;AAAA,MACR,SAAS,eAAe,GAAG;AAAA,IAC5B;AAAA,EACD;AACD;AAKO,IAAM,0BAA0B,CAAC,WAIlC;AACL,QAAM,MAAM,eAAe,OAAO,KAAK;AACvC,QAAM,EAAE,WAAW,WAAW,IAAI,qBAAqB,KAAK,OAAO,UAAU;AAC7E,SAAO;AAAA,IACN,YAAY;AAAA,MACX,GAAG;AAAA,MACH,WAAW,OAAO;AAAA,IACnB;AAAA,IACA;AAAA,IACA,eAAe;AAAA,EAChB;AACD;","names":["XmlDomParser","CBC_NS","CAC_NS","stripDoctype","cbcText","cbcDirectText","cacElement","trimmed"]}
package/package.json CHANGED
@@ -1,8 +1,16 @@
1
1
  {
2
2
  "name": "@financica/ubl",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "UBL (Universal Business Language) invoice toolkit for TypeScript: parse, build, and serialize Peppol BIS Billing 3.0 documents.",
5
5
  "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/financica/ubl-ts.git"
9
+ },
10
+ "homepage": "https://github.com/financica/ubl-ts#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/financica/ubl-ts/issues"
13
+ },
6
14
  "type": "module",
7
15
  "exports": {
8
16
  ".": {