@financica/ubl 0.3.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 ADDED
@@ -0,0 +1,76 @@
1
+ # @ingram-tech/ubl
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.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @ingram-tech/ubl
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Parse UBL XML
14
+
15
+ ```typescript
16
+ import { parseUblInvoice } from "@ingram-tech/ubl";
17
+
18
+ const xml = `<?xml version="1.0"?>
19
+ <Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" ...>
20
+ <cbc:ID>INV-001</cbc:ID>
21
+ ...
22
+ </Invoice>`;
23
+
24
+ const invoice = parseUblInvoice(xml);
25
+ // invoice.id => "INV-001"
26
+ // invoice.seller.name => "Acme BV"
27
+ // invoice.lines[0].description => "Consulting services"
28
+ // invoice.monetaryTotal.payableAmount => 121
29
+ ```
30
+
31
+ Returns a typed `UblInvoice` object, or `null` if the XML is not a valid UBL Invoice/CreditNote.
32
+
33
+ ### Normalize to DTO
34
+
35
+ ```typescript
36
+ import { normalizeUblResponse } from "@ingram-tech/ubl";
37
+
38
+ const { extracted, rawPayload } = normalizeUblResponse(xml, "doc-123");
39
+ // extracted.invoice.invoice_number => "INV-001"
40
+ // extracted.invoice.supplier.name => "Acme BV"
41
+ // extracted.line_items[0].tax_rate => 21
42
+ ```
43
+
44
+ ### Parse from raw bytes
45
+
46
+ ```typescript
47
+ import { parseUblInvoiceDocument } from "@ingram-tech/ubl";
48
+
49
+ const result = parseUblInvoiceDocument({
50
+ bytes: new Uint8Array(buffer),
51
+ documentId: "doc-123",
52
+ mimeType: "application/xml",
53
+ });
54
+ ```
55
+
56
+ Handles UTF-8 BOM stripping automatically.
57
+
58
+ ## Supported document types
59
+
60
+ - UBL 2.1 Invoice
61
+ - UBL 2.1 CreditNote
62
+
63
+ ## Parsed fields
64
+
65
+ Parties (seller/buyer), addresses, contacts, endpoint IDs, line items with quantities/prices/tax, allowance/charge at both header and line level, tax subtotals, monetary totals, payment means (including multiple), payment terms, invoice period, delivery information, order/contract/project references, notes, and embedded attachments.
66
+
67
+ ## Development
68
+
69
+ ```bash
70
+ npm test # run tests in watch mode
71
+ npm run test:run # run tests once
72
+ npm run lint # eslint
73
+ npm run format # prettier
74
+ npm run build # build to dist/
75
+ npm run ci # type-check + lint + test + build
76
+ ```
@@ -0,0 +1,230 @@
1
+ interface UblAddress {
2
+ street: string;
3
+ additionalStreet?: string;
4
+ city: string;
5
+ postalZone: string;
6
+ countrySubentity?: string;
7
+ countryCode: string;
8
+ }
9
+ interface UblContact {
10
+ name?: string;
11
+ phone?: string;
12
+ email?: string;
13
+ }
14
+ interface UblPartyIdentification {
15
+ id: string;
16
+ schemeId?: string;
17
+ }
18
+ interface UblParty {
19
+ name: string;
20
+ registrationName?: string;
21
+ companyLegalForm?: string;
22
+ vatId?: string;
23
+ taxSchemeId?: string;
24
+ companyId?: string;
25
+ companyIdSchemeId?: string;
26
+ endpointId?: string;
27
+ endpointSchemeId?: string;
28
+ partyIdentifications?: UblPartyIdentification[];
29
+ address?: UblAddress;
30
+ contact?: UblContact;
31
+ }
32
+ interface UblItemProperty {
33
+ name: string;
34
+ value: string;
35
+ }
36
+ interface UblLine {
37
+ id: string;
38
+ description: string;
39
+ quantity: number;
40
+ unitCode: string;
41
+ unitPrice: number;
42
+ lineExtensionAmount: number;
43
+ taxPercent?: number;
44
+ taxAmount?: number;
45
+ taxCategoryId?: string;
46
+ taxSchemeId?: string;
47
+ taxSubtotals?: UblTaxSubtotal[];
48
+ allowanceCharges?: UblAllowanceCharge[];
49
+ discountAmount?: number;
50
+ chargeAmount?: number;
51
+ itemName?: string;
52
+ sellersItemId?: string;
53
+ buyersItemId?: string;
54
+ additionalItemProperties?: UblItemProperty[];
55
+ }
56
+ interface UblAllowanceCharge {
57
+ chargeIndicator: boolean;
58
+ amount: number;
59
+ baseAmount?: number;
60
+ multiplierFactorNumeric?: number;
61
+ reason?: string;
62
+ reasonCode?: string;
63
+ taxPercent?: number;
64
+ taxCategoryId?: string;
65
+ taxSchemeId?: string;
66
+ }
67
+ interface UblTaxSubtotal {
68
+ taxableAmount: number;
69
+ taxAmount: number;
70
+ taxPercent: number;
71
+ taxCategoryId?: string;
72
+ taxSchemeId?: string;
73
+ taxExemptionReason?: string;
74
+ }
75
+ interface UblMonetaryTotal {
76
+ lineExtensionAmount: number;
77
+ taxExclusiveAmount: number;
78
+ taxInclusiveAmount: number;
79
+ allowanceTotalAmount?: number;
80
+ chargeTotalAmount?: number;
81
+ prepaidAmount?: number;
82
+ payableRoundingAmount?: number;
83
+ payableAmount: number;
84
+ }
85
+ interface UblPaymentMeans {
86
+ code: string;
87
+ codeName?: string;
88
+ paymentId?: string;
89
+ iban?: string;
90
+ bic?: string;
91
+ accountName?: string;
92
+ mandateId?: string;
93
+ }
94
+ interface UblInvoicePeriod {
95
+ startDate?: string;
96
+ endDate?: string;
97
+ descriptionCode?: string;
98
+ }
99
+ interface UblAttachment {
100
+ id: string;
101
+ filename?: string;
102
+ mimeCode?: string;
103
+ description?: string;
104
+ base64Content?: string;
105
+ externalUri?: string;
106
+ }
107
+ interface UblDocumentReference {
108
+ id: string;
109
+ description?: string;
110
+ }
111
+ interface UblDelivery {
112
+ actualDeliveryDate?: string;
113
+ address?: UblAddress;
114
+ }
115
+ interface UblBillingReference {
116
+ invoiceId?: string;
117
+ invoiceIssueDate?: string;
118
+ }
119
+ interface UblInvoice {
120
+ documentType: "Invoice" | "CreditNote";
121
+ customizationId?: string;
122
+ profileId?: string;
123
+ id: string;
124
+ invoiceTypeCode?: string;
125
+ issueDate: string;
126
+ dueDate?: string;
127
+ taxPointDate?: string;
128
+ currency: string;
129
+ buyerReference?: string;
130
+ orderReference?: string;
131
+ salesOrderId?: string;
132
+ contractReference?: string;
133
+ projectReference?: string;
134
+ billingReference?: UblBillingReference;
135
+ seller: UblParty;
136
+ buyer: UblParty;
137
+ delivery?: UblDelivery;
138
+ lines: UblLine[];
139
+ taxSubtotals: UblTaxSubtotal[];
140
+ monetaryTotal: UblMonetaryTotal;
141
+ paymentMeans?: UblPaymentMeans;
142
+ paymentMeansList?: UblPaymentMeans[];
143
+ invoicePeriod?: UblInvoicePeriod;
144
+ note?: string;
145
+ paymentTermsNote?: string;
146
+ attachments?: UblAttachment[];
147
+ documentReferences?: UblDocumentReference[];
148
+ allowanceCharges?: UblAllowanceCharge[];
149
+ }
150
+ interface InvoiceExtractionDTO {
151
+ provider: string;
152
+ document_id: string;
153
+ invoice: {
154
+ invoice_number: string | null;
155
+ invoice_date: string | null;
156
+ due_date: string | null;
157
+ currency: string | null;
158
+ subtotal: number | null;
159
+ tax_total: number | null;
160
+ total: number | null;
161
+ amount_due: number | null;
162
+ amount_paid: number | null;
163
+ discount_total: number | null;
164
+ shipping_total: number | null;
165
+ payment_terms: string | null;
166
+ po_number: string | null;
167
+ supplier: {
168
+ name: string | null;
169
+ address: string | null;
170
+ tax_id: string | null;
171
+ iban: string | null;
172
+ bic: string | null;
173
+ };
174
+ receiver: {
175
+ name: string | null;
176
+ address: string | null;
177
+ tax_id: string | null;
178
+ };
179
+ extra: Record<string, unknown>;
180
+ };
181
+ line_items: Array<{
182
+ description: string;
183
+ quantity: number | null;
184
+ unit: string | null;
185
+ unit_price: number | null;
186
+ amount: number | null;
187
+ tax_amount: number | null;
188
+ tax_rate: number | null;
189
+ product_code: string | null;
190
+ discount_amount: number | null;
191
+ extra: Record<string, unknown>;
192
+ }>;
193
+ confidence: {
194
+ overall: number | null;
195
+ fields: Record<string, number>;
196
+ };
197
+ }
198
+
199
+ declare function parseUblInvoice(xml: string): UblInvoice | null;
200
+
201
+ declare const normalizeCurrency: (value?: string | null) => string | null;
202
+ declare const parseDate: (value?: string | null) => string | null;
203
+ /**
204
+ * Decode raw XML bytes, stripping an optional UTF-8 BOM.
205
+ */
206
+ declare const decodeXmlBytes: (bytes: Uint8Array) => string;
207
+ /**
208
+ * Parse a UBL XML string and normalize it into a flat DTO suitable for
209
+ * database storage or API responses.
210
+ */
211
+ declare const normalizeUblResponse: (xml: string, documentId: string) => {
212
+ extracted: InvoiceExtractionDTO;
213
+ rawPayload: Record<string, unknown>;
214
+ };
215
+ /**
216
+ * Parse a UBL invoice from raw bytes and normalize it into a DTO.
217
+ */
218
+ declare const parseUblInvoiceDocument: (params: {
219
+ bytes: Uint8Array;
220
+ documentId: string;
221
+ mimeType: string;
222
+ }) => {
223
+ rawPayload: {
224
+ mime_type: string;
225
+ };
226
+ extracted: InvoiceExtractionDTO;
227
+ providerJobId: string | null;
228
+ };
229
+
230
+ export { type InvoiceExtractionDTO, 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, normalizeCurrency, normalizeUblResponse, parseDate, parseUblInvoice, parseUblInvoiceDocument };
package/dist/index.js ADDED
@@ -0,0 +1,715 @@
1
+ // src/parser.ts
2
+ import { DOMParser as XmlDomParser } from "@xmldom/xmldom";
3
+ var CBC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
4
+ var CAC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
5
+ function cbcText(parent, tag) {
6
+ const el = parent.getElementsByTagNameNS(CBC_NS, tag)[0];
7
+ return el?.textContent?.trim() ?? "";
8
+ }
9
+ function cacElement(parent, tag) {
10
+ return parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;
11
+ }
12
+ function cacElements(parent, tag) {
13
+ return Array.from(parent.getElementsByTagNameNS(CAC_NS, tag));
14
+ }
15
+ function cbcNumber(parent, tag) {
16
+ const n = Number.parseFloat(cbcText(parent, tag));
17
+ return Number.isNaN(n) ? 0 : n;
18
+ }
19
+ function childElementsByTagNs(parent, namespace, tag) {
20
+ const elements = [];
21
+ for (let i = 0; i < parent.childNodes.length; i++) {
22
+ const node = parent.childNodes[i];
23
+ if (!node || node.nodeType !== 1) continue;
24
+ const element = node;
25
+ if (element.namespaceURI === namespace && element.localName === tag) {
26
+ elements.push(element);
27
+ }
28
+ }
29
+ return elements;
30
+ }
31
+ function cbcDirectText(parent, tag) {
32
+ const el = childElementsByTagNs(parent, CBC_NS, tag)[0];
33
+ return el?.textContent?.trim() ?? "";
34
+ }
35
+ function cbcDirectNumber(parent, tag) {
36
+ const value = cbcDirectText(parent, tag);
37
+ if (!value) return null;
38
+ const parsed = Number.parseFloat(value);
39
+ return Number.isNaN(parsed) ? null : parsed;
40
+ }
41
+ function cacDirectElement(parent, tag) {
42
+ return childElementsByTagNs(parent, CAC_NS, tag)[0] ?? null;
43
+ }
44
+ function cacDirectElements(parent, tag) {
45
+ return childElementsByTagNs(parent, CAC_NS, tag);
46
+ }
47
+ function parseAddressFromElement(address) {
48
+ if (!address) return void 0;
49
+ const country = cacElement(address, "Country");
50
+ return {
51
+ street: cbcText(address, "StreetName"),
52
+ additionalStreet: cbcText(address, "AdditionalStreetName") || void 0,
53
+ city: cbcText(address, "CityName"),
54
+ postalZone: cbcText(address, "PostalZone"),
55
+ countrySubentity: cbcText(address, "CountrySubentity") || void 0,
56
+ countryCode: country ? cbcText(country, "IdentificationCode") : ""
57
+ };
58
+ }
59
+ function parseAddress(party) {
60
+ const postal = cacElement(party, "PostalAddress");
61
+ return parseAddressFromElement(postal);
62
+ }
63
+ function parseTaxSchemeId(parent) {
64
+ if (!parent) return void 0;
65
+ const taxScheme = cacElement(parent, "TaxScheme");
66
+ if (!taxScheme) return void 0;
67
+ return cbcText(taxScheme, "ID") || void 0;
68
+ }
69
+ function parseContact(party) {
70
+ const contact = cacElement(party, "Contact");
71
+ if (!contact) return void 0;
72
+ const name = cbcText(contact, "Name");
73
+ const phone = cbcText(contact, "Telephone");
74
+ const email = cbcText(contact, "ElectronicMail");
75
+ if (!name && !phone && !email) return void 0;
76
+ return {
77
+ name: name || void 0,
78
+ phone: phone || void 0,
79
+ email: email || void 0
80
+ };
81
+ }
82
+ function parsePartyIdentifications(party) {
83
+ const ids = cacElements(party, "PartyIdentification");
84
+ const result = [];
85
+ for (const idEl of ids) {
86
+ const idValue = cbcText(idEl, "ID");
87
+ if (!idValue) continue;
88
+ const schemeIdAttr = idEl.getElementsByTagNameNS(CBC_NS, "ID")[0]?.getAttribute("schemeID");
89
+ result.push({
90
+ id: idValue,
91
+ schemeId: schemeIdAttr || void 0
92
+ });
93
+ }
94
+ return result;
95
+ }
96
+ function parseParty(root, role) {
97
+ const wrapper = cacElement(root, role);
98
+ const party = wrapper ? cacElement(wrapper, "Party") : null;
99
+ if (!party) return { name: "Unknown" };
100
+ const partyName = cacElement(party, "PartyName");
101
+ const legalEntity = cacElement(party, "PartyLegalEntity");
102
+ const taxScheme = cacElement(party, "PartyTaxScheme");
103
+ const partyId = cacElement(party, "PartyIdentification");
104
+ const endpointEl = party.getElementsByTagNameNS(CBC_NS, "EndpointID")[0];
105
+ const partyIdentifications = parsePartyIdentifications(party);
106
+ const companyIdEl = legalEntity ? legalEntity.getElementsByTagNameNS(CBC_NS, "CompanyID")[0] : null;
107
+ return {
108
+ name: partyName ? cbcText(partyName, "Name") : "",
109
+ registrationName: legalEntity ? cbcText(legalEntity, "RegistrationName") || void 0 : void 0,
110
+ companyLegalForm: legalEntity ? cbcText(legalEntity, "CompanyLegalForm") || void 0 : void 0,
111
+ vatId: taxScheme ? cbcText(taxScheme, "CompanyID") || void 0 : void 0,
112
+ taxSchemeId: parseTaxSchemeId(taxScheme),
113
+ companyId: companyIdEl ? companyIdEl.textContent?.trim() || void 0 : partyId ? cbcText(partyId, "ID") || void 0 : void 0,
114
+ companyIdSchemeId: companyIdEl?.getAttribute("schemeID") || void 0,
115
+ endpointId: endpointEl?.textContent?.trim() || void 0,
116
+ endpointSchemeId: endpointEl?.getAttribute("schemeID") || void 0,
117
+ partyIdentifications: partyIdentifications.length > 0 ? partyIdentifications : void 0,
118
+ address: parseAddress(party),
119
+ contact: parseContact(party)
120
+ };
121
+ }
122
+ function parseTaxSubtotal(sub) {
123
+ const cat = cacElement(sub, "TaxCategory");
124
+ return {
125
+ taxableAmount: cbcNumber(sub, "TaxableAmount"),
126
+ taxAmount: cbcNumber(sub, "TaxAmount"),
127
+ taxPercent: (cat ? cbcNumber(cat, "Percent") : 0) || cbcNumber(sub, "Percent"),
128
+ taxCategoryId: cat ? cbcText(cat, "ID") || void 0 : void 0,
129
+ taxSchemeId: parseTaxSchemeId(cat),
130
+ taxExemptionReason: cat ? cbcText(cat, "TaxExemptionReason") || void 0 : void 0
131
+ };
132
+ }
133
+ function parseTaxSubtotalsFromTaxTotal(taxTotal) {
134
+ return cacDirectElements(taxTotal, "TaxSubtotal").map(parseTaxSubtotal);
135
+ }
136
+ function parseTaxSubtotals(root) {
137
+ const taxTotals = cacDirectElements(root, "TaxTotal");
138
+ if (taxTotals.length === 0) return [];
139
+ return taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal);
140
+ }
141
+ function parseAllowanceCharge(charge) {
142
+ const taxCategory = cacElement(charge, "TaxCategory");
143
+ const indicatorRaw = cbcDirectText(charge, "ChargeIndicator").toLowerCase();
144
+ const chargeIndicator = indicatorRaw === "true" || indicatorRaw === "1";
145
+ return {
146
+ chargeIndicator,
147
+ amount: cbcNumber(charge, "Amount"),
148
+ baseAmount: cbcDirectNumber(charge, "BaseAmount") ?? void 0,
149
+ multiplierFactorNumeric: cbcDirectNumber(charge, "MultiplierFactorNumeric") ?? void 0,
150
+ reason: cbcText(charge, "AllowanceChargeReason") || void 0,
151
+ reasonCode: cbcText(charge, "AllowanceChargeReasonCode") || void 0,
152
+ taxPercent: taxCategory ? cbcNumber(taxCategory, "Percent") : void 0,
153
+ taxCategoryId: taxCategory ? cbcText(taxCategory, "ID") || void 0 : void 0,
154
+ taxSchemeId: parseTaxSchemeId(taxCategory)
155
+ };
156
+ }
157
+ function parseAllowanceCharges(parent) {
158
+ return cacDirectElements(parent, "AllowanceCharge").map(parseAllowanceCharge);
159
+ }
160
+ function parseLines(root, isCreditNote) {
161
+ const qtyTag = isCreditNote ? "CreditedQuantity" : "InvoicedQuantity";
162
+ const lineTag = isCreditNote ? "CreditNoteLine" : "InvoiceLine";
163
+ return cacElements(root, lineTag).map((line) => {
164
+ const item = cacElement(line, "Item");
165
+ const price = cacElement(line, "Price");
166
+ const taxCategory = item ? cacElement(item, "ClassifiedTaxCategory") : null;
167
+ const sellersId = item ? cacElement(item, "SellersItemIdentification") : null;
168
+ const buyersId = item ? cacElement(item, "BuyersItemIdentification") : null;
169
+ const qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];
170
+ const lineExtensionAmount = cbcNumber(line, "LineExtensionAmount");
171
+ const lineTaxTotal = cacDirectElement(line, "TaxTotal");
172
+ const lineTaxSubtotals = lineTaxTotal ? parseTaxSubtotalsFromTaxTotal(lineTaxTotal) : [];
173
+ const taxAmountFromSubtotals = lineTaxSubtotals.reduce(
174
+ (sum, subtotal) => sum + subtotal.taxAmount,
175
+ 0
176
+ );
177
+ const taxAmountFromLineTotal = lineTaxTotal ? cbcDirectNumber(lineTaxTotal, "TaxAmount") : null;
178
+ const taxPercent = lineTaxSubtotals[0]?.taxPercent ?? (taxCategory ? cbcNumber(taxCategory, "Percent") : void 0);
179
+ const computedTaxAmount = taxPercent !== void 0 ? Number((lineExtensionAmount * taxPercent / 100).toFixed(2)) : void 0;
180
+ const allowanceCharges = parseAllowanceCharges(line);
181
+ const discountAmount = allowanceCharges.reduce(
182
+ (sum, charge) => charge.chargeIndicator ? sum : sum + Math.abs(charge.amount),
183
+ 0
184
+ );
185
+ const chargeAmount = allowanceCharges.reduce(
186
+ (sum, charge) => charge.chargeIndicator ? sum + Math.abs(charge.amount) : sum,
187
+ 0
188
+ );
189
+ const additionalItemProperties = [];
190
+ if (item) {
191
+ for (const prop of cacElements(item, "AdditionalItemProperty")) {
192
+ const propName = cbcText(prop, "Name");
193
+ const propValue = cbcText(prop, "Value");
194
+ if (propName) {
195
+ additionalItemProperties.push({
196
+ name: propName,
197
+ value: propValue
198
+ });
199
+ }
200
+ }
201
+ }
202
+ return {
203
+ id: cbcText(line, "ID"),
204
+ description: item ? cbcText(item, "Description") : "",
205
+ quantity: cbcNumber(line, qtyTag),
206
+ unitCode: qtyEl?.getAttribute("unitCode") ?? "",
207
+ unitPrice: price ? cbcNumber(price, "PriceAmount") : 0,
208
+ lineExtensionAmount,
209
+ taxPercent,
210
+ taxAmount: taxAmountFromLineTotal ?? (lineTaxSubtotals.length > 0 ? taxAmountFromSubtotals : computedTaxAmount),
211
+ taxCategoryId: lineTaxSubtotals[0]?.taxCategoryId ?? (taxCategory ? cbcText(taxCategory, "ID") || void 0 : void 0),
212
+ taxSchemeId: lineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),
213
+ taxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : void 0,
214
+ allowanceCharges: allowanceCharges.length > 0 ? allowanceCharges : void 0,
215
+ discountAmount: discountAmount > 0 ? discountAmount : void 0,
216
+ chargeAmount: chargeAmount > 0 ? chargeAmount : void 0,
217
+ itemName: item ? cbcText(item, "Name") || void 0 : void 0,
218
+ sellersItemId: sellersId ? cbcText(sellersId, "ID") || void 0 : void 0,
219
+ buyersItemId: buyersId ? cbcText(buyersId, "ID") || void 0 : void 0,
220
+ additionalItemProperties: additionalItemProperties.length > 0 ? additionalItemProperties : void 0
221
+ };
222
+ });
223
+ }
224
+ function parseMonetaryTotal(root) {
225
+ const total = cacDirectElement(root, "LegalMonetaryTotal");
226
+ if (!total) {
227
+ return {
228
+ lineExtensionAmount: 0,
229
+ taxExclusiveAmount: 0,
230
+ taxInclusiveAmount: 0,
231
+ payableAmount: 0
232
+ };
233
+ }
234
+ return {
235
+ lineExtensionAmount: cbcNumber(total, "LineExtensionAmount"),
236
+ taxExclusiveAmount: cbcNumber(total, "TaxExclusiveAmount"),
237
+ taxInclusiveAmount: cbcNumber(total, "TaxInclusiveAmount"),
238
+ allowanceTotalAmount: cbcNumber(total, "AllowanceTotalAmount") || void 0,
239
+ chargeTotalAmount: cbcNumber(total, "ChargeTotalAmount") || void 0,
240
+ prepaidAmount: cbcNumber(total, "PrepaidAmount") || void 0,
241
+ payableRoundingAmount: cbcNumber(total, "PayableRoundingAmount") || void 0,
242
+ payableAmount: cbcNumber(total, "PayableAmount")
243
+ };
244
+ }
245
+ function parsePaymentMeansElement(pm) {
246
+ const account = cacElement(pm, "PayeeFinancialAccount");
247
+ const branch = account ? cacElement(account, "FinancialInstitutionBranch") : null;
248
+ const paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, "PaymentMeansCode")[0];
249
+ const mandate = cacElement(pm, "PaymentMandate");
250
+ return {
251
+ code: cbcText(pm, "PaymentMeansCode"),
252
+ codeName: paymentMeansCodeEl?.getAttribute("name") || void 0,
253
+ paymentId: cbcText(pm, "PaymentID") || void 0,
254
+ iban: account ? cbcText(account, "ID") || void 0 : void 0,
255
+ bic: branch ? cbcText(branch, "ID") || void 0 : void 0,
256
+ accountName: account && cbcText(account, "Name") || void 0,
257
+ mandateId: mandate ? cbcText(mandate, "ID") || void 0 : void 0
258
+ };
259
+ }
260
+ function parsePaymentMeansList(root) {
261
+ const list = cacElements(root, "PaymentMeans").map(parsePaymentMeansElement);
262
+ return list.length > 0 ? list : void 0;
263
+ }
264
+ function parseInvoicePeriod(root) {
265
+ const period = cacElement(root, "InvoicePeriod");
266
+ if (!period) return void 0;
267
+ const start = cbcText(period, "StartDate");
268
+ const end = cbcText(period, "EndDate");
269
+ if (!start && !end) return void 0;
270
+ return {
271
+ startDate: start || void 0,
272
+ endDate: end || void 0,
273
+ descriptionCode: cbcText(period, "DescriptionCode") || void 0
274
+ };
275
+ }
276
+ function parseDelivery(root) {
277
+ const delivery = cacElement(root, "Delivery");
278
+ if (!delivery) return void 0;
279
+ const actualDeliveryDate = cbcText(delivery, "ActualDeliveryDate") || void 0;
280
+ const deliveryLocation = cacElement(delivery, "DeliveryLocation");
281
+ const address = parseAddressFromElement(
282
+ deliveryLocation ? cacElement(deliveryLocation, "Address") : null
283
+ );
284
+ if (!actualDeliveryDate && !address) return void 0;
285
+ return {
286
+ actualDeliveryDate,
287
+ address
288
+ };
289
+ }
290
+ function parsePaymentTermsNote(root) {
291
+ const paymentTerms = cacElement(root, "PaymentTerms");
292
+ if (!paymentTerms) return void 0;
293
+ const note = cbcText(paymentTerms, "Note");
294
+ return note || void 0;
295
+ }
296
+ function parseNotes(root) {
297
+ const noteEls = root.getElementsByTagNameNS(CBC_NS, "Note");
298
+ const notes = [];
299
+ for (let i = 0; i < noteEls.length; i++) {
300
+ const el = noteEls[i];
301
+ if (!el) continue;
302
+ if (el.parentElement === root || el.parentNode === root) {
303
+ const text = el.textContent?.trim();
304
+ if (text) notes.push(text);
305
+ }
306
+ }
307
+ return notes.length > 0 ? notes.join("\n") : void 0;
308
+ }
309
+ function parseAttachments(root) {
310
+ const refs = cacElements(root, "AdditionalDocumentReference");
311
+ const attachments = [];
312
+ const documentReferences = [];
313
+ for (const ref of refs) {
314
+ const attachment = cacElement(ref, "Attachment");
315
+ const refId = cbcText(ref, "ID");
316
+ const description = cbcText(ref, "DocumentDescription") || void 0;
317
+ if (!attachment) {
318
+ if (refId || description) {
319
+ documentReferences.push({ id: refId, description });
320
+ }
321
+ continue;
322
+ }
323
+ const binaryEl = attachment.getElementsByTagNameNS(
324
+ CBC_NS,
325
+ "EmbeddedDocumentBinaryObject"
326
+ )[0];
327
+ const externalRef = cacElement(attachment, "ExternalReference");
328
+ if (binaryEl) {
329
+ const content = binaryEl.textContent?.trim();
330
+ if (content) {
331
+ attachments.push({
332
+ id: refId,
333
+ filename: binaryEl.getAttribute("filename") || void 0,
334
+ mimeCode: binaryEl.getAttribute("mimeCode") || void 0,
335
+ description,
336
+ base64Content: content
337
+ });
338
+ }
339
+ } else if (externalRef) {
340
+ const uri = cbcText(externalRef, "URI");
341
+ if (uri) {
342
+ attachments.push({
343
+ id: refId,
344
+ description,
345
+ externalUri: uri
346
+ });
347
+ }
348
+ }
349
+ }
350
+ return {
351
+ attachments: attachments.length > 0 ? attachments : void 0,
352
+ documentReferences: documentReferences.length > 0 ? documentReferences : void 0
353
+ };
354
+ }
355
+ function parseBillingReference(root) {
356
+ const billingRef = cacElement(root, "BillingReference");
357
+ if (!billingRef) return void 0;
358
+ const invoiceRef = cacElement(billingRef, "InvoiceDocumentReference");
359
+ if (!invoiceRef) return void 0;
360
+ const invoiceId = cbcText(invoiceRef, "ID") || void 0;
361
+ const invoiceIssueDate = cbcText(invoiceRef, "IssueDate") || void 0;
362
+ if (!invoiceId && !invoiceIssueDate) return void 0;
363
+ return { invoiceId, invoiceIssueDate };
364
+ }
365
+ var stripDoctype = (xml) => xml.replace(/<!DOCTYPE\s[^>[]*(?:\[[^\]]*\])?>/gi, "");
366
+ function parseUblInvoice(xml) {
367
+ try {
368
+ const safeXml = stripDoctype(xml);
369
+ const BrowserDomParser = globalThis.DOMParser;
370
+ const parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();
371
+ const doc = parser.parseFromString(safeXml, "text/xml");
372
+ if (doc.getElementsByTagName("parsererror").length > 0) return null;
373
+ const root = doc.documentElement;
374
+ const localName = root.localName;
375
+ let documentType;
376
+ if (localName === "Invoice") {
377
+ documentType = "Invoice";
378
+ } else if (localName === "CreditNote") {
379
+ documentType = "CreditNote";
380
+ } else {
381
+ return null;
382
+ }
383
+ const isCreditNote = documentType === "CreditNote";
384
+ const id = cbcText(root, "ID");
385
+ if (!id) return null;
386
+ const paymentMeansList = parsePaymentMeansList(root);
387
+ const orderReference = cacElement(root, "OrderReference");
388
+ const contractReference = cacElement(root, "ContractDocumentReference");
389
+ const projectReference = cacElement(root, "ProjectReference");
390
+ const { attachments, documentReferences } = parseAttachments(root);
391
+ return {
392
+ documentType,
393
+ customizationId: cbcText(root, "CustomizationID") || void 0,
394
+ profileId: cbcText(root, "ProfileID") || void 0,
395
+ id,
396
+ invoiceTypeCode: cbcText(root, "InvoiceTypeCode") || cbcText(root, "CreditNoteTypeCode") || void 0,
397
+ issueDate: cbcText(root, "IssueDate"),
398
+ dueDate: cbcText(root, "DueDate") || void 0,
399
+ taxPointDate: cbcText(root, "TaxPointDate") || void 0,
400
+ currency: cbcText(root, "DocumentCurrencyCode"),
401
+ buyerReference: cbcText(root, "BuyerReference") || void 0,
402
+ orderReference: orderReference ? cbcText(orderReference, "ID") : void 0,
403
+ salesOrderId: orderReference ? cbcText(orderReference, "SalesOrderID") || void 0 : void 0,
404
+ contractReference: contractReference ? cbcText(contractReference, "ID") : void 0,
405
+ projectReference: projectReference ? cbcText(projectReference, "ID") : void 0,
406
+ billingReference: parseBillingReference(root),
407
+ seller: parseParty(root, "AccountingSupplierParty"),
408
+ buyer: parseParty(root, "AccountingCustomerParty"),
409
+ delivery: parseDelivery(root),
410
+ lines: parseLines(root, isCreditNote),
411
+ taxSubtotals: parseTaxSubtotals(root),
412
+ monetaryTotal: parseMonetaryTotal(root),
413
+ paymentMeansList,
414
+ paymentMeans: paymentMeansList?.[0],
415
+ invoicePeriod: parseInvoicePeriod(root),
416
+ note: parseNotes(root),
417
+ paymentTermsNote: parsePaymentTermsNote(root),
418
+ attachments,
419
+ documentReferences,
420
+ allowanceCharges: parseAllowanceCharges(root)
421
+ };
422
+ } catch {
423
+ return null;
424
+ }
425
+ }
426
+
427
+ // src/normalize.ts
428
+ var UTF8_BOM = 65279;
429
+ var normalizeText = (value) => {
430
+ if (!value) return null;
431
+ const trimmed = value.trim();
432
+ if (!trimmed) return null;
433
+ const upper = trimmed.toUpperCase();
434
+ if (upper === "NA" || upper === "N/A") return null;
435
+ return trimmed;
436
+ };
437
+ var toNumberOrNull = (value) => Number.isFinite(value ?? Number.NaN) ? value : null;
438
+ var normalizeCurrency = (value) => {
439
+ if (!value) return null;
440
+ const trimmed = value.trim();
441
+ if (!trimmed) return null;
442
+ return trimmed.toUpperCase();
443
+ };
444
+ var parseDate = (value) => {
445
+ if (!value) return null;
446
+ const trimmed = value.trim();
447
+ if (!trimmed) return null;
448
+ const timestamp = Date.parse(trimmed);
449
+ if (Number.isNaN(timestamp)) return null;
450
+ const iso = new Date(timestamp).toISOString();
451
+ return iso.slice(0, 10);
452
+ };
453
+ var addressToString = (address) => {
454
+ if (!address) return null;
455
+ const street = [address.street, address.additionalStreet].filter((part) => part && part.trim().length > 0).join(" ");
456
+ const cityLine = [address.postalZone, address.city].filter((part) => part && part.trim().length > 0).join(" ");
457
+ const countryLine = [address.countrySubentity, address.countryCode].filter((part) => part && part.trim().length > 0).join(" ");
458
+ const lines = [street, cityLine, countryLine].filter((line) => line.length > 0);
459
+ return lines.length > 0 ? lines.join("\n") : null;
460
+ };
461
+ var addressToStructured = (address) => {
462
+ if (!address) return null;
463
+ const line1 = [address.street, address.additionalStreet].filter((part) => part && part.trim().length > 0).join(" ");
464
+ const result = {
465
+ line1: normalizeText(line1),
466
+ line2: null,
467
+ city: normalizeText(address.city),
468
+ state: normalizeText(address.countrySubentity),
469
+ postal_code: normalizeText(address.postalZone),
470
+ country: normalizeText(address.countryCode)
471
+ };
472
+ const hasValue = Object.values(result).some((value) => value);
473
+ return hasValue ? result : null;
474
+ };
475
+ var base64ByteLength = (content) => {
476
+ const sanitized = content.replace(/\s+/g, "");
477
+ if (!sanitized) return 0;
478
+ const paddingLength = sanitized.endsWith("==") ? 2 : sanitized.endsWith("=") ? 1 : 0;
479
+ return Math.floor(sanitized.length * 3 / 4) - paddingLength;
480
+ };
481
+ var sanitizeAttachments = (attachments) => (attachments ?? []).map((attachment) => ({
482
+ id: normalizeText(attachment.id),
483
+ filename: normalizeText(attachment.filename),
484
+ mime_code: normalizeText(attachment.mimeCode),
485
+ description: normalizeText(attachment.description),
486
+ size_bytes: attachment.base64Content ? base64ByteLength(attachment.base64Content) : null,
487
+ external_uri: normalizeText(attachment.externalUri)
488
+ }));
489
+ var sanitizeAllowanceCharges = (charges) => (charges ?? []).map((charge) => ({
490
+ charge_indicator: charge.chargeIndicator,
491
+ amount: toNumberOrNull(charge.amount),
492
+ base_amount: toNumberOrNull(charge.baseAmount),
493
+ multiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),
494
+ reason: normalizeText(charge.reason),
495
+ reason_code: normalizeText(charge.reasonCode),
496
+ tax_percent: toNumberOrNull(charge.taxPercent),
497
+ tax_category_id: normalizeText(charge.taxCategoryId),
498
+ tax_scheme_id: normalizeText(charge.taxSchemeId)
499
+ }));
500
+ var sanitizeRawUbl = (ubl) => ({
501
+ ...ubl,
502
+ attachments: sanitizeAttachments(ubl.attachments),
503
+ documentReferences: ubl.documentReferences ?? []
504
+ });
505
+ var sumTaxTotal = (ubl) => {
506
+ const subtotalSum = ubl.taxSubtotals.reduce(
507
+ (sum, subtotal) => sum + subtotal.taxAmount,
508
+ 0
509
+ );
510
+ if (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) {
511
+ return subtotalSum;
512
+ }
513
+ return ubl.monetaryTotal.taxInclusiveAmount - ubl.monetaryTotal.taxExclusiveAmount;
514
+ };
515
+ var sumAllowanceChargesByType = (charges, chargeIndicator) => (charges ?? []).reduce((sum, charge) => {
516
+ if (charge.chargeIndicator !== chargeIndicator) return sum;
517
+ return sum + Math.abs(charge.amount);
518
+ }, 0);
519
+ var decodeXmlBytes = (bytes) => {
520
+ const text = new TextDecoder("utf-8").decode(bytes);
521
+ return text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;
522
+ };
523
+ var normalizeUblResponse = (xml, documentId) => {
524
+ const ubl = parseUblInvoice(xml);
525
+ if (!ubl) {
526
+ throw new Error("Failed to parse UBL invoice XML");
527
+ }
528
+ const subtotal = toNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ?? toNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);
529
+ const total = toNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ?? toNumberOrNull(ubl.monetaryTotal.payableAmount);
530
+ const amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);
531
+ const prepaidAmount = toNumberOrNull(ubl.monetaryTotal.prepaidAmount);
532
+ const amountPaid = prepaidAmount ?? (total !== null && amountDue !== null && total > amountDue ? toNumberOrNull(total - amountDue) : null);
533
+ const taxTotal = toNumberOrNull(sumTaxTotal(ubl));
534
+ const hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;
535
+ const headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);
536
+ const headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);
537
+ const currency = normalizeCurrency(ubl.currency);
538
+ const paymentTerms = normalizeText(ubl.paymentTermsNote);
539
+ const poNumber = normalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);
540
+ const lineItems = ubl.lines.map((line) => ({
541
+ description: normalizeText(line.description) ?? normalizeText(line.itemName) ?? "Line item",
542
+ quantity: toNumberOrNull(line.quantity),
543
+ unit: normalizeText(line.unitCode),
544
+ unit_price: toNumberOrNull(line.unitPrice),
545
+ amount: toNumberOrNull(line.lineExtensionAmount),
546
+ tax_amount: toNumberOrNull(line.taxAmount),
547
+ tax_rate: toNumberOrNull(line.taxPercent),
548
+ product_code: normalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),
549
+ discount_amount: toNumberOrNull(line.discountAmount),
550
+ extra: {
551
+ ubl_line_id: normalizeText(line.id),
552
+ item_name: normalizeText(line.itemName),
553
+ sellers_item_id: normalizeText(line.sellersItemId),
554
+ buyers_item_id: normalizeText(line.buyersItemId),
555
+ tax_category_id: normalizeText(line.taxCategoryId),
556
+ tax_scheme_id: normalizeText(line.taxSchemeId),
557
+ tax_subtotals: line.taxSubtotals ?? [],
558
+ allowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),
559
+ charge_amount: toNumberOrNull(line.chargeAmount),
560
+ metadata: line.additionalItemProperties ? Object.fromEntries(
561
+ line.additionalItemProperties.map((p) => [p.name, p.value])
562
+ ) : null
563
+ }
564
+ }));
565
+ const supplierAddress = addressToString(ubl.seller.address);
566
+ const receiverAddress = addressToString(ubl.buyer.address);
567
+ const supplierAddressStructured = addressToStructured(ubl.seller.address);
568
+ const receiverAddressStructured = addressToStructured(ubl.buyer.address);
569
+ const attachmentMetadata = sanitizeAttachments(ubl.attachments);
570
+ const paymentMeansList = ubl.paymentMeansList && ubl.paymentMeansList.length > 0 ? ubl.paymentMeansList : ubl.paymentMeans ? [ubl.paymentMeans] : [];
571
+ const extracted = {
572
+ provider: "ubl_xml",
573
+ document_id: documentId,
574
+ invoice: {
575
+ invoice_number: normalizeText(ubl.id),
576
+ invoice_date: parseDate(ubl.issueDate),
577
+ due_date: parseDate(ubl.dueDate),
578
+ currency,
579
+ subtotal,
580
+ tax_total: taxTotal,
581
+ total,
582
+ amount_due: amountDue,
583
+ amount_paid: amountPaid,
584
+ discount_total: toNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ?? (hasHeaderAllowanceCharges ? toNumberOrNull(headerDiscountTotal) : null),
585
+ shipping_total: toNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ?? (hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),
586
+ payment_terms: paymentTerms,
587
+ po_number: poNumber,
588
+ supplier: {
589
+ name: normalizeText(ubl.seller.name) ?? normalizeText(ubl.seller.registrationName),
590
+ address: supplierAddress,
591
+ tax_id: normalizeText(ubl.seller.vatId) ?? normalizeText(ubl.seller.companyId),
592
+ iban: normalizeText(ubl.paymentMeans?.iban),
593
+ bic: normalizeText(ubl.paymentMeans?.bic)
594
+ },
595
+ receiver: {
596
+ name: normalizeText(ubl.buyer.name) ?? normalizeText(ubl.buyer.registrationName),
597
+ address: receiverAddress,
598
+ tax_id: normalizeText(ubl.buyer.vatId) ?? normalizeText(ubl.buyer.companyId)
599
+ },
600
+ extra: {
601
+ document_type: ubl.documentType,
602
+ customization_id: normalizeText(ubl.customizationId),
603
+ profile_id: normalizeText(ubl.profileId),
604
+ invoice_type_code: normalizeText(ubl.invoiceTypeCode),
605
+ buyer_reference: normalizeText(ubl.buyerReference),
606
+ order_reference_id: normalizeText(ubl.orderReference),
607
+ sales_order_id: normalizeText(ubl.salesOrderId),
608
+ contract_reference: normalizeText(ubl.contractReference),
609
+ project_reference: normalizeText(ubl.projectReference),
610
+ billing_reference: ubl.billingReference ? {
611
+ invoice_id: normalizeText(ubl.billingReference.invoiceId),
612
+ invoice_issue_date: parseDate(
613
+ ubl.billingReference.invoiceIssueDate
614
+ )
615
+ } : null,
616
+ tax_point_date: parseDate(ubl.taxPointDate),
617
+ invoice_period: ubl.invoicePeriod ?? null,
618
+ note: normalizeText(ubl.note),
619
+ payment_means: ubl.paymentMeans ? {
620
+ code: normalizeText(ubl.paymentMeans.code),
621
+ code_name: normalizeText(ubl.paymentMeans.codeName),
622
+ payment_id: normalizeText(ubl.paymentMeans.paymentId),
623
+ iban: normalizeText(ubl.paymentMeans.iban),
624
+ bic: normalizeText(ubl.paymentMeans.bic),
625
+ account_name: normalizeText(ubl.paymentMeans.accountName),
626
+ mandate_id: normalizeText(ubl.paymentMeans.mandateId)
627
+ } : null,
628
+ payment_means_list: paymentMeansList.map((item) => ({
629
+ code: normalizeText(item.code),
630
+ code_name: normalizeText(item.codeName),
631
+ payment_id: normalizeText(item.paymentId),
632
+ iban: normalizeText(item.iban),
633
+ bic: normalizeText(item.bic),
634
+ account_name: normalizeText(item.accountName),
635
+ mandate_id: normalizeText(item.mandateId)
636
+ })),
637
+ delivery: ubl.delivery ? {
638
+ actual_delivery_date: parseDate(
639
+ ubl.delivery.actualDeliveryDate
640
+ ),
641
+ address: addressToStructured(ubl.delivery.address)
642
+ } : null,
643
+ supplier: {
644
+ endpoint_id: normalizeText(ubl.seller.endpointId),
645
+ endpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),
646
+ registration_name: normalizeText(ubl.seller.registrationName),
647
+ company_legal_form: normalizeText(ubl.seller.companyLegalForm),
648
+ company_id_scheme_id: normalizeText(ubl.seller.companyIdSchemeId),
649
+ tax_scheme_id: normalizeText(ubl.seller.taxSchemeId),
650
+ party_identifications: ubl.seller.partyIdentifications ?? [],
651
+ contact_name: normalizeText(ubl.seller.contact?.name),
652
+ contact_phone: normalizeText(ubl.seller.contact?.phone),
653
+ contact_email: normalizeText(ubl.seller.contact?.email)
654
+ },
655
+ receiver: {
656
+ endpoint_id: normalizeText(ubl.buyer.endpointId),
657
+ endpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),
658
+ registration_name: normalizeText(ubl.buyer.registrationName),
659
+ company_legal_form: normalizeText(ubl.buyer.companyLegalForm),
660
+ company_id_scheme_id: normalizeText(ubl.buyer.companyIdSchemeId),
661
+ tax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),
662
+ party_identifications: ubl.buyer.partyIdentifications ?? [],
663
+ contact_name: normalizeText(ubl.buyer.contact?.name),
664
+ contact_phone: normalizeText(ubl.buyer.contact?.phone),
665
+ contact_email: normalizeText(ubl.buyer.contact?.email)
666
+ },
667
+ supplier_address_structured: supplierAddressStructured,
668
+ receiver_address_structured: receiverAddressStructured,
669
+ tax_subtotals: ubl.taxSubtotals,
670
+ allowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),
671
+ attachments: attachmentMetadata,
672
+ document_references: ubl.documentReferences ?? []
673
+ }
674
+ },
675
+ line_items: lineItems,
676
+ confidence: {
677
+ overall: 1,
678
+ fields: {
679
+ invoice_id: 1,
680
+ invoice_date: 1,
681
+ due_date: 1,
682
+ total_amount: 1,
683
+ supplier_name: 1
684
+ }
685
+ }
686
+ };
687
+ return {
688
+ extracted,
689
+ rawPayload: {
690
+ format: "ubl_xml",
691
+ invoice: sanitizeRawUbl(ubl)
692
+ }
693
+ };
694
+ };
695
+ var parseUblInvoiceDocument = (params) => {
696
+ const xml = decodeXmlBytes(params.bytes);
697
+ const { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);
698
+ return {
699
+ rawPayload: {
700
+ ...rawPayload,
701
+ mime_type: params.mimeType
702
+ },
703
+ extracted,
704
+ providerJobId: null
705
+ };
706
+ };
707
+ export {
708
+ decodeXmlBytes,
709
+ normalizeCurrency,
710
+ normalizeUblResponse,
711
+ parseDate,
712
+ parseUblInvoice,
713
+ parseUblInvoiceDocument
714
+ };
715
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parser.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 =\n\t\t\tidEl.getElementsByTagNameNS(CBC_NS, \"ID\")[0]?.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 allowanceCharges = parseAllowanceCharges(line);\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\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: price ? cbcNumber(price, \"PriceAmount\") : 0,\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(\n\troot: Element,\n): {\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 {\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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AAwB,CAAC;AAAA,UAC1D,cAAc,cAAc,IAAI,MAAM,SAAS,IAAI;AAAA,UACnD,eAAe,cAAc,IAAI,MAAM,SAAS,KAAK;AAAA,UACrD,eAAe,cAAc,IAAI,MAAM,SAAS,KAAK;AAAA,QACtD;AAAA,QACA,6BAA6B;AAAA,QAC7B,6BAA6B;AAAA,QAC7B,eAAe,IAAI;AAAA,QACnB,mBAAmB,yBAAyB,IAAI,gBAAgB;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":[]}
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@financica/ubl",
3
+ "version": "0.3.0",
4
+ "description": "UBL (Universal Business Language) invoice XML parser for TypeScript",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/index.js",
10
+ "types": "./dist/index.d.ts"
11
+ }
12
+ },
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsup",
20
+ "prepack": "npm run build",
21
+ "lint": "eslint",
22
+ "format": "prettier --write .",
23
+ "format:check": "prettier --check .",
24
+ "type-check": "tsc --noEmit",
25
+ "test": "vitest",
26
+ "test:run": "vitest --run",
27
+ "test:coverage": "vitest --coverage",
28
+ "ci": "npm run type-check && npm run lint && npm run test:run && npm run build"
29
+ },
30
+ "dependencies": {
31
+ "@xmldom/xmldom": "^0.8.11"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^22.0.0",
35
+ "eslint": "^9.0.0",
36
+ "prettier": "^3.8.1",
37
+ "tsup": "^8.0.0",
38
+ "typescript": "^5.9.3",
39
+ "typescript-eslint": "^8.0.0",
40
+ "vitest": "^4.0.18"
41
+ },
42
+ "prettier": {
43
+ "printWidth": 88,
44
+ "tabWidth": 4,
45
+ "useTabs": true,
46
+ "overrides": [
47
+ {
48
+ "files": "*.{yml,yaml}",
49
+ "options": {
50
+ "tabWidth": 2,
51
+ "useTabs": false
52
+ }
53
+ }
54
+ ]
55
+ }
56
+ }