@financica/ubl 0.4.0 → 0.6.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.
@@ -0,0 +1,413 @@
1
+ /** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */
2
+ /** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */
3
+ declare const UBL_CUSTOMIZATION_ID = "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0";
4
+ /** Peppol BIS Billing 3.0 process (BT-23). */
5
+ declare const UBL_PROFILE_ID = "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0";
6
+ /** UNTDID 1001 — commercial invoice. */
7
+ declare const INVOICE_TYPE_CODE = "380";
8
+ /** UNTDID 1001 — credit note. */
9
+ declare const CREDIT_NOTE_TYPE_CODE = "381";
10
+ /** UN/ECE Recommendation 20 — "one / piece" (the default line unit). */
11
+ declare const DEFAULT_UNIT_CODE = "C62";
12
+ /** UNCL5153 — the VAT tax scheme identifier. */
13
+ declare const VAT_TAX_SCHEME_ID = "VAT";
14
+ /** ISO 3166-1 alpha-2 list identifier for `cbc:IdentificationCode`. */
15
+ declare const COUNTRY_CODE_LIST_ID = "ISO3166-1:Alpha2";
16
+ declare const NS_INVOICE = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
17
+ declare const NS_CREDIT_NOTE = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
18
+ declare const NS_CAC = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
19
+ declare const NS_CBC = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
20
+
21
+ /**
22
+ * A vendor-neutral model of a Peppol BIS Billing 3.0 document.
23
+ *
24
+ * This is the intermediate representation `stripe-ubl` produces from a Stripe
25
+ * invoice or credit note; {@link ../ubl/serialize.ts} turns it into UBL XML.
26
+ * It is deliberately a thin, construction-oriented mirror of the UBL fields we
27
+ * populate — not a full UBL object graph.
28
+ */
29
+ interface UblAddress {
30
+ /** `cbc:StreetName` (BT-35). */
31
+ street: string | null;
32
+ /** `cbc:AdditionalStreetName` (BT-36). */
33
+ additionalStreet: string | null;
34
+ /** `cbc:CityName` (BT-37). */
35
+ city: string | null;
36
+ /** `cbc:PostalZone` (BT-38). */
37
+ postalZone: string | null;
38
+ /** `cbc:CountrySubentity` (BT-39). */
39
+ countrySubentity: string | null;
40
+ /** `cac:Country/cbc:IdentificationCode` (BT-40) — ISO 3166-1 alpha-2. */
41
+ countryCode: string | null;
42
+ }
43
+ /** Peppol participant identifier, e.g. scheme `0208`, value `0800279001`. */
44
+ interface UblEndpoint {
45
+ scheme: string;
46
+ value: string;
47
+ }
48
+ /** Legal registration identifier, e.g. a Belgian enterprise number. */
49
+ interface UblCompanyId {
50
+ value: string;
51
+ /** ICD scheme (e.g. `0208` for the Belgian CBE), when known. */
52
+ scheme?: string | null;
53
+ }
54
+ interface UblParty {
55
+ /** `cbc:EndpointID` (BT-49/BT-34) — the Peppol routing identifier. */
56
+ endpoint: UblEndpoint | null;
57
+ /** `cac:PartyName/cbc:Name` (BT-27/BT-44). */
58
+ name: string;
59
+ address: UblAddress;
60
+ /** `cac:PartyTaxScheme/cbc:CompanyID` with `VAT` scheme (BT-31/BT-48). */
61
+ vatNumber: string | null;
62
+ /** `cac:PartyLegalEntity/cbc:RegistrationName` (BT-27/BT-44). Defaults to `name`. */
63
+ legalName: string | null;
64
+ /** `cac:PartyLegalEntity/cbc:CompanyID` (BT-30/BT-47). */
65
+ companyId: UblCompanyId | null;
66
+ }
67
+ /**
68
+ * VAT breakdown category. `id` is a UNCL5305 code:
69
+ * - `S` Standard rate
70
+ * - `Z` Zero-rated goods
71
+ * - `E` Exempt from VAT
72
+ * - `AE` VAT reverse charge
73
+ * - `O` Services outside scope of tax
74
+ * - `K` Intra-community supply
75
+ * - `G` Export outside the EU
76
+ */
77
+ interface UblTaxCategory {
78
+ id: string;
79
+ percent: number;
80
+ /** Required by EN 16931 (BR-E-10/BR-AE-10/…) for non-`S`/`Z` categories. */
81
+ exemptionReason?: string | null;
82
+ }
83
+ interface UblLine {
84
+ /** `cbc:ID` (BT-126) — line identifier. */
85
+ id: string;
86
+ /** `cac:Item/cbc:Name` (BT-153). */
87
+ name: string;
88
+ /** `cbc:InvoicedQuantity` / `cbc:CreditedQuantity` (BT-129). */
89
+ quantity: number;
90
+ /** UN/ECE Rec 20 unit code (BT-130). */
91
+ unitCode: string;
92
+ /** `cbc:LineExtensionAmount` (BT-131) — net of VAT, after line discounts. */
93
+ lineExtensionAmount: number;
94
+ /** `cac:Price/cbc:PriceAmount` (BT-146) — net unit price. */
95
+ priceAmount: number;
96
+ taxCategory: UblTaxCategory;
97
+ }
98
+ interface UblTaxSubtotal {
99
+ /** `cbc:TaxableAmount` (BT-116). */
100
+ taxableAmount: number;
101
+ /** `cbc:TaxAmount` (BT-117). */
102
+ taxAmount: number;
103
+ category: UblTaxCategory;
104
+ }
105
+ interface UblTaxTotal {
106
+ /** `cbc:TaxAmount` (BT-110) — sum of subtotal tax amounts. */
107
+ taxAmount: number;
108
+ subtotals: UblTaxSubtotal[];
109
+ }
110
+ interface UblMonetaryTotal {
111
+ /** BT-106 — sum of line net amounts. */
112
+ lineExtensionAmount: number;
113
+ /** BT-109 — total without VAT. */
114
+ taxExclusiveAmount: number;
115
+ /** BT-112 — total with VAT. */
116
+ taxInclusiveAmount: number;
117
+ /** BT-115 — amount due for payment. */
118
+ payableAmount: number;
119
+ }
120
+ /** An embedded supporting document (BG-24), e.g. the rendered PDF. */
121
+ interface UblAttachment {
122
+ /** `cac:AdditionalDocumentReference/cbc:ID` (BT-122). */
123
+ id: string;
124
+ /** `cbc:EmbeddedDocumentBinaryObject/@filename`. */
125
+ filename: string;
126
+ /** MIME type, e.g. `application/pdf`. */
127
+ mimeCode: string;
128
+ /** Base64-encoded document bytes. */
129
+ base64: string;
130
+ }
131
+ interface UblDocument {
132
+ documentType: "invoice" | "creditNote";
133
+ /** Invoice / credit note number (BT-1). */
134
+ id: string;
135
+ /** Issue date (BT-2), `YYYY-MM-DD`. */
136
+ issueDate: string;
137
+ /** Payment due date (BT-9). Invoices only. */
138
+ dueDate: string | null;
139
+ /** Free-text note (BT-22). */
140
+ note: string | null;
141
+ /** Document currency (BT-5). */
142
+ currency: string;
143
+ /** Buyer reference (BT-10). */
144
+ buyerReference: string | null;
145
+ /** For credit notes: the referenced original invoice number (BT-25). */
146
+ precedingInvoiceId: string | null;
147
+ supplier: UblParty;
148
+ customer: UblParty;
149
+ lines: UblLine[];
150
+ taxTotal: UblTaxTotal;
151
+ monetaryTotal: UblMonetaryTotal;
152
+ attachments: UblAttachment[];
153
+ }
154
+
155
+ /** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */
156
+ declare const serializeUblDocument: (doc: UblDocument) => string;
157
+
158
+ /**
159
+ * Supplier (seller) VAT status. Drives how zero-VAT lines are reported when the
160
+ * seller does not charge VAT:
161
+ *
162
+ * 1 — Subject to VAT (the normal case): line categories come from the data.
163
+ * 2 — Not subject to VAT.
164
+ * 3 — Small business / franchise exemption (e.g. Belgian Article 56bis).
165
+ *
166
+ * For statuses 2 and 3, {@link ../build.ts} coerces all line categories to a
167
+ * non-charging exempt category so no VAT is reported.
168
+ */
169
+ type SupplierVatStatus = 1 | 2 | 3;
170
+ /**
171
+ * Caller-provided supplier data, normalized into a stable shape.
172
+ *
173
+ * Each consumer builds this from its own data store. Once a `UblSupplier`
174
+ * exists, the party builder no longer needs to know where it came from.
175
+ */
176
+ interface UblSupplier {
177
+ /** Display + legal name shown on the invoice. */
178
+ name: string;
179
+ /** ISO 3166-1 alpha-2 country code (e.g. `"BE"`). */
180
+ countryCode: string;
181
+ /**
182
+ * Free-form address. Stripe-style fields (`line1`, `postal_code`, `country`)
183
+ * and legacy/internal fields (`street`, `zip_code`) are both accepted.
184
+ */
185
+ address: unknown;
186
+ /** Country-specific company/registration number (e.g. BE enterprise number). */
187
+ companyNumber?: string | null;
188
+ /** VAT number with country prefix (e.g. `"BE0793904121"`). */
189
+ vatNumber?: string | null;
190
+ /** Whether the supplier charges VAT. See {@link SupplierVatStatus}. */
191
+ vatStatus: SupplierVatStatus;
192
+ /** Peppol participant identifier in `scheme:value` form (e.g. `"0208:0793904121"`). */
193
+ peppolID?: string | null;
194
+ }
195
+ /** Convert a {@link UblSupplier} into the supplier (seller) party. */
196
+ declare const buildSupplierParty: (supplier: UblSupplier) => UblParty;
197
+
198
+ /**
199
+ * Normalize a free-form address (Stripe shape, custom shape, or an internal
200
+ * shape) into a {@link UblAddress}.
201
+ *
202
+ * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`
203
+ * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address
204
+ * has no country, but never silently substitutes a caller's country — pass
205
+ * `null` when "no country" is the right answer.
206
+ */
207
+ declare const normalizeAddress: (address: unknown, fallbackCountryCode: string | null, fallbackLine?: string | null) => UblAddress;
208
+
209
+ /**
210
+ * Build a UBL embedded-document attachment (BG-24) from raw bytes — e.g. the
211
+ * rendered PDF of the invoice. Emitted as a `cac:AdditionalDocumentReference`
212
+ * with an inline base64 `cbc:EmbeddedDocumentBinaryObject`.
213
+ */
214
+ declare const buildPdfAttachment: (params: {
215
+ filename: string;
216
+ bytes: Uint8Array;
217
+ /** Document reference ID (BT-122). Defaults to the filename. */
218
+ id?: string;
219
+ }) => UblAttachment;
220
+ /**
221
+ * Replace each attachment's base64 payload with `[omitted]` plus a length, so a
222
+ * {@link UblDocument} is safe to log or persist for audit.
223
+ */
224
+ declare const sanitizeUblDocumentForAudit: (doc: UblDocument) => UblDocument;
225
+
226
+ /**
227
+ * Strip whitespace/punctuation from a country-specific company number.
228
+ * For Belgium, also strips an optional `BE` prefix.
229
+ */
230
+ declare const normalizeCompanyNumberForCountry: (countryCode: string | null | undefined, companyNumber: string | null | undefined) => string;
231
+ /**
232
+ * Country code → Peppol/ISO 6523 ICD scheme for a legal registration number
233
+ * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`).
234
+ *
235
+ * BE → 0208 (Belgian enterprise number, CBE/KBO/BCE)
236
+ * NL → 0106 (Netherlands KvK)
237
+ * FR → 0002 (France SIRENE)
238
+ *
239
+ * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).
240
+ * Returns `null` when the scheme can't be determined, in which case the
241
+ * CompanyID is emitted without a `schemeID` attribute.
242
+ */
243
+ declare const resolveCompanyIdScheme: (params: {
244
+ countryCode: string | null;
245
+ companyNumber: string | null;
246
+ }) => string | null;
247
+ /**
248
+ * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the
249
+ * country-appropriate ICD scheme when known. Returns `null` when there is no
250
+ * company number.
251
+ */
252
+ declare const buildCompanyId: (params: {
253
+ countryCode: string | null;
254
+ companyNumber: string | null;
255
+ }) => UblCompanyId | null;
256
+ /**
257
+ * Resolve the Peppol participant identifier for a VAT number, deriving the EAS
258
+ * scheme from the number's own country prefix (falling back to `countryCode`).
259
+ *
260
+ * `BE0206582284` → `{ scheme: "9925", value: "BE0206582284" }`
261
+ *
262
+ * The value keeps its country prefix, matching how participants register (the
263
+ * Peppol directory lists this party as `9925:be0206582284`). Returns `null`
264
+ * when the country has no VAT EAS scheme or the input is empty.
265
+ */
266
+ declare const resolveVatEndpoint: (params: {
267
+ vatNumber: string | null | undefined;
268
+ countryCode?: string | null;
269
+ }) => UblEndpoint | null;
270
+ /**
271
+ * Parse a Peppol participant identifier into a {@link UblEndpoint}.
272
+ *
273
+ * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns
274
+ * `null` for values without an explicit scheme, since `cbc:EndpointID` requires
275
+ * a `schemeID` and guessing one would mis-route the document.
276
+ */
277
+ declare const parsePeppolEndpoint: (peppolId: string | null | undefined) => UblEndpoint | null;
278
+ interface CustomerTaxIdentifiers {
279
+ peppolID: string | null;
280
+ glnNumber: string | null;
281
+ taxNumber: string | null;
282
+ vatNumber: string | null;
283
+ }
284
+ /**
285
+ * Pick the first usable Peppol identifier, GLN, VAT number, and tax number
286
+ * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).
287
+ *
288
+ * Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.
289
+ * Peppol IDs are typically stored as a custom `peppol_id` type.
290
+ */
291
+ declare const extractCustomerTaxIdentifiers: (taxIds: unknown) => CustomerTaxIdentifiers;
292
+ /**
293
+ * Build the fully-qualified Peppol participant identifiers (`scheme:value`) a
294
+ * receiver lookup will accept, in priority order, de-duplicated.
295
+ *
296
+ * Stripe stores a customer's VAT number without a Peppol scheme (e.g.
297
+ * `BE0206582284`), but a participant lookup needs the qualified identifier
298
+ * (`9925:BE0206582284`). This attaches the right scheme:
299
+ *
300
+ * 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;
301
+ * 2. a GLN under EAS `0088`;
302
+ * 3. the VAT number under its country's VAT EAS scheme (see
303
+ * {@link resolveVatEndpoint});
304
+ * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)
305
+ * under EAS `0208` — many Belgian entities register only under that;
306
+ * 5. a generic tax/registration number under its country's company-ID scheme.
307
+ *
308
+ * `countryCode` (the customer's country, when known) disambiguates schemes for
309
+ * identifiers that don't carry a country prefix (GLN, plain tax numbers).
310
+ */
311
+ declare const listPeppolReceiverIdentifierCandidates: (customer: {
312
+ peppolID?: string | null;
313
+ glnNumber?: string | null;
314
+ taxNumber?: string | null;
315
+ vatNumber?: string | null;
316
+ }, countryCode?: string | null) => string[];
317
+
318
+ /** Round a number to 2 decimal places (cents). */
319
+ declare const roundCurrency: (value: number) => number;
320
+ /** Convert an integer cent amount into a 2-decimal currency value. */
321
+ declare const centsToDecimal: (cents: number) => number;
322
+
323
+ /**
324
+ * Stripe Tax `taxability_reason` values that map to a VAT-exempt UBL category
325
+ * (`E`). Reverse charge is handled separately (category `AE`).
326
+ */
327
+ declare const EXEMPT_TAXABILITY_REASONS: Set<string>;
328
+ interface TaxAmountInfo {
329
+ amount: number;
330
+ taxability_reason?: string | null;
331
+ tax_rate_percentage?: number | null;
332
+ }
333
+ /**
334
+ * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a
335
+ * numeric rate into a {@link UblTaxCategory}.
336
+ *
337
+ * - Reverse charge → `AE` (0%, with exemption reason)
338
+ * - Any other exempt reason → `E` (0%, with exemption reason)
339
+ * - Category `Z` / rate ≤ 0 → `Z` (zero-rated, 0%)
340
+ * - Otherwise → `S` (standard, the line's rate)
341
+ */
342
+ declare const taxCategoryFromReasonOrRate: (params: {
343
+ taxCategoryId?: string | null;
344
+ taxabilityReason: string | null;
345
+ rate: number;
346
+ }) => UblTaxCategory;
347
+ /**
348
+ * Resolve a {@link UblTaxCategory} from a line's Stripe tax info.
349
+ *
350
+ * Exempt / reverse-charge / zero-rated reasons take precedence over the rate;
351
+ * otherwise the rate decides standard (`S`) vs zero-rated (`Z`).
352
+ */
353
+ declare const resolveTaxCategoryFromTaxAmounts: (taxAmounts: TaxAmountInfo[], rate: number) => UblTaxCategory;
354
+
355
+ /**
356
+ * Adjust the largest line's net amount so the line nets sum to the
357
+ * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).
358
+ *
359
+ * Reconciling at the *line* level — rather than directly on the VAT breakdown —
360
+ * keeps the document consistent bottom-up: the VAT category taxable amounts
361
+ * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the
362
+ * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level
363
+ * coupon; larger ones indicate a real upstream data problem.
364
+ */
365
+ declare const reconcileLinesToExclTotal: (lines: UblLine[], authoritativeTotalExclVat: number) => UblLine[];
366
+ interface BuildTaxTotalsResult {
367
+ taxTotal: UblTaxTotal;
368
+ monetaryTotal: UblMonetaryTotal;
369
+ }
370
+ /**
371
+ * Group lines by `(category, percent)` into a VAT breakdown and compute the
372
+ * document monetary totals.
373
+ *
374
+ * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,
375
+ * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the
376
+ * upstream per-line tax cents. This guarantees the breakdown is internally
377
+ * consistent and passes validation; it can differ by a cent from the figure a
378
+ * payment processor reported, which is an unavoidable artifact of representing
379
+ * a cents-rounded system as a rate-based VAT breakdown.
380
+ */
381
+ declare const buildTaxTotals: (lines: UblLine[]) => BuildTaxTotalsResult;
382
+
383
+ /**
384
+ * Minimal, dependency-free XML builder + serializer.
385
+ *
386
+ * UBL is order-sensitive (every element sequence is fixed by the schema), so
387
+ * children are always explicit, ordered arrays. There is no attribute or text
388
+ * coercion magic beyond escaping — the UBL layer is responsible for emitting
389
+ * elements in the right order.
390
+ */
391
+ type XmlAttrs = Record<string, string | number | null | undefined>;
392
+ interface XmlElement {
393
+ name: string;
394
+ attrs?: XmlAttrs;
395
+ /** Leaf text content. Mutually exclusive with `children`. */
396
+ text?: string | number | null;
397
+ /** Child elements. Mutually exclusive with `text`. */
398
+ children?: XmlElement[];
399
+ }
400
+ /** Falsy children are dropped, so callers can write `cond && el(...)`. */
401
+ type ChildSpec = XmlElement | null | undefined | false;
402
+ /**
403
+ * Build an XML element.
404
+ *
405
+ * el("cbc:ID", null, "INV-1") → <cbc:ID>INV-1</cbc:ID>
406
+ * el("cbc:Amount", { currencyID: "EUR" }, "10.00") → <cbc:Amount currencyID="EUR">10.00</cbc:Amount>
407
+ * el("cac:Party", null, [child, cond && child2]) → nested element
408
+ */
409
+ declare const el: (name: string, attrs?: XmlAttrs | null, content?: string | number | null | ChildSpec[]) => XmlElement;
410
+ /** Serialize a root element into a UTF-8 XML document string. */
411
+ declare const serializeDocument: (root: XmlElement) => string;
412
+
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 };
@@ -0,0 +1,614 @@
1
+ // src/build/ubl/constants.ts
2
+ var UBL_CUSTOMIZATION_ID = "urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0";
3
+ var UBL_PROFILE_ID = "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0";
4
+ var INVOICE_TYPE_CODE = "380";
5
+ var CREDIT_NOTE_TYPE_CODE = "381";
6
+ var DEFAULT_UNIT_CODE = "C62";
7
+ var VAT_TAX_SCHEME_ID = "VAT";
8
+ var COUNTRY_CODE_LIST_ID = "ISO3166-1:Alpha2";
9
+ var NS_INVOICE = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
10
+ var NS_CREDIT_NOTE = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
11
+ var NS_CAC = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
12
+ var NS_CBC = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
13
+
14
+ // src/build/xml.ts
15
+ var el = (name, attrs, content) => {
16
+ if (Array.isArray(content)) {
17
+ return {
18
+ name,
19
+ attrs: attrs ?? void 0,
20
+ children: content.filter((c) => Boolean(c))
21
+ };
22
+ }
23
+ return { name, attrs: attrs ?? void 0, text: content ?? void 0 };
24
+ };
25
+ var escapeText = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
26
+ var escapeAttr = (value) => escapeText(value).replace(/"/g, "&quot;");
27
+ var serializeAttrs = (attrs) => {
28
+ if (!attrs) return "";
29
+ return Object.entries(attrs).filter(([, value]) => value !== null && value !== void 0).map(([key, value]) => ` ${key}="${escapeAttr(String(value))}"`).join("");
30
+ };
31
+ var serializeElement = (node, indentLevel) => {
32
+ const pad = " ".repeat(indentLevel);
33
+ const attrs = serializeAttrs(node.attrs);
34
+ if (node.text !== void 0 && node.text !== null) {
35
+ return `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;
36
+ }
37
+ const children = node.children ?? [];
38
+ if (children.length === 0) {
39
+ return `${pad}<${node.name}${attrs}/>`;
40
+ }
41
+ const inner = children.map((child) => serializeElement(child, indentLevel + 1)).join("\n");
42
+ return `${pad}<${node.name}${attrs}>
43
+ ${inner}
44
+ ${pad}</${node.name}>`;
45
+ };
46
+ var serializeDocument = (root) => `<?xml version="1.0" encoding="UTF-8"?>
47
+ ${serializeElement(root, 0)}
48
+ `;
49
+
50
+ // src/build/ubl/serialize.ts
51
+ var amount = (value) => value.toFixed(2);
52
+ var percent = (value) => {
53
+ const rounded = Math.round(value * 100) / 100;
54
+ return Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);
55
+ };
56
+ var money = (name, value, currency) => el(name, { currencyID: currency }, amount(value));
57
+ var vatTaxScheme = () => el("cac:TaxScheme", null, [el("cbc:ID", null, VAT_TAX_SCHEME_ID)]);
58
+ var taxCategory = (name, category) => el(name, null, [
59
+ el("cbc:ID", null, category.id),
60
+ el("cbc:Percent", null, percent(category.percent)),
61
+ category.exemptionReason ? el("cbc:TaxExemptionReason", null, category.exemptionReason) : null,
62
+ vatTaxScheme()
63
+ ]);
64
+ var postalAddress = (address) => el("cac:PostalAddress", null, [
65
+ address.street ? el("cbc:StreetName", null, address.street) : null,
66
+ address.additionalStreet ? el("cbc:AdditionalStreetName", null, address.additionalStreet) : null,
67
+ address.city ? el("cbc:CityName", null, address.city) : null,
68
+ address.postalZone ? el("cbc:PostalZone", null, address.postalZone) : null,
69
+ address.countrySubentity ? el("cbc:CountrySubentity", null, address.countrySubentity) : null,
70
+ address.countryCode ? el("cac:Country", null, [
71
+ el(
72
+ "cbc:IdentificationCode",
73
+ { listID: COUNTRY_CODE_LIST_ID },
74
+ address.countryCode
75
+ )
76
+ ]) : null
77
+ ]);
78
+ var party = (source) => el("cac:Party", null, [
79
+ source.endpoint ? el(
80
+ "cbc:EndpointID",
81
+ { schemeID: source.endpoint.scheme },
82
+ source.endpoint.value
83
+ ) : null,
84
+ el("cac:PartyName", null, [el("cbc:Name", null, source.name)]),
85
+ postalAddress(source.address),
86
+ source.vatNumber ? el("cac:PartyTaxScheme", null, [
87
+ el("cbc:CompanyID", null, source.vatNumber),
88
+ vatTaxScheme()
89
+ ]) : null,
90
+ el("cac:PartyLegalEntity", null, [
91
+ el("cbc:RegistrationName", null, source.legalName ?? source.name),
92
+ source.companyId ? el(
93
+ "cbc:CompanyID",
94
+ source.companyId.scheme ? { schemeID: source.companyId.scheme } : null,
95
+ source.companyId.value
96
+ ) : null
97
+ ])
98
+ ]);
99
+ var taxSubtotal = (subtotal, currency) => el("cac:TaxSubtotal", null, [
100
+ money("cbc:TaxableAmount", subtotal.taxableAmount, currency),
101
+ money("cbc:TaxAmount", subtotal.taxAmount, currency),
102
+ taxCategory("cac:TaxCategory", subtotal.category)
103
+ ]);
104
+ var line = (source, currency, documentType) => {
105
+ const lineElementName = documentType === "creditNote" ? "cac:CreditNoteLine" : "cac:InvoiceLine";
106
+ const quantityElementName = documentType === "creditNote" ? "cbc:CreditedQuantity" : "cbc:InvoicedQuantity";
107
+ return el(lineElementName, null, [
108
+ el("cbc:ID", null, source.id),
109
+ el(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),
110
+ money("cbc:LineExtensionAmount", source.lineExtensionAmount, currency),
111
+ el("cac:Item", null, [
112
+ el("cbc:Name", null, source.name),
113
+ taxCategory("cac:ClassifiedTaxCategory", source.taxCategory)
114
+ ]),
115
+ el("cac:Price", null, [money("cbc:PriceAmount", source.priceAmount, currency)])
116
+ ]);
117
+ };
118
+ var attachmentReference = (attachment) => el("cac:AdditionalDocumentReference", null, [
119
+ el("cbc:ID", null, attachment.id),
120
+ el("cac:Attachment", null, [
121
+ el(
122
+ "cbc:EmbeddedDocumentBinaryObject",
123
+ { mimeCode: attachment.mimeCode, filename: attachment.filename },
124
+ attachment.base64
125
+ )
126
+ ])
127
+ ]);
128
+ var billingReference = (precedingInvoiceId) => el("cac:BillingReference", null, [
129
+ el("cac:InvoiceDocumentReference", null, [
130
+ el("cbc:ID", null, precedingInvoiceId)
131
+ ])
132
+ ]);
133
+ var serializeUblDocument = (doc) => {
134
+ const isCreditNote = doc.documentType === "creditNote";
135
+ const rootName = isCreditNote ? "CreditNote" : "Invoice";
136
+ const rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;
137
+ const typeCodeElement = isCreditNote ? el("cbc:CreditNoteTypeCode", null, CREDIT_NOTE_TYPE_CODE) : el("cbc:InvoiceTypeCode", null, INVOICE_TYPE_CODE);
138
+ const children = [
139
+ el("cbc:CustomizationID", null, UBL_CUSTOMIZATION_ID),
140
+ el("cbc:ProfileID", null, UBL_PROFILE_ID),
141
+ el("cbc:ID", null, doc.id),
142
+ el("cbc:IssueDate", null, doc.issueDate),
143
+ // CreditNote has no DueDate element in the UBL sequence.
144
+ !isCreditNote && doc.dueDate ? el("cbc:DueDate", null, doc.dueDate) : null,
145
+ typeCodeElement,
146
+ doc.note ? el("cbc:Note", null, doc.note) : null,
147
+ el("cbc:DocumentCurrencyCode", null, doc.currency),
148
+ doc.buyerReference ? el("cbc:BuyerReference", null, doc.buyerReference) : null,
149
+ doc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,
150
+ ...doc.attachments.map(attachmentReference),
151
+ el("cac:AccountingSupplierParty", null, [party(doc.supplier)]),
152
+ el("cac:AccountingCustomerParty", null, [party(doc.customer)]),
153
+ el("cac:TaxTotal", null, [
154
+ money("cbc:TaxAmount", doc.taxTotal.taxAmount, doc.currency),
155
+ ...doc.taxTotal.subtotals.map(
156
+ (subtotal) => taxSubtotal(subtotal, doc.currency)
157
+ )
158
+ ]),
159
+ el("cac:LegalMonetaryTotal", null, [
160
+ money(
161
+ "cbc:LineExtensionAmount",
162
+ doc.monetaryTotal.lineExtensionAmount,
163
+ doc.currency
164
+ ),
165
+ money(
166
+ "cbc:TaxExclusiveAmount",
167
+ doc.monetaryTotal.taxExclusiveAmount,
168
+ doc.currency
169
+ ),
170
+ money(
171
+ "cbc:TaxInclusiveAmount",
172
+ doc.monetaryTotal.taxInclusiveAmount,
173
+ doc.currency
174
+ ),
175
+ money("cbc:PayableAmount", doc.monetaryTotal.payableAmount, doc.currency)
176
+ ]),
177
+ ...doc.lines.map((source) => line(source, doc.currency, doc.documentType))
178
+ ];
179
+ const root = el(
180
+ rootName,
181
+ {
182
+ xmlns: rootNamespace,
183
+ "xmlns:cac": NS_CAC,
184
+ "xmlns:cbc": NS_CBC
185
+ },
186
+ children.filter((child) => Boolean(child))
187
+ );
188
+ return serializeDocument(root);
189
+ };
190
+
191
+ // src/build/utils.ts
192
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
193
+ var normalizeString = (value) => {
194
+ if (typeof value !== "string") return null;
195
+ const normalized = value.trim();
196
+ return normalized.length > 0 ? normalized : null;
197
+ };
198
+
199
+ // src/build/address.ts
200
+ var normalizeCountryCode = (value) => {
201
+ const trimmed = normalizeString(value);
202
+ if (!trimmed) return null;
203
+ return trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;
204
+ };
205
+ var normalizeAddress = (address, fallbackCountryCode, fallbackLine) => {
206
+ const record = isRecord(address) ? address : {};
207
+ const countryCode = normalizeCountryCode(normalizeString(record.country)) ?? normalizeCountryCode(normalizeString(record.country_code)) ?? normalizeCountryCode(fallbackCountryCode);
208
+ return {
209
+ street: normalizeString(record.line1) ?? normalizeString(record.street) ?? fallbackLine ?? null,
210
+ additionalStreet: normalizeString(record.line2),
211
+ city: normalizeString(record.city),
212
+ postalZone: normalizeString(record.postal_code) ?? normalizeString(record.zip_code),
213
+ countrySubentity: normalizeString(record.state) ?? normalizeString(record.country_subentity),
214
+ countryCode
215
+ };
216
+ };
217
+
218
+ // src/build/identifiers.ts
219
+ var cleanIdentifierValue = (value) => value.trim().replace(/\s+/g, "").replace(/[^A-Za-z0-9]/g, "");
220
+ var normalizeBelgianCompanyNumber = (value) => {
221
+ if (!value) return "";
222
+ return cleanIdentifierValue(value).toUpperCase().replace(/^BE/, "");
223
+ };
224
+ var normalizeCompanyNumberForCountry = (countryCode, companyNumber) => {
225
+ if (!companyNumber) return "";
226
+ const upper = countryCode?.trim().toUpperCase() ?? "";
227
+ if (upper === "BE") return normalizeBelgianCompanyNumber(companyNumber);
228
+ return companyNumber.trim();
229
+ };
230
+ var resolveCompanyIdScheme = (params) => {
231
+ const companyNumber = normalizeString(params.companyNumber);
232
+ if (!companyNumber) return null;
233
+ const TABLE = {
234
+ BE: "0208",
235
+ NL: "0106",
236
+ FR: "0002"
237
+ };
238
+ const normalizedCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;
239
+ if (normalizedCountry && normalizedCountry in TABLE) {
240
+ return TABLE[normalizedCountry] ?? null;
241
+ }
242
+ const countryPrefix = cleanIdentifierValue(companyNumber).toUpperCase().slice(0, 2);
243
+ return countryPrefix in TABLE ? TABLE[countryPrefix] ?? null : null;
244
+ };
245
+ var buildCompanyId = (params) => {
246
+ const normalized = normalizeString(
247
+ normalizeCompanyNumberForCountry(params.countryCode, params.companyNumber)
248
+ );
249
+ if (!normalized) return null;
250
+ return {
251
+ value: normalized,
252
+ scheme: resolveCompanyIdScheme({
253
+ countryCode: params.countryCode,
254
+ companyNumber: normalized
255
+ })
256
+ };
257
+ };
258
+ var VAT_SCHEME_BY_COUNTRY = {
259
+ AD: "9922",
260
+ // Andorra
261
+ AL: "9923",
262
+ // Albania
263
+ AT: "9914",
264
+ // Austria
265
+ BA: "9924",
266
+ // Bosnia and Herzegovina
267
+ BE: "9925",
268
+ // Belgium
269
+ BG: "9926",
270
+ // Bulgaria
271
+ CH: "9927",
272
+ // Switzerland
273
+ CY: "9928",
274
+ // Cyprus
275
+ CZ: "9929",
276
+ // Czech Republic
277
+ DE: "9930",
278
+ // Germany
279
+ EE: "9931",
280
+ // Estonia
281
+ ES: "9920",
282
+ // Spain (Spanish Tax Administration)
283
+ FI: "0213",
284
+ // Finland (Finnish VAT Identifier)
285
+ FR: "9957",
286
+ // France
287
+ GB: "9932",
288
+ // United Kingdom
289
+ GR: "9933",
290
+ // Greece (VAT prefix "EL")
291
+ HR: "9934",
292
+ // Croatia
293
+ HU: "9910",
294
+ // Hungary
295
+ IE: "9935",
296
+ // Ireland
297
+ LI: "9936",
298
+ // Liechtenstein
299
+ LT: "9937",
300
+ // Lithuania
301
+ LU: "9938",
302
+ // Luxembourg
303
+ LV: "9939",
304
+ // Latvia
305
+ MC: "9940",
306
+ // Monaco
307
+ ME: "9941",
308
+ // Montenegro
309
+ MK: "9942",
310
+ // North Macedonia
311
+ MT: "9943",
312
+ // Malta
313
+ NL: "9944",
314
+ // Netherlands
315
+ PL: "9945",
316
+ // Poland
317
+ PT: "9946",
318
+ // Portugal
319
+ RO: "9947",
320
+ // Romania
321
+ RS: "9948",
322
+ // Serbia
323
+ SI: "9949",
324
+ // Slovenia
325
+ SK: "9950",
326
+ // Slovakia
327
+ SM: "9951",
328
+ // San Marino
329
+ TR: "9952",
330
+ // Turkey
331
+ VA: "9953"
332
+ // Holy See / Vatican City
333
+ };
334
+ var VAT_PREFIX_TO_COUNTRY = {
335
+ EL: "GR",
336
+ // Greece issues VAT numbers with the "EL" prefix
337
+ XI: "GB"
338
+ // Northern Ireland VAT is issued under the UK scheme
339
+ };
340
+ var resolveVatEndpoint = (params) => {
341
+ const value = normalizeString(params.vatNumber);
342
+ if (!value) return null;
343
+ const cleaned = cleanIdentifierValue(value).toUpperCase();
344
+ if (!cleaned) return null;
345
+ const prefix = cleaned.slice(0, 2);
346
+ const fromPrefix = /^[A-Z]{2}$/.test(prefix) ? VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix : null;
347
+ const fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;
348
+ const country = fromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;
349
+ const scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : void 0;
350
+ if (!scheme) return null;
351
+ return { scheme, value: cleaned };
352
+ };
353
+ var parsePeppolEndpoint = (peppolId) => {
354
+ const normalized = normalizeString(peppolId);
355
+ if (!normalized) return null;
356
+ const separatorIndex = normalized.indexOf(":");
357
+ if (separatorIndex <= 0) return null;
358
+ const scheme = normalized.slice(0, separatorIndex).trim();
359
+ const value = normalized.slice(separatorIndex + 1).trim();
360
+ if (!scheme || !value) return null;
361
+ return { scheme, value };
362
+ };
363
+ var normalizeIdentifierType = (value) => value?.toLowerCase().replace(/[^a-z0-9]+/g, "_") ?? null;
364
+ var extractCustomerTaxIdentifiers = (taxIds) => {
365
+ let peppolID = null;
366
+ let glnNumber = null;
367
+ let taxNumber = null;
368
+ let vatNumber = null;
369
+ if (!Array.isArray(taxIds)) {
370
+ return { peppolID, glnNumber, taxNumber, vatNumber };
371
+ }
372
+ for (const entry of taxIds) {
373
+ if (!isRecord(entry)) continue;
374
+ const type = normalizeIdentifierType(normalizeString(entry.type));
375
+ const value = normalizeString(entry.value);
376
+ if (!type || !value) continue;
377
+ if (!peppolID && type.includes("peppol")) {
378
+ peppolID = value;
379
+ continue;
380
+ }
381
+ if (!glnNumber && type.includes("gln")) {
382
+ glnNumber = value;
383
+ continue;
384
+ }
385
+ if (!vatNumber && type.includes("vat")) {
386
+ vatNumber = value;
387
+ continue;
388
+ }
389
+ if (!taxNumber && type.includes("tax")) {
390
+ taxNumber = value;
391
+ }
392
+ }
393
+ return { peppolID, glnNumber, taxNumber, vatNumber };
394
+ };
395
+ var listPeppolReceiverIdentifierCandidates = (customer, countryCode) => {
396
+ const candidates = [];
397
+ const add = (id) => {
398
+ if (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);
399
+ };
400
+ const peppol = normalizeString(customer.peppolID);
401
+ if (peppol) candidates.push(peppol);
402
+ const gln = normalizeString(customer.glnNumber);
403
+ if (gln) add({ scheme: "0088", value: cleanIdentifierValue(gln) });
404
+ const vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });
405
+ add(vat);
406
+ if (vat?.scheme === "9925") {
407
+ add(buildCompanyId({ countryCode: "BE", companyNumber: customer.vatNumber ?? null }));
408
+ }
409
+ const tax = normalizeString(customer.taxNumber);
410
+ if (tax) add(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));
411
+ return Array.from(new Set(candidates));
412
+ };
413
+
414
+ // src/build/party.ts
415
+ var buildSupplierParty = (supplier) => {
416
+ const address = normalizeAddress(supplier.address, supplier.countryCode);
417
+ return {
418
+ endpoint: parsePeppolEndpoint(supplier.peppolID),
419
+ name: supplier.name,
420
+ address,
421
+ vatNumber: normalizeString(supplier.vatNumber),
422
+ legalName: supplier.name,
423
+ companyId: buildCompanyId({
424
+ countryCode: supplier.countryCode,
425
+ companyNumber: supplier.companyNumber ?? null
426
+ })
427
+ };
428
+ };
429
+
430
+ // src/build/attachment.ts
431
+ var buildPdfAttachment = (params) => ({
432
+ id: params.id ?? params.filename,
433
+ filename: params.filename,
434
+ mimeCode: "application/pdf",
435
+ base64: Buffer.from(params.bytes).toString("base64")
436
+ });
437
+ var sanitizeUblDocumentForAudit = (doc) => {
438
+ if (doc.attachments.length === 0) return doc;
439
+ return {
440
+ ...doc,
441
+ attachments: doc.attachments.map((attachment) => ({
442
+ ...attachment,
443
+ base64: `[omitted ${attachment.base64.length} chars]`
444
+ }))
445
+ };
446
+ };
447
+
448
+ // src/build/numeric.ts
449
+ var roundCurrency = (value) => Math.round((value + Number.EPSILON) * 100) / 100;
450
+ var centsToDecimal = (cents) => roundCurrency(cents / 100);
451
+
452
+ // src/build/tax-category.ts
453
+ var EXEMPT_TAXABILITY_REASONS = /* @__PURE__ */ new Set([
454
+ "customer_exempt",
455
+ "product_exempt",
456
+ "not_subject_to_tax",
457
+ "not_collecting",
458
+ "not_supported",
459
+ "portion_product_exempt"
460
+ ]);
461
+ var EXEMPTION_REASON_TEXT = {
462
+ reverse_charge: "Reverse charge",
463
+ customer_exempt: "Exempt based on customer status",
464
+ product_exempt: "Exempt based on the supplied goods or services",
465
+ portion_product_exempt: "Exempt based on the supplied goods or services",
466
+ not_subject_to_tax: "Not subject to VAT",
467
+ not_collecting: "VAT not collected",
468
+ not_supported: "VAT not applicable"
469
+ };
470
+ var normalizeTaxCategoryId = (value) => {
471
+ if (typeof value !== "string") return null;
472
+ const normalized = value.trim().toUpperCase();
473
+ return normalized.length > 0 ? normalized : null;
474
+ };
475
+ var taxCategoryFromReasonOrRate = (params) => {
476
+ const categoryHint = normalizeTaxCategoryId(params.taxCategoryId);
477
+ const reason = params.taxabilityReason;
478
+ if (categoryHint === "AE" || reason === "reverse_charge") {
479
+ return {
480
+ id: "AE",
481
+ percent: 0,
482
+ exemptionReason: EXEMPTION_REASON_TEXT.reverse_charge
483
+ };
484
+ }
485
+ if (categoryHint === "E" || reason && EXEMPT_TAXABILITY_REASONS.has(reason)) {
486
+ return {
487
+ id: "E",
488
+ percent: 0,
489
+ exemptionReason: (reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? "Exempt from VAT"
490
+ };
491
+ }
492
+ if (categoryHint === "Z" || reason === "zero_rated" || params.rate <= 0) {
493
+ return { id: "Z", percent: 0 };
494
+ }
495
+ return { id: "S", percent: params.rate };
496
+ };
497
+ var resolveTaxCategoryFromTaxAmounts = (taxAmounts, rate) => {
498
+ for (const ta of taxAmounts) {
499
+ if (!ta.taxability_reason) continue;
500
+ if (ta.taxability_reason === "reverse_charge") {
501
+ return taxCategoryFromReasonOrRate({
502
+ taxabilityReason: "reverse_charge",
503
+ rate
504
+ });
505
+ }
506
+ if (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) {
507
+ return taxCategoryFromReasonOrRate({
508
+ taxabilityReason: ta.taxability_reason,
509
+ rate
510
+ });
511
+ }
512
+ if (ta.taxability_reason === "zero_rated") {
513
+ return taxCategoryFromReasonOrRate({
514
+ taxabilityReason: "zero_rated",
515
+ rate
516
+ });
517
+ }
518
+ }
519
+ return taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });
520
+ };
521
+
522
+ // src/build/tax-totals.ts
523
+ var reconcileLinesToExclTotal = (lines, authoritativeTotalExclVat) => {
524
+ if (lines.length === 0) return lines;
525
+ const computed = roundCurrency(
526
+ lines.reduce((sum, line2) => sum + line2.lineExtensionAmount, 0)
527
+ );
528
+ const diff = roundCurrency(authoritativeTotalExclVat - computed);
529
+ if (diff === 0) return lines;
530
+ const largestIdx = lines.reduce(
531
+ (maxIdx, line2, idx, arr) => line2.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0) ? idx : maxIdx,
532
+ 0
533
+ );
534
+ return lines.map((line2, idx) => {
535
+ if (idx !== largestIdx) return line2;
536
+ const adjusted = roundCurrency(line2.lineExtensionAmount + diff);
537
+ return {
538
+ ...line2,
539
+ lineExtensionAmount: adjusted,
540
+ priceAmount: roundCurrency(adjusted / Math.max(line2.quantity, 1))
541
+ };
542
+ });
543
+ };
544
+ var categoryKey = (category) => `${category.id}:${category.percent}`;
545
+ var buildTaxTotals = (lines) => {
546
+ const groups = /* @__PURE__ */ new Map();
547
+ for (const line2 of lines) {
548
+ const key = categoryKey(line2.taxCategory);
549
+ const current = groups.get(key) ?? {
550
+ category: line2.taxCategory,
551
+ taxableAmount: 0
552
+ };
553
+ current.taxableAmount = roundCurrency(
554
+ current.taxableAmount + line2.lineExtensionAmount
555
+ );
556
+ groups.set(key, current);
557
+ }
558
+ const subtotals = Array.from(groups.values()).map((group) => ({
559
+ taxableAmount: group.taxableAmount,
560
+ taxAmount: roundCurrency(group.taxableAmount * group.category.percent / 100),
561
+ category: group.category
562
+ }));
563
+ const lineExtensionAmount = roundCurrency(
564
+ lines.reduce((sum, line2) => sum + line2.lineExtensionAmount, 0)
565
+ );
566
+ const taxAmount = roundCurrency(
567
+ subtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0)
568
+ );
569
+ const taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);
570
+ return {
571
+ taxTotal: { taxAmount, subtotals },
572
+ monetaryTotal: {
573
+ lineExtensionAmount,
574
+ taxExclusiveAmount: lineExtensionAmount,
575
+ taxInclusiveAmount,
576
+ payableAmount: taxInclusiveAmount
577
+ }
578
+ };
579
+ };
580
+ export {
581
+ COUNTRY_CODE_LIST_ID,
582
+ CREDIT_NOTE_TYPE_CODE,
583
+ DEFAULT_UNIT_CODE,
584
+ EXEMPT_TAXABILITY_REASONS,
585
+ INVOICE_TYPE_CODE,
586
+ NS_CAC,
587
+ NS_CBC,
588
+ NS_CREDIT_NOTE,
589
+ NS_INVOICE,
590
+ UBL_CUSTOMIZATION_ID,
591
+ UBL_PROFILE_ID,
592
+ VAT_TAX_SCHEME_ID,
593
+ buildCompanyId,
594
+ buildPdfAttachment,
595
+ buildSupplierParty,
596
+ buildTaxTotals,
597
+ centsToDecimal,
598
+ el,
599
+ extractCustomerTaxIdentifiers,
600
+ listPeppolReceiverIdentifierCandidates,
601
+ normalizeAddress,
602
+ normalizeCompanyNumberForCountry,
603
+ parsePeppolEndpoint,
604
+ reconcileLinesToExclTotal,
605
+ resolveCompanyIdScheme,
606
+ resolveTaxCategoryFromTaxAmounts,
607
+ resolveVatEndpoint,
608
+ roundCurrency,
609
+ sanitizeUblDocumentForAudit,
610
+ serializeDocument,
611
+ serializeUblDocument,
612
+ taxCategoryFromReasonOrRate
613
+ };
614
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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\ttaxTotal: { taxAmount, subtotals },\n\t\tmonetaryTotal: {\n\t\t\tlineExtensionAmount,\n\t\t\ttaxExclusiveAmount: lineExtensionAmount,\n\t\t\ttaxInclusiveAmount,\n\t\t\tpayableAmount: taxInclusiveAmount,\n\t\t},\n\t};\n};\n"],"mappings":";AAGO,IAAM,uBACZ;AAGM,IAAM,iBAAiB;AAGvB,IAAM,oBAAoB;AAE1B,IAAM,wBAAwB;AAG9B,IAAM,oBAAoB;AAG1B,IAAM,oBAAoB;AAG1B,IAAM,uBAAuB;AAE7B,IAAM,aAAa;AACnB,IAAM,iBACZ;AACM,IAAM,SACZ;AACM,IAAM,SACZ;;;ACCM,IAAM,KAAK,CACjB,MACA,OACA,YACgB;AAChB,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC3B,WAAO;AAAA,MACN;AAAA,MACA,OAAO,SAAS;AAAA,MAChB,UAAU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AAK,IAAIA,MAAK,UAAU,CAAC,CAAC;AAAA,IACjE;AAAA,EACD,CAAC;AACF;AAEA,IAAM,cAAc,CAAC,aACpB,GAAG,SAAS,EAAE,IAAI,SAAS,OAAO;AAkB5B,IAAM,iBAAiB,CAAC,UAA2C;AACzE,QAAM,SAAS,oBAAI,IAGjB;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/package.json CHANGED
@@ -1,13 +1,17 @@
1
1
  {
2
2
  "name": "@financica/ubl",
3
- "version": "0.4.0",
4
- "description": "UBL (Universal Business Language) invoice XML parser for TypeScript",
3
+ "version": "0.6.0",
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
6
  "type": "module",
7
7
  "exports": {
8
8
  ".": {
9
9
  "import": "./dist/index.js",
10
10
  "types": "./dist/index.d.ts"
11
+ },
12
+ "./build": {
13
+ "import": "./dist/build/index.js",
14
+ "types": "./dist/build/index.d.ts"
11
15
  }
12
16
  },
13
17
  "main": "./dist/index.js",