@ripwords/myinvois-client 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/documentManagement.d.ts +2 -2
- package/dist/api/documentSubmission.d.ts +2 -2
- package/dist/api/documentSubmission.js +2 -2
- package/dist/api/documentTypeManagement.d.ts +2 -2
- package/dist/api/notificationManagement.d.ts +2 -2
- package/dist/api/platformLogin.d.ts +2 -2
- package/dist/api/taxpayerValidation.d.ts +2 -2
- package/dist/{document-DLFdGSK1.js → document-D4O7JY0G.js} +9 -3
- package/dist/{document-CCza2JPL.cjs → document-DoQEvmcK.cjs} +10 -4
- package/dist/document-DoQEvmcK.cjs.map +1 -0
- package/dist/{documentSubmission-M4UlirJ7.cjs → documentSubmission-DUsjqWhR.cjs} +2 -2
- package/dist/{documentSubmission-M4UlirJ7.cjs.map → documentSubmission-DUsjqWhR.cjs.map} +1 -1
- package/dist/{documentSubmission-ZAgXsd3X.js → documentSubmission-uJ7yPWub.js} +1 -1
- package/dist/{documents-DCZ3Ffya.d.cts → documents-BECak3KN.d.cts} +7 -1
- package/dist/{documents-DzZA3NHj.d.ts → documents-Dp19RgNX.d.ts} +6 -0
- package/dist/index.cjs +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/index18.cjs +2 -2
- package/dist/index33.cjs +4 -17
- package/dist/index34.cjs +9 -34
- package/dist/index34.cjs.map +1 -1
- package/dist/index35.cjs +4 -18
- package/dist/index36.cjs +21 -28
- package/dist/index37.cjs +2 -19
- package/dist/index38.cjs +2 -13
- package/dist/index39.cjs +324 -8
- package/dist/index39.cjs.map +1 -1
- package/dist/index40.cjs +187 -11
- package/dist/index40.cjs.map +1 -1
- package/dist/index41.cjs +11 -6
- package/dist/index41.cjs.map +1 -1
- package/dist/index42.cjs +31 -101
- package/dist/index42.cjs.map +1 -1
- package/dist/index43.cjs +12 -106
- package/dist/index43.cjs.map +1 -1
- package/dist/index44.cjs +22 -119
- package/dist/index44.cjs.map +1 -1
- package/dist/index45.cjs +13 -106
- package/dist/index45.cjs.map +1 -1
- package/dist/index46.cjs +7 -98
- package/dist/index46.cjs.map +1 -1
- package/dist/index47.cjs +7 -118
- package/dist/index47.cjs.map +1 -1
- package/dist/index48.cjs +10 -127
- package/dist/index48.cjs.map +1 -1
- package/dist/index49.cjs +6 -117
- package/dist/index49.cjs.map +1 -1
- package/dist/index50.cjs +101 -14
- package/dist/index50.cjs.map +1 -1
- package/dist/index51.cjs +106 -95
- package/dist/index51.cjs.map +1 -1
- package/dist/index52.cjs +119 -142
- package/dist/index52.cjs.map +1 -1
- package/dist/index53.cjs +106 -114
- package/dist/index53.cjs.map +1 -1
- package/dist/index54.cjs +98 -144
- package/dist/index54.cjs.map +1 -1
- package/dist/index55.cjs +118 -113
- package/dist/index55.cjs.map +1 -1
- package/dist/index56.cjs +127 -17
- package/dist/index56.cjs.map +1 -1
- package/dist/index57.cjs +117 -112
- package/dist/index57.cjs.map +1 -1
- package/dist/index58.cjs +14 -47
- package/dist/index58.cjs.map +1 -1
- package/dist/index59.cjs +95 -14
- package/dist/index59.cjs.map +1 -1
- package/dist/index60.cjs +142 -28
- package/dist/index60.cjs.map +1 -1
- package/dist/index61.cjs +114 -22
- package/dist/index61.cjs.map +1 -1
- package/dist/index62.cjs +144 -9
- package/dist/index62.cjs.map +1 -1
- package/dist/index63.cjs +113 -8
- package/dist/index63.cjs.map +1 -1
- package/dist/index64.cjs +17 -17
- package/dist/index64.cjs.map +1 -1
- package/dist/index65.cjs +112 -412
- package/dist/index65.cjs.map +1 -1
- package/dist/index66.cjs +47 -8
- package/dist/index66.cjs.map +1 -1
- package/dist/index67.cjs +14 -9
- package/dist/index67.cjs.map +1 -1
- package/dist/index68.cjs +34 -4
- package/dist/index68.cjs.map +1 -0
- package/dist/index69.cjs +25 -9
- package/dist/index69.cjs.map +1 -1
- package/dist/index70.cjs +15 -4
- package/dist/index70.cjs.map +1 -0
- package/dist/index71.cjs +14 -21
- package/dist/index71.cjs.map +1 -0
- package/dist/index71.cts.map +1 -1
- package/dist/index72.cjs +23 -2
- package/dist/index72.cjs.map +1 -0
- package/dist/index73.cjs +418 -2
- package/dist/index73.cjs.map +1 -0
- package/dist/index74.cjs +9 -324
- package/dist/index74.cjs.map +1 -1
- package/dist/index75.cjs +10 -187
- package/dist/index75.cjs.map +1 -1
- package/dist/{taxpayer-DmHW0m7o.d.ts → taxpayer-BdvCGHHC.d.ts} +1 -1
- package/dist/{taxpayer-Pm90MrPj.d.cts → taxpayer-CaDfslWB.d.cts} +2 -2
- package/dist/types/documents.d.ts +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/taxpayer.d.ts +2 -2
- package/dist/utils/document.d.ts +4 -3
- package/dist/utils/document.js +1 -1
- package/dist/utils/signature-diagnostics.d.ts +2 -2
- package/dist/utils/signature-diagnostics.js +1 -1
- package/dist/utils/validation.d.ts +2 -2
- package/package.json +1 -1
- package/dist/document-CCza2JPL.cjs.map +0 -1
- package/dist/index33.cjs.map +0 -1
- package/dist/index35.cjs.map +0 -1
- package/dist/index36.cjs.map +0 -1
- package/dist/index37.cjs.map +0 -1
- package/dist/index38.cjs.map +0 -1
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { DocumentStatus, DocumentSummary, DocumentValidationResult, DocumentValidationStepResult } from "../documents-
|
|
54
|
+
import { DocumentStatus, DocumentSummary, DocumentValidationResult, DocumentValidationStepResult } from "../documents-Dp19RgNX.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-BdvCGHHC.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { AllDocumentsV1_1, DocumentSummary, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus } from "../documents-
|
|
54
|
+
import { AllDocumentsV1_1, DocumentSummary, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus } from "../documents-Dp19RgNX.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-BdvCGHHC.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "../formatIdValue-qTxJqj9o.js";
|
|
2
|
-
import "../document-
|
|
3
|
-
import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-
|
|
2
|
+
import "../document-D4O7JY0G.js";
|
|
3
|
+
import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-uJ7yPWub.js";
|
|
4
4
|
|
|
5
5
|
export { getSubmissionStatus, performDocumentAction, submitDocument };
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { DocumentTypeResponse, DocumentTypeVersionResponse, DocumentTypesResponse } from "../documents-
|
|
54
|
+
import { DocumentTypeResponse, DocumentTypeVersionResponse, DocumentTypesResponse } from "../documents-Dp19RgNX.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-BdvCGHHC.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import "../documents-
|
|
54
|
+
import "../documents-Dp19RgNX.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import { NotificationResponse, NotificationSearchParams } from "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-BdvCGHHC.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import "../documents-
|
|
54
|
+
import "../documents-Dp19RgNX.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-BdvCGHHC.js";
|
|
59
59
|
import "../utils-C4FoVKLq.js";
|
|
60
60
|
import { ClientCredentials } from "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { RegistrationType } from "../documents-
|
|
54
|
+
import { RegistrationType } from "../documents-Dp19RgNX.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "../taxpayer-
|
|
58
|
+
import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "../taxpayer-BdvCGHHC.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -173,6 +173,10 @@ const generateCleanInvoiceObject = (invoice) => {
|
|
|
173
173
|
_: invoice.legalMonetaryTotal.taxInclusiveAmount,
|
|
174
174
|
currencyID: invoice.invoiceCurrencyCode
|
|
175
175
|
}],
|
|
176
|
+
PayableRoundingAmount: [{
|
|
177
|
+
_: invoice.legalMonetaryTotal.payableRoundingAmount,
|
|
178
|
+
currencyID: invoice.invoiceCurrencyCode
|
|
179
|
+
}],
|
|
176
180
|
PayableAmount: [{
|
|
177
181
|
_: invoice.legalMonetaryTotal.payableAmount,
|
|
178
182
|
currencyID: invoice.invoiceCurrencyCode
|
|
@@ -545,7 +549,7 @@ const generateCompleteDocument = (invoices, signingCredentials) => {
|
|
|
545
549
|
* Creates a line item with percentage-based taxation (e.g., SST, GST)
|
|
546
550
|
*/
|
|
547
551
|
const createPercentageTaxLineItem = (params) => {
|
|
548
|
-
const quantity = params.quantity
|
|
552
|
+
const quantity = params.quantity ? params.quantity <= 0 ? 1 : params.quantity ?? 1 : 1;
|
|
549
553
|
const preDiscountAmount = params.unitPrice * quantity;
|
|
550
554
|
const hasDiscount = params.discountAmount !== void 0 || params.discountRate !== void 0;
|
|
551
555
|
const computedDiscountByRate = hasDiscount && params.discountRate !== void 0 ? preDiscountAmount * params.discountRate : 0;
|
|
@@ -594,15 +598,17 @@ const createFixedRateTaxLineItem = (params) => {
|
|
|
594
598
|
/**
|
|
595
599
|
* Calculates invoice totals from line items
|
|
596
600
|
*/
|
|
597
|
-
const calculateInvoiceTotals = (lineItems) => {
|
|
601
|
+
const calculateInvoiceTotals = (lineItems, payableRoundingAmount = 0) => {
|
|
598
602
|
const taxExclusiveAmount = lineItems.reduce((sum, item) => sum + item.totalTaxableAmountPerLine, 0);
|
|
599
603
|
const totalTaxAmount = lineItems.reduce((sum, item) => sum + item.taxAmount, 0);
|
|
600
604
|
const taxInclusiveAmount = taxExclusiveAmount + totalTaxAmount;
|
|
605
|
+
const payableAmount = taxInclusiveAmount + payableRoundingAmount;
|
|
601
606
|
return {
|
|
602
607
|
legalMonetaryTotal: {
|
|
603
608
|
taxExclusiveAmount: Math.round(taxExclusiveAmount * 100) / 100,
|
|
604
609
|
taxInclusiveAmount: Math.round(taxInclusiveAmount * 100) / 100,
|
|
605
|
-
|
|
610
|
+
payableRoundingAmount: Math.round(payableRoundingAmount * 100) / 100,
|
|
611
|
+
payableAmount: Math.round(payableAmount * 100) / 100
|
|
606
612
|
},
|
|
607
613
|
taxTotal: { taxAmount: Math.round(totalTaxAmount * 100) / 100 }
|
|
608
614
|
};
|
|
@@ -174,6 +174,10 @@ const generateCleanInvoiceObject = (invoice) => {
|
|
|
174
174
|
_: invoice.legalMonetaryTotal.taxInclusiveAmount,
|
|
175
175
|
currencyID: invoice.invoiceCurrencyCode
|
|
176
176
|
}],
|
|
177
|
+
PayableRoundingAmount: [{
|
|
178
|
+
_: invoice.legalMonetaryTotal.payableRoundingAmount,
|
|
179
|
+
currencyID: invoice.invoiceCurrencyCode
|
|
180
|
+
}],
|
|
177
181
|
PayableAmount: [{
|
|
178
182
|
_: invoice.legalMonetaryTotal.payableAmount,
|
|
179
183
|
currencyID: invoice.invoiceCurrencyCode
|
|
@@ -546,7 +550,7 @@ const generateCompleteDocument = (invoices, signingCredentials) => {
|
|
|
546
550
|
* Creates a line item with percentage-based taxation (e.g., SST, GST)
|
|
547
551
|
*/
|
|
548
552
|
const createPercentageTaxLineItem = (params) => {
|
|
549
|
-
const quantity = params.quantity
|
|
553
|
+
const quantity = params.quantity ? params.quantity <= 0 ? 1 : params.quantity ?? 1 : 1;
|
|
550
554
|
const preDiscountAmount = params.unitPrice * quantity;
|
|
551
555
|
const hasDiscount = params.discountAmount !== void 0 || params.discountRate !== void 0;
|
|
552
556
|
const computedDiscountByRate = hasDiscount && params.discountRate !== void 0 ? preDiscountAmount * params.discountRate : 0;
|
|
@@ -595,15 +599,17 @@ const createFixedRateTaxLineItem = (params) => {
|
|
|
595
599
|
/**
|
|
596
600
|
* Calculates invoice totals from line items
|
|
597
601
|
*/
|
|
598
|
-
const calculateInvoiceTotals = (lineItems) => {
|
|
602
|
+
const calculateInvoiceTotals = (lineItems, payableRoundingAmount = 0) => {
|
|
599
603
|
const taxExclusiveAmount = lineItems.reduce((sum, item) => sum + item.totalTaxableAmountPerLine, 0);
|
|
600
604
|
const totalTaxAmount = lineItems.reduce((sum, item) => sum + item.taxAmount, 0);
|
|
601
605
|
const taxInclusiveAmount = taxExclusiveAmount + totalTaxAmount;
|
|
606
|
+
const payableAmount = taxInclusiveAmount + payableRoundingAmount;
|
|
602
607
|
return {
|
|
603
608
|
legalMonetaryTotal: {
|
|
604
609
|
taxExclusiveAmount: Math.round(taxExclusiveAmount * 100) / 100,
|
|
605
610
|
taxInclusiveAmount: Math.round(taxInclusiveAmount * 100) / 100,
|
|
606
|
-
|
|
611
|
+
payableRoundingAmount: Math.round(payableRoundingAmount * 100) / 100,
|
|
612
|
+
payableAmount: Math.round(payableAmount * 100) / 100
|
|
607
613
|
},
|
|
608
614
|
taxTotal: { taxAmount: Math.round(totalTaxAmount * 100) / 100 }
|
|
609
615
|
};
|
|
@@ -724,4 +730,4 @@ Object.defineProperty(exports, 'transformDocumentForHashing', {
|
|
|
724
730
|
return transformDocumentForHashing;
|
|
725
731
|
}
|
|
726
732
|
});
|
|
727
|
-
//# sourceMappingURL=document-
|
|
733
|
+
//# sourceMappingURL=document-DoQEvmcK.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document-DoQEvmcK.cjs","names":["item: InvoiceLineItem","doc: AllDocumentsV1_1","obj: unknown","sortedObj: Record<string, unknown>","invoice: AllDocumentsV1_1","invoices: AllDocumentsV1_1[]","invoice: InvoiceSubmission","certificatePem: string","X509Certificate","str: string","issuer: string","serialHex: string","error: unknown","certificateDigest: string","signingTime: string","issuerName: string","serialNumber: string","signedProperties: SignedPropertiesObject","useTargetWrapper: boolean","digestObj: unknown","docDigest: string","propsDigest: string","privateKeyPem: string","signedInfo: SignedInfoObject","documentString: string","signingCredentials: SigningCredentials","params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxRate: number\n totalTaxableAmountPerLine?: number\n discountAmount?: number\n discountRate?: number\n}","params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: UnitTypeCode\n totalTaxableAmountPerLine?: number\n discountAmount?: number\n discountRate?: number\n}","lineItems: InvoiceLineItem[]","payableRoundingAmount: number"],"sources":["../src/utils/document.ts"],"sourcesContent":["import crypto, { X509Certificate } from 'crypto'\nimport {\n InvoiceSubmission,\n AllDocumentsV1_1,\n SigningCredentials,\n SignedPropertiesObject,\n UBLDocument,\n CompleteInvoice,\n SignedInfoObject,\n UnitTypeCode,\n InvoiceLineItem,\n} from '../types'\nimport type { ClassificationCode } from '../types'\nimport type { TaxTypeCode } from '../types'\nimport { formatIdValue } from './formatIdValue'\n\n/**\n * MyInvois v1.1 Document Generation and Signing Utilities\n * Strictly follows: https://sdk.myinvois.hasil.gov.my/documents/invoice-v1-1\n * JSON Signature Guide: https://sdk.myinvois.hasil.gov.my/signature-creation-json/\n */\n\n/**\n * Determines if a line item uses fixed rate taxation\n */\nexport const isFixedRateTax = (item: InvoiceLineItem): boolean => {\n return (\n item.taxPerUnitAmount !== undefined && item.baseUnitMeasure !== undefined\n )\n}\n\n/**\n * Determines if a line item uses percentage taxation\n */\nexport const isPercentageTax = (item: InvoiceLineItem): boolean => {\n return item.taxRate !== undefined && !isFixedRateTax(item)\n}\n\n/**\n * Calculates expected tax amount for a line item based on its tax type\n */\nexport const calculateExpectedTaxAmount = (item: InvoiceLineItem): number => {\n if (isFixedRateTax(item)) {\n return item.taxPerUnitAmount! * item.baseUnitMeasure!\n } else if (isPercentageTax(item)) {\n return (item.totalTaxableAmountPerLine * item.taxRate!) / 100\n }\n return 0\n}\n\n/**\n * Extracts the line-item array from any document variant\n */\nconst getLineItems = (doc: AllDocumentsV1_1): InvoiceLineItem[] => {\n if ('invoiceLineItems' in doc) return doc.invoiceLineItems\n if ('creditNoteLineItems' in doc) return doc.creditNoteLineItems\n if ('debitNoteLineItems' in doc) return doc.debitNoteLineItems\n if ('refundNoteLineItems' in doc) return doc.refundNoteLineItems\n if ('selfBilledCreditNoteLineItems' in doc)\n return doc.selfBilledCreditNoteLineItems\n if ('selfBilledRefundNoteLineItems' in doc)\n return doc.selfBilledRefundNoteLineItems\n // Fallback (should never happen with exhaustive types)\n return []\n}\n\n/**\n * Helper function to recursively sort object keys for JSON canonicalization\n */\nexport function sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortObjectKeys)\n }\n\n const sortedObj: Record<string, unknown> = {}\n const keys = Object.keys(obj as Record<string, unknown>).sort()\n\n for (const key of keys) {\n sortedObj[key] = sortObjectKeys((obj as Record<string, unknown>)[key])\n }\n\n return sortedObj\n}\n\n/**\n * Enhanced canonicalization following MyInvois specification exactly\n * Key changes: ensure consistent ordering and formatting\n */\nexport const canonicalizeJSON = (obj: unknown): string => {\n const sortedObj = sortObjectKeys(obj)\n // Use compact JSON with no extra whitespace\n return JSON.stringify(sortedObj, null, 0)\n}\n\n/**\n * Generates a clean invoice object following MyInvois v1.1 specification exactly\n * This is the base invoice structure WITHOUT signature elements (for hash calculation)\n *\n * Key requirements from working documents:\n * - All mandatory fields must be present\n * - Many optional fields must be present even if empty\n * - Specific field ordering and structure\n * - Correct listID values (e.g., \"3166-1\" not \"ISO3166-1\")\n */\nexport const generateCleanInvoiceObject = (\n invoice: AllDocumentsV1_1,\n): InvoiceSubmission => {\n const lineItems = getLineItems(invoice)\n return {\n // === MANDATORY CORE FIELDS ===\n ID: [{ _: invoice.eInvoiceCodeOrNumber }],\n IssueDate: [{ _: invoice.eInvoiceDate }],\n IssueTime: [{ _: invoice.eInvoiceTime }],\n InvoiceTypeCode: [\n {\n _: invoice.eInvoiceTypeCode,\n listVersionID: invoice.eInvoiceVersion || '1.1',\n },\n ],\n DocumentCurrencyCode: [{ _: invoice.invoiceCurrencyCode }],\n\n // === BILLING REFERENCE (only for credit/debit/refund notes) ===\n ...('originalEInvoiceReferenceNumber' in invoice &&\n 'originalEInvoiceInternalId' in invoice &&\n invoice.originalEInvoiceReferenceNumber\n ? {\n BillingReference: [\n {\n InvoiceDocumentReference: [\n {\n UUID: [\n {\n _: invoice.originalEInvoiceReferenceNumber,\n },\n ],\n ID: [\n {\n _: invoice.originalEInvoiceInternalId,\n },\n ],\n },\n ],\n },\n ],\n }\n : {}),\n\n // === SUPPLIER PARTY (AccountingSupplierParty) ===\n AccountingSupplierParty: [\n {\n Party: [\n {\n // Industry Classification - required field\n IndustryClassificationCode: [\n {\n _: invoice.supplier.industryClassificationCode,\n name: invoice.supplier.industryClassificationDescription,\n },\n ],\n\n // Party Identifications\n PartyIdentification: [\n {\n ID: [\n {\n _: invoice.supplier.tin,\n schemeID: 'TIN',\n },\n ],\n },\n {\n ID: [\n {\n _: formatIdValue(invoice.supplier.registrationNumber),\n schemeID: invoice.supplier.registrationType || 'NRIC',\n },\n ],\n },\n ],\n\n // Postal Address - FIXED listID format\n PostalAddress: [\n {\n CityName: [{ _: invoice.supplier.address.cityName }],\n CountrySubentityCode: [{ _: invoice.supplier.address.state }],\n AddressLine: [\n {\n Line: [{ _: invoice.supplier.address.addressLine0 }],\n },\n ],\n Country: [\n {\n IdentificationCode: [\n {\n _: invoice.supplier.address.country || 'MYS',\n listID: '3166-1', // FIXED: was \"ISO3166-1\"\n listAgencyID: 'ISO',\n },\n ],\n },\n ],\n },\n ],\n\n // Party Legal Entity\n PartyLegalEntity: [\n {\n RegistrationName: [{ _: invoice.supplier.name }],\n },\n ],\n\n // Contact Information\n Contact: [\n {\n Telephone: [{ _: invoice.supplier.contactNumber || '' }],\n },\n ],\n },\n ],\n },\n ],\n\n // === BUYER PARTY (AccountingCustomerParty) ===\n AccountingCustomerParty: [\n {\n Party: [\n {\n // Party Identifications\n PartyIdentification: [\n {\n ID: [\n {\n _: invoice.buyer.tin,\n schemeID: 'TIN',\n },\n ],\n },\n {\n ID: [\n {\n _: formatIdValue(invoice.buyer.registrationNumber),\n schemeID: invoice.buyer.registrationType || 'NRIC',\n },\n ],\n },\n {\n ID: [\n {\n _: invoice.buyer.sstRegistrationNumber || 'NA',\n schemeID: 'SST',\n },\n ],\n },\n ],\n\n // Postal Address - FIXED listID format\n PostalAddress: [\n {\n CityName: [{ _: invoice.buyer.address.cityName }],\n CountrySubentityCode: [{ _: invoice.buyer.address.state }],\n AddressLine: [\n {\n Line: [{ _: invoice.buyer.address.addressLine0 }],\n },\n ],\n Country: [\n {\n IdentificationCode: [\n {\n _: invoice.buyer.address.country || 'MYS',\n listID: '3166-1', // FIXED: was \"ISO3166-1\"\n listAgencyID: 'ISO',\n },\n ],\n },\n ],\n },\n ],\n\n // Party Legal Entity\n PartyLegalEntity: [\n {\n RegistrationName: [{ _: invoice.buyer.name }],\n },\n ],\n\n // Contact Information\n Contact: [\n {\n Telephone: [{ _: invoice.buyer.contactNumber || '' }],\n },\n ],\n },\n ],\n },\n ],\n\n // === TAX TOTAL ===\n TaxTotal: [\n {\n TaxAmount: [\n {\n _: invoice.taxTotal.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxSubtotal: [\n // Generate basic tax subtotal from invoice line items\n {\n TaxableAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxAmount: [\n {\n _: invoice.taxTotal.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxCategory: [\n {\n ID: [{ _: lineItems[0]?.taxType || '01' }],\n TaxScheme: [\n {\n ID: [\n {\n _: 'OTH',\n schemeAgencyID: '6',\n schemeID: 'UN/ECE 5153',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n\n // === LEGAL MONETARY TOTAL ===\n LegalMonetaryTotal: [\n {\n LineExtensionAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxExclusiveAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxInclusiveAmount: [\n {\n _: invoice.legalMonetaryTotal.taxInclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n PayableRoundingAmount: [\n {\n _: invoice.legalMonetaryTotal.payableRoundingAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n PayableAmount: [\n {\n _: invoice.legalMonetaryTotal.payableAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n // === INVOICE LINES ===\n InvoiceLine: lineItems.map((item, index) => ({\n ID: [{ _: (index + 1).toString() }],\n\n // Item Information\n Item: [\n {\n CommodityClassification: [\n {\n ItemClassificationCode: [\n {\n _: item.itemClassificationCode,\n listID: 'CLASS',\n },\n ],\n },\n ],\n Description: [{ _: item.itemDescription }],\n },\n ],\n\n ItemPriceExtension: [\n {\n Amount: [\n {\n _:\n (item.totalTaxableAmountPerLine ?? 0) +\n (item.discountAmount ?? 0),\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n LineExtensionAmount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n\n // Price Information\n Price: [\n {\n PriceAmount: [\n {\n _: item.unitPrice,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n // Line-level discount (AllowanceCharge with ChargeIndicator=false) – include only if a discount exists\n ...(item.discountAmount !== undefined || item.discountRate !== undefined\n ? {\n AllowanceCharge: [\n {\n ChargeIndicator: [{ _: false }],\n Amount: [\n {\n _: item.discountAmount ?? 0,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n ...(item.discountRate !== undefined\n ? {\n MultiplierFactorNumeric: [{ _: item.discountRate }],\n BaseAmount: [\n {\n _:\n (item.totalTaxableAmountPerLine ?? 0) +\n (item.discountAmount ?? 0),\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n }\n : {}),\n },\n ],\n }\n : {}),\n\n // Tax Information for line\n TaxTotal: [\n {\n TaxAmount: [\n {\n _: item.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxSubtotal: [\n {\n TaxableAmount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxAmount: [\n {\n _: item.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n // Conditional tax fields based on taxation type\n ...(item.taxPerUnitAmount !== undefined &&\n item.baseUnitMeasure !== undefined\n ? {\n // Fixed Rate Taxation\n PerUnitAmount: [\n {\n _: item.taxPerUnitAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n BaseUnitMeasure: [\n {\n _: item.baseUnitMeasure,\n unitCode: item.baseUnitMeasureCode || 'C62',\n },\n ],\n }\n : item.taxRate !== undefined\n ? {\n // Percentage Taxation\n Percent: [{ _: item.taxRate }],\n }\n : {}),\n TaxCategory: [\n {\n ID: [{ _: item.taxType }],\n TaxScheme: [\n {\n ID: [\n {\n _: 'OTH',\n schemeAgencyID: '6',\n schemeID: 'UN/ECE 5153',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n })),\n\n // === TAX EXCHANGE RATE (mandatory where applicable) ===\n TaxExchangeRate: invoice.currencyExchangeRate\n ? [\n {\n SourceCurrencyCode: [\n {\n _: invoice.invoiceCurrencyCode,\n },\n ],\n TargetCurrencyCode: [\n {\n _: 'MYR',\n },\n ],\n CalculationRate: [\n {\n _: invoice.currencyExchangeRate,\n },\n ],\n },\n ]\n : undefined,\n }\n}\n\n/**\n * Generates the complete UBL document structure with namespace declarations\n */\nexport const generateCleanUBLDocument = (\n invoices: AllDocumentsV1_1[],\n): UBLDocument => {\n return {\n _D: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',\n _A: 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',\n _B: 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',\n Invoice: invoices.map(generateCleanInvoiceObject),\n }\n}\n\n/**\n * Step 1: Transform the document for hashing or transmission\n * Removes UBLExtensions and Signature, and minifies the JSON\n * Returns the minified, cleaned JSON string\n *\n * FIXED: Use regex-based minification to match PowerShell script exactly\n */\nexport const transformDocumentForHashing = (\n invoices: AllDocumentsV1_1[],\n): string => {\n // Generate clean UBL document structure\n const cleanDocument = generateCleanUBLDocument(invoices)\n\n // Deep clone to avoid mutating input\n const documentForTransform = JSON.parse(JSON.stringify(cleanDocument))\n if (\n documentForTransform.Invoice &&\n Array.isArray(documentForTransform.Invoice)\n ) {\n documentForTransform.Invoice.forEach((invoice: InvoiceSubmission) => {\n delete invoice.UBLExtensions\n delete invoice.Signature\n })\n }\n\n // Convert to JSON string first\n const jsonString = JSON.stringify(documentForTransform)\n\n // Apply the exact same regex-based minification as PowerShell script\n // This regex preserves whitespace within quoted strings but removes all other whitespace\n const minifiedJson = jsonString.replace(\n /(\"(?:\\\\.|[^\"\\\\])*\")|\\s+/g,\n (match, quotedString) => {\n if (quotedString) {\n return quotedString // Keep string content exactly as-is\n } else {\n return '' // Remove all other whitespace\n }\n },\n )\n\n return minifiedJson\n}\n\n/**\n * Step 2: Calculate Document Digest\n * FIXED: Remove UBLExtensions and Signature before hashing (DS322)\n * Based on working implementation pattern\n */\nexport const calculateDocumentDigest = (\n invoices: AllDocumentsV1_1[],\n): string => {\n // Use the transformation function to get the minified, cleaned JSON string\n const documentString = transformDocumentForHashing(invoices)\n\n // Calculate SHA-256 hash\n const hash = crypto.createHash('sha256')\n hash.update(documentString, 'utf8')\n\n // Return as Base64 (DocDigest)\n return hash.digest('base64')\n}\n\n/**\n * Step 4: Calculate Certificate Digest\n * Enhanced to handle certificate content properly\n * FIXED: Match PowerShell script exactly - use raw certificate data like $cert.RawData\n */\nexport const calculateCertificateDigest = (certificatePem: string): string => {\n try {\n // Create X509Certificate object to get raw data (like PowerShell $cert.RawData)\n const cert = new X509Certificate(certificatePem)\n\n // Get the raw certificate data (DER-encoded, like PowerShell $cert.RawData)\n const rawCertificateData = cert.raw\n\n // Calculate SHA-256 hash of raw certificate data (like PowerShell $sha256.ComputeHash($cert.RawData))\n const hash = crypto.createHash('sha256')\n hash.update(rawCertificateData)\n\n // Return as Base64 (like PowerShell [Convert]::ToBase64String($certHash))\n return hash.digest('base64')\n } catch {\n // Fallback to the previous method if X509Certificate fails\n const certificateContent = certificatePem\n .replace(/-----BEGIN CERTIFICATE-----/g, '')\n .replace(/-----END CERTIFICATE-----/g, '')\n .replace(/\\s+/g, '') // Remove all whitespace\n\n // Convert Base64 to binary\n const certificateBinary = Buffer.from(certificateContent, 'base64')\n\n // Calculate SHA-256 hash of binary content\n const hash = crypto.createHash('sha256')\n hash.update(certificateBinary)\n\n // Return as Base64\n return hash.digest('base64')\n }\n}\n\n/**\n * Enhanced certificate info extraction with better error handling\n * FIXED: Normalize issuer name format to match MyInvois expectations (DS326)\n */\nexport const extractCertificateInfo = (\n certificatePem: string,\n): {\n issuerName: string\n serialNumber: string\n subjectName: string\n} => {\n try {\n const cert = new X509Certificate(certificatePem)\n\n // Extract serial number and convert to decimal string\n const serialNumberHex = cert.serialNumber\n\n // FIXED: Use raw issuer name like PowerShell $cert.IssuerName.Name\n // Apply XML escaping to match PowerShell [System.Security.SecurityElement]::Escape()\n const escapeXmlSpecialChars = (str: string): string => {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n }\n\n // FIXED: Normalize issuer name to match MyInvois expectations\n // The issuer name should be in the format: \"CN=Trial LHDNM Sub CA V1, OU=Terms of use at http://www.testcertcomp.com.my, O=LHDNM, C=MY\"\n const normalizeIssuerName = (issuer: string): string => {\n // Node returns issuer DN in reverse RDN order (C, O, ... , CN).\n // The MyInvois validator expects forward order (CN first).\n // 1. Break DN into components separated by newline or commas.\n // 2. Reverse to get CN → ... → C ordering.\n // 3. Join with \", \" and ensure single '=' spacing.\n const parts = issuer\n .split(/\\r?\\n|,\\s*/)\n .map(part => part.trim())\n .filter(part => part.length > 0)\n .reverse()\n return parts.join(', ').replace(/\\s*=\\s*/g, '=')\n }\n\n // Enhanced serial number formatting\n const formatSerialNumber = (serialHex: string): string => {\n // Convert hex to decimal and ensure it's a string\n const decimal = BigInt('0x' + serialHex).toString()\n return decimal\n }\n\n // FIXED: Use raw subject name without normalization to match PowerShell $cert.SubjectName.Name\n // The subject name should be in the format shown in the specification\n const rawSubjectName = cert.subject\n\n return {\n issuerName: escapeXmlSpecialChars(normalizeIssuerName(cert.issuer)),\n serialNumber: formatSerialNumber(serialNumberHex),\n subjectName: rawSubjectName, // Use raw subject name like PowerShell\n }\n } catch (error: unknown) {\n throw new Error(\n `Failed to extract certificate info: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Step 5: Create SignedProperties with enhanced structure\n * FIXED: Simplified structure to match MyInvois expectations (DS320)\n * Following MyInvois JSON signature specification exactly\n */\nexport const createSignedProperties = (\n certificateDigest: string,\n signingTime: string,\n issuerName: string,\n serialNumber: string,\n): SignedPropertiesObject => {\n return {\n SignedProperties: [\n {\n Id: 'id-xades-signed-props',\n SignedSignatureProperties: [\n {\n SigningTime: [{ _: signingTime }],\n SigningCertificate: [\n {\n Cert: [\n {\n CertDigest: [\n {\n DigestMethod: [\n {\n _: '',\n Algorithm:\n 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: certificateDigest }],\n },\n ],\n IssuerSerial: [\n {\n X509IssuerName: [{ _: issuerName }],\n X509SerialNumber: [{ _: serialNumber }],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Step 6: Calculate SignedProperties Digest\n * Calculates the digest over the correct structure for validator compliance.\n * FIXED: Calculate digest from SignedProperties only (without Target wrapper)\n */\nexport const calculateSignedPropertiesDigest = (\n signedProperties: SignedPropertiesObject,\n useTargetWrapper: boolean = true, // Changed to true - validator calculates digest from embedded structure with Target wrapper\n): string => {\n let digestObj: unknown\n if (useTargetWrapper) {\n digestObj = {\n Target: 'signature',\n SignedProperties: signedProperties.SignedProperties,\n }\n } else {\n digestObj = signedProperties.SignedProperties\n }\n\n // FIXED: Don't sort object keys - use exact structure as embedded\n // The validator calculates digest from the exact embedded structure\n const signedPropertiesString = JSON.stringify(digestObj)\n\n // Apply the same regex-based minification as the document transformation\n const minifiedSignedProperties = signedPropertiesString.replace(\n /(\"(?:\\\\.|[^\"\\\\])*\")|\\s+/g,\n (match, quotedString) => {\n if (quotedString) {\n return quotedString // Keep string content exactly as-is\n } else {\n return '' // Remove all other whitespace\n }\n },\n )\n\n const hash = crypto.createHash('sha256')\n hash.update(minifiedSignedProperties, 'utf8')\n return hash.digest('base64')\n}\n\n/**\n * Step 3: Create SignedInfo and calculate signature\n * Enhanced with better structure and signature generation\n */\nexport const createSignedInfoAndSign = (\n docDigest: string,\n propsDigest: string,\n privateKeyPem: string,\n): { signedInfo: SignedInfoObject; signatureValue: string } => {\n // Create SignedInfo structure following specification exactly\n const signedInfo: SignedInfoObject = {\n CanonicalizationMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2006/12/xml-c14n11',\n },\n ],\n SignatureMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',\n },\n ],\n Reference: [\n {\n Id: 'id-doc-signed-data',\n Type: '',\n URI: '',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: docDigest }],\n },\n {\n Id: 'id-xades-signed-props',\n Type: 'http://uri.etsi.org/01903/v1.3.2#SignedProperties',\n URI: '#id-xades-signed-props',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: propsDigest }],\n },\n ],\n }\n\n // Serialize the SignedInfo exactly as it will be embedded (no reordering)\n const signedInfoRaw = JSON.stringify(signedInfo)\n\n try {\n const signer = crypto.createSign('RSA-SHA256')\n signer.update(signedInfoRaw, 'utf8')\n const signatureValue = signer.sign(privateKeyPem, 'base64')\n\n // Reuse the original object so ordering is preserved\n return { signedInfo, signatureValue }\n } catch (error) {\n throw new Error(\n `Signature generation failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Signs the minified document string using the provided private key PEM\n * Returns the signature as a base64 string\n * FIXED: Match PowerShell script exactly - first compute hash, then sign the hash\n */\nexport const signDocumentString = (\n documentString: string,\n privateKeyPem: string,\n): string => {\n // Create signer with RSA-SHA256 (matches PowerShell RSAPKCS1SignatureFormatter)\n const signer = crypto.createSign('RSA-SHA256')\n signer.update(documentString, 'utf8')\n return signer.sign(privateKeyPem, 'base64')\n}\n\n/**\n * Complete document generation with signatures\n * Follows the complete MyInvois JSON signature creation process (Steps 1-7)\n */\nexport const generateCompleteDocument = (\n invoices: AllDocumentsV1_1[],\n signingCredentials: SigningCredentials,\n): CompleteInvoice => {\n try {\n // Step 1: Generate clean document (done in calculateDocumentDigest)\n // Step 2: Calculate document digest\n const docDigest = calculateDocumentDigest(invoices)\n\n // Get the minified, cleaned JSON string for signing\n const documentString = transformDocumentForHashing(invoices)\n\n // Step 3: Sign the minified document string (not the digest)\n const docSignature = signDocumentString(\n documentString,\n signingCredentials.privateKeyPem,\n )\n\n // Generate signing time in proper ISO format matching PowerShell exactly\n // PowerShell: Get-Date -Format \"yyyy-MM-ddTHH:mm:ssZ\"\n const now = new Date()\n const signingTime =\n now.getFullYear() +\n '-' +\n String(now.getMonth() + 1).padStart(2, '0') +\n '-' +\n String(now.getDate()).padStart(2, '0') +\n 'T' +\n String(now.getHours()).padStart(2, '0') +\n ':' +\n String(now.getMinutes()).padStart(2, '0') +\n ':' +\n String(now.getSeconds()).padStart(2, '0') +\n 'Z'\n\n // Extract certificate information (enhanced)\n const certInfo = extractCertificateInfo(signingCredentials.certificatePem)\n\n // Step 4: Calculate certificate digest\n const certificateDigest = calculateCertificateDigest(\n signingCredentials.certificatePem,\n )\n\n // Step 5: Create SignedProperties using extracted cert info\n const signedProperties = createSignedProperties(\n certificateDigest,\n signingTime,\n certInfo.issuerName,\n certInfo.serialNumber,\n )\n\n // Step 6: Calculate SignedProperties digest using the dedicated function\n const propsDigest = calculateSignedPropertiesDigest(signedProperties)\n\n // Create simple SignedInfo structure (matching PowerShell approach)\n const signedInfo: SignedInfoObject = {\n CanonicalizationMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2006/12/xml-c14n11',\n },\n ],\n SignatureMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',\n },\n ],\n Reference: [\n {\n Id: 'id-doc-signed-data',\n Type: '',\n URI: '',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: docDigest }],\n },\n {\n Id: 'id-xades-signed-props',\n Type: 'http://uri.etsi.org/01903/v1.3.2#SignedProperties',\n URI: '#id-xades-signed-props',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: propsDigest }],\n },\n ],\n }\n\n // Extract certificate content using raw data (like PowerShell $cert.RawData)\n const cert = new X509Certificate(signingCredentials.certificatePem)\n const certificate = cert.raw.toString('base64')\n\n // Step 7: Create final signed document\n const signedInvoices = invoices.map(invoice => {\n const cleanInvoice = generateCleanInvoiceObject(invoice)\n\n return {\n ...cleanInvoice,\n\n // Add UBLExtensions with complete signature structure\n UBLExtensions: [\n {\n UBLExtension: [\n {\n ExtensionURI: [\n {\n _: 'urn:oasis:names:specification:ubl:dsig:enveloped:xades',\n },\n ],\n ExtensionContent: [\n {\n UBLDocumentSignatures: [\n {\n SignatureInformation: [\n {\n ID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:1',\n },\n ],\n ReferencedSignatureID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:Invoice',\n },\n ],\n Signature: [\n {\n Id: 'signature',\n Object: [\n {\n QualifyingProperties: [\n {\n Target: 'signature',\n SignedProperties:\n signedProperties.SignedProperties,\n },\n ],\n },\n ],\n KeyInfo: [\n {\n X509Data: [\n {\n X509Certificate: [{ _: certificate }],\n X509SubjectName: [\n { _: certInfo.subjectName },\n ],\n X509IssuerSerial: [\n {\n X509IssuerName: [\n {\n _: certInfo.issuerName,\n },\n ],\n X509SerialNumber: [\n {\n _: certInfo.serialNumber,\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n SignatureValue: [{ _: docSignature }],\n SignedInfo: [signedInfo],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n\n // Add simple Signature reference\n Signature: [\n {\n ID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:Invoice',\n },\n ],\n SignatureMethod: [\n {\n _: 'urn:oasis:names:specification:ubl:dsig:enveloped:xades',\n },\n ],\n },\n ],\n }\n })\n\n return {\n _D: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',\n _A: 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',\n _B: 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',\n Invoice: signedInvoices,\n }\n } catch (error) {\n throw new Error(\n `Document generation failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Creates a line item with percentage-based taxation (e.g., SST, GST)\n */\nexport const createPercentageTaxLineItem = (params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxRate: number\n totalTaxableAmountPerLine?: number\n discountAmount?: number\n discountRate?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity\n ? params.quantity <= 0\n ? 1\n : (params.quantity ?? 1)\n : 1\n // Compute pre-discount from unit price and quantity only to avoid double-discounting\n const preDiscountAmount = params.unitPrice * quantity\n const hasDiscount =\n params.discountAmount !== undefined || params.discountRate !== undefined\n const computedDiscountByRate =\n hasDiscount && params.discountRate !== undefined\n ? preDiscountAmount * params.discountRate\n : 0\n const discountAmount =\n hasDiscount && params.discountAmount !== undefined\n ? params.discountAmount\n : computedDiscountByRate\n const totalTaxableAmount = Math.max(\n 0,\n preDiscountAmount - (hasDiscount ? discountAmount : 0),\n )\n const taxAmount = (totalTaxableAmount * params.taxRate) / 100\n\n return {\n itemClassificationCode: params.itemClassificationCode,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType,\n taxRate: params.taxRate,\n ...(hasDiscount && discountAmount !== undefined ? { discountAmount } : {}),\n ...(hasDiscount && params.discountRate !== undefined\n ? { discountRate: params.discountRate }\n : {}),\n taxAmount: Math.round(taxAmount * 100) / 100, // Round to 2 decimal places\n totalTaxableAmountPerLine: totalTaxableAmount,\n totalAmountPerLine: totalTaxableAmount + taxAmount,\n }\n}\n\n/**\n * Creates a line item with fixed rate taxation (e.g., Tourism Tax)\n */\nexport const createFixedRateTaxLineItem = (params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: UnitTypeCode\n totalTaxableAmountPerLine?: number\n discountAmount?: number\n discountRate?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n // Compute pre-discount from unit price and quantity only to avoid double-discounting\n const preDiscountAmount = params.unitPrice * quantity\n const hasDiscount =\n params.discountAmount !== undefined || params.discountRate !== undefined\n const computedDiscountByRate =\n hasDiscount && params.discountRate !== undefined\n ? preDiscountAmount * params.discountRate\n : 0\n const discountAmount =\n hasDiscount && params.discountAmount !== undefined\n ? params.discountAmount\n : computedDiscountByRate\n const totalTaxableAmount = Math.max(\n 0,\n preDiscountAmount - (hasDiscount ? discountAmount : 0),\n )\n const taxAmount = params.taxPerUnitAmount * params.baseUnitMeasure\n\n return {\n itemClassificationCode: params.itemClassificationCode,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType,\n taxPerUnitAmount: params.taxPerUnitAmount,\n baseUnitMeasure: params.baseUnitMeasure,\n baseUnitMeasureCode: params.baseUnitMeasureCode,\n ...(hasDiscount && discountAmount !== undefined ? { discountAmount } : {}),\n ...(hasDiscount && params.discountRate !== undefined\n ? { discountRate: params.discountRate }\n : {}),\n taxAmount: Math.round(taxAmount * 100) / 100, // Round to 2 decimal places\n totalTaxableAmountPerLine: totalTaxableAmount,\n totalAmountPerLine: totalTaxableAmount + taxAmount,\n }\n}\n\n/**\n * Calculates invoice totals from line items\n */\nexport const calculateInvoiceTotals = (\n lineItems: InvoiceLineItem[],\n payableRoundingAmount: number = 0,\n): {\n legalMonetaryTotal: {\n taxExclusiveAmount: number\n taxInclusiveAmount: number\n payableRoundingAmount: number\n payableAmount: number\n }\n taxTotal: {\n taxAmount: number\n }\n} => {\n const taxExclusiveAmount = lineItems.reduce(\n (sum, item) => sum + item.totalTaxableAmountPerLine,\n 0,\n )\n const totalTaxAmount = lineItems.reduce(\n (sum, item) => sum + item.taxAmount,\n 0,\n )\n const taxInclusiveAmount = taxExclusiveAmount + totalTaxAmount\n const payableAmount = taxInclusiveAmount + payableRoundingAmount\n\n return {\n legalMonetaryTotal: {\n taxExclusiveAmount: Math.round(taxExclusiveAmount * 100) / 100,\n taxInclusiveAmount: Math.round(taxInclusiveAmount * 100) / 100,\n payableRoundingAmount: Math.round(payableRoundingAmount * 100) / 100,\n payableAmount: Math.round(payableAmount * 100) / 100,\n },\n taxTotal: {\n taxAmount: Math.round(totalTaxAmount * 100) / 100,\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAyBA,MAAa,iBAAiB,CAACA,SAAmC;AAChE,QACE,KAAK,+BAAkC,KAAK;AAE/C;;;;AAKD,MAAa,kBAAkB,CAACA,SAAmC;AACjE,QAAO,KAAK,uBAA0B,eAAe,KAAK;AAC3D;;;;AAKD,MAAa,6BAA6B,CAACA,SAAkC;AAC3E,KAAI,eAAe,KAAK,CACtB,QAAO,KAAK,mBAAoB,KAAK;UAC5B,gBAAgB,KAAK,CAC9B,QAAQ,KAAK,4BAA4B,KAAK,UAAY;AAE5D,QAAO;AACR;;;;AAKD,MAAM,eAAe,CAACC,QAA6C;AACjE,KAAI,sBAAsB,IAAK,QAAO,IAAI;AAC1C,KAAI,yBAAyB,IAAK,QAAO,IAAI;AAC7C,KAAI,wBAAwB,IAAK,QAAO,IAAI;AAC5C,KAAI,yBAAyB,IAAK,QAAO,IAAI;AAC7C,KAAI,mCAAmC,IACrC,QAAO,IAAI;AACb,KAAI,mCAAmC,IACrC,QAAO,IAAI;AAEb,QAAO,CAAE;AACV;;;;AAKD,SAAgB,eA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IAAI,GAAG,IAC/C;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_document = require('./document-
|
|
1
|
+
const require_document = require('./document-DoQEvmcK.cjs');
|
|
2
2
|
|
|
3
3
|
//#region src/api/documentSubmission.ts
|
|
4
4
|
async function submitDocument(context, documents) {
|
|
@@ -148,4 +148,4 @@ Object.defineProperty(exports, 'submitDocument', {
|
|
|
148
148
|
return submitDocument;
|
|
149
149
|
}
|
|
150
150
|
});
|
|
151
|
-
//# sourceMappingURL=documentSubmission-
|
|
151
|
+
//# sourceMappingURL=documentSubmission-DUsjqWhR.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentSubmission-M4UlirJ7.cjs","names":["context: SubmissionContext","documents: AllDocumentsV1_1[]","context: Pick<SubmissionContext, 'fetch' | 'debug'>","submissionUid: string","pollInterval: number","maxRetries: number","pageNo: number","pageSize: number","context: Pick<SubmissionContext, 'fetch'>","documentUid: string","status: 'rejected' | 'cancelled'","reason: string"],"sources":["../src/api/documentSubmission.ts"],"sourcesContent":["import type {\n AllDocumentsV1_1,\n SubmissionResponse,\n SigningCredentials,\n SubmissionStatus,\n DocumentSummary,\n Fetch,\n StandardError,\n GetSubmissionResponse,\n} from '../types'\nimport { generateCompleteDocument } from '../utils/document'\n\ninterface SubmissionContext {\n fetch: Fetch\n debug: boolean\n signingCredentials: SigningCredentials\n}\n\nexport async function submitDocument(\n context: SubmissionContext,\n documents: AllDocumentsV1_1[],\n): Promise<{\n data: SubmissionResponse\n status: number\n}> {\n const { fetch, debug, signingCredentials } = context\n\n // 🔒 Hard enforcement of platform submission limits\n if (documents.length > 100) {\n throw new Error(\n 'Submission rejected: Cannot submit more than 100 documents at once',\n )\n }\n\n if (debug) {\n console.log(`📦 Preparing to submit ${documents.length} document(s)...`)\n }\n\n // For batch submission, each document must be signed and encoded separately\n // Build the submission payload according to MyInvois API format\n const crypto = await import('crypto')\n\n const submissionPayload = {\n documents: await Promise.all(\n documents.map(async doc => {\n // 1️⃣ Sign the single document (generateCompleteDocument expects an array)\n const signedDocument = generateCompleteDocument(\n [doc],\n signingCredentials,\n )\n\n // 2️⃣ Serialize\n const docJson = JSON.stringify(signedDocument)\n\n // 3️⃣ Hash\n const docHash = crypto\n .createHash('sha256')\n .update(docJson, 'utf8')\n .digest('hex')\n\n // 4️⃣ Base64 encode\n const docBase64 = Buffer.from(docJson, 'utf8').toString('base64')\n\n // 🚨 Enforce 300 KB per-document limit\n const rawSize = Buffer.byteLength(docBase64, 'base64')\n if (rawSize > 300 * 1024) {\n throw new Error(\n `Submission rejected: Document ${doc.eInvoiceCodeOrNumber} is ${rawSize} bytes – exceeds 300KB limit`,\n )\n }\n\n if (debug) {\n console.log('—'.repeat(60))\n console.log(`📄 Prepared document: ${doc.eInvoiceCodeOrNumber}`)\n console.log(` • JSON size : ${docJson.length} bytes`)\n console.log(` • Base64 size: ${docBase64.length} bytes`)\n }\n\n return {\n format: 'JSON',\n document: docBase64,\n documentHash: docHash,\n codeNumber: doc.eInvoiceCodeOrNumber,\n }\n }),\n ),\n }\n\n const payloadSize = Buffer.byteLength(JSON.stringify(submissionPayload))\n\n if (payloadSize > 5 * 1024 * 1024) {\n throw new Error(\n `Submission rejected: Payload is ${payloadSize} bytes – exceeds 5MB limit`,\n )\n }\n\n if (debug) {\n console.log('🚀 Submission payload structure:')\n console.log('- Format: JSON')\n console.log('- Documents count:', submissionPayload.documents.length)\n console.log('- Total payload size:', payloadSize, 'bytes')\n }\n\n // Submit to MyInvois API with proper headers\n const response = await fetch('/api/v1.0/documentsubmissions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(submissionPayload),\n })\n\n const responseData = (await response.json()) as SubmissionResponse\n\n if (debug) {\n console.log(`📡 API Response status: ${response.status}`)\n\n if (responseData.rejectedDocuments?.length > 0) {\n responseData.rejectedDocuments.forEach((doc, index) => {\n console.log(` Document ${index + 1}:`, doc.invoiceCodeNumber)\n if (doc.error) {\n console.log(` Error:`, doc.error.message)\n if (doc.error.details) {\n doc.error.details.forEach((detail, detailIndex) => {\n console.log(` Detail ${detailIndex + 1}:`, detail.message)\n })\n }\n }\n })\n }\n }\n\n const data = responseData as SubmissionResponse\n\n if (debug) {\n if (response.status !== 202) {\n console.error('❌ Submission failed with status:', response.status)\n console.error('❌ Response data:', JSON.stringify(data, null, 2))\n } else {\n console.log('✅ Submission successful!')\n console.log(`📋 Submission UID: ${data.submissionUid}`)\n console.log(\n `✅ Accepted documents: ${data.acceptedDocuments?.length || 0}`,\n )\n console.log(\n `❌ Rejected documents: ${data.rejectedDocuments?.length || 0}`,\n )\n }\n }\n\n return {\n data,\n status: response.status,\n }\n}\n\nexport async function getSubmissionStatus(\n context: Pick<SubmissionContext, 'fetch' | 'debug'>,\n submissionUid: string,\n pollInterval: number = 1000,\n maxRetries: number = 10,\n pageNo: number = 0,\n pageSize: number = 10,\n): Promise<{\n status: SubmissionStatus\n documentSummary?: DocumentSummary[]\n error?: {\n code: string\n message: string | null\n target: string\n details: {\n code: string\n message: string\n target: string\n }[]\n }\n}> {\n const { fetch, debug } = context\n\n try {\n const response = await fetch(\n `/api/v1.0/documentsubmissions/${submissionUid}?pageNo=${pageNo}&pageSize=${pageSize}`,\n )\n\n const data = (await response.json()) as GetSubmissionResponse\n\n if (debug) {\n console.log('Submission:', data)\n if (data.error) {\n console.log('Submission error details:', data.error.details)\n }\n }\n\n // If we have a successful response and status is completed, return success\n if (data.overallStatus === 'Valid') {\n return {\n status: data.overallStatus,\n documentSummary: data.documentSummary,\n }\n }\n if (data.overallStatus === 'Invalid') {\n return {\n status: 'Invalid',\n documentSummary: data.documentSummary,\n }\n }\n\n // If we have retries left, continue polling for any non-completed status or errors\n if (maxRetries > 0) {\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n return await getSubmissionStatus(\n context,\n submissionUid,\n pollInterval,\n maxRetries - 1,\n )\n }\n\n return {\n status: data.overallStatus || 'TimedOut',\n documentSummary: data.documentSummary,\n error:\n data.error ??\n ({\n code: 'Timeout',\n message: 'Submission timed out',\n target: 'submission',\n details: [],\n } satisfies StandardError),\n }\n } catch (error) {\n // Handle any request errors by retrying if we have retries left\n if (maxRetries > 0) {\n if (debug) {\n console.log('Request error, retrying...', error)\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n return await getSubmissionStatus(\n context,\n submissionUid,\n pollInterval,\n maxRetries - 1,\n )\n }\n\n // No retries left - return timeout\n return {\n status: 'TimedOut',\n documentSummary: [],\n error: {\n code: 'Timeout',\n message: 'Submission timed out after request errors',\n target: 'submission',\n details: [],\n },\n }\n }\n}\n\nexport async function performDocumentAction(\n context: Pick<SubmissionContext, 'fetch'>,\n documentUid: string,\n status: 'rejected' | 'cancelled',\n reason: string,\n): Promise<{\n uuid: string\n status: string\n error: StandardError\n}> {\n const { fetch } = context\n const response = await fetch(\n `/api/v1.0/documents/state/${documentUid}/state`,\n {\n method: 'POST',\n body: JSON.stringify({\n status,\n reason,\n }),\n },\n )\n\n const data = (await response.json()) as {\n uuid: string\n status: string\n error: StandardError\n }\n\n return data\n}\n"],"mappings":";;;AAkBA,eAAsB,eACpBA,SACAC,WAIC;CACD,MAAM,EAAE,OAAO,OAAO,oBAAoB,GAAG;AAG7C,KAAI,UAAU,SAAS,IACrB,OAAM,IAAI,MACR;AAIJ,KAAI,MACF,SAAQ,KAAK,yBAAyB,UAAU,OAAO,iBAAiB;CAK1E,MAAM,SAAS,MAAM,OAAO;CAE5B,MAAM,oBAAoB,EACxB,WAAW,MAAM,QAAQ,IACvB,UAAU,IAAI,OAAM,QAAO;EAEzB,MAAM,iBAAiB,0CACrB,CAAC,GAAI,GACL,mBACD;EAGD,MAAM,UAAU,KAAK,UAAU,eAAe;EAG9C,MAAM,UAAU,OACb,WAAW,SAAS,CACpB,OAAO,SAAS,OAAO,CACvB,OAAO,MAAM;EAGhB,MAAM,YAAY,OAAO,KAAK,SAAS,OAAO,CAAC,SAAS,SAAS;EAGjE,MAA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SACJ;IACC,MAAM;IACN,SAAS;IACT,QAAQ;IACR,SAAS,CAAE;GACZ;EACJ;CACF,SAAQ,OAAO;AAEd,MAAI,aAAa,GAAG;AAClB,OAAI,MACF,SAAQ,IAAI,8BAA8B,MAAM;AAElD,SAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,aAAa;AAC9D,UAAO,MAAM,oBACX,SACA,eACA,cACA,aAAa,EACd;EACF;AAGD,SAAO;GACL,QAAQ;GACR,iBAAiB,CAAE;GACnB,OAAO;IACL,MAAM;IACN,SAAS;IACT,QAAQ;IACR,SAAS,CAAE;GACZ;EACF;CACF;AACF;AAED,eAAsB,sBACpBC,SACAC,aACAC,QACAC,QAKC;CACD,MAAM,EAAE,OAAO,GAAG;CAClB,MAAM,WAAW,MAAM,OACpB,4BAA4B,YAAY,SACzC;EACE,QAAQ;EACR,MAAM,KAAK,UAAU;GACnB;GACA;EACD,EAAC;CACH,EACF;CAED,MAAM,OAAQ,MAAM,SAAS,MAAM;AAMnC,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"documentSubmission-DUsjqWhR.cjs","names":["context: SubmissionContext","documents: AllDocumentsV1_1[]","context: Pick<SubmissionContext, 'fetch' | 'debug'>","submissionUid: string","pollInterval: number","maxRetries: number","pageNo: number","pageSize: number","context: Pick<SubmissionContext, 'fetch'>","documentUid: string","status: 'rejected' | 'cancelled'","reason: string"],"sources":["../src/api/documentSubmission.ts"],"sourcesContent":["import type {\n AllDocumentsV1_1,\n SubmissionResponse,\n SigningCredentials,\n SubmissionStatus,\n DocumentSummary,\n Fetch,\n StandardError,\n GetSubmissionResponse,\n} from '../types'\nimport { generateCompleteDocument } from '../utils/document'\n\ninterface SubmissionContext {\n fetch: Fetch\n debug: boolean\n signingCredentials: SigningCredentials\n}\n\nexport async function submitDocument(\n context: SubmissionContext,\n documents: AllDocumentsV1_1[],\n): Promise<{\n data: SubmissionResponse\n status: number\n}> {\n const { fetch, debug, signingCredentials } = context\n\n // 🔒 Hard enforcement of platform submission limits\n if (documents.length > 100) {\n throw new Error(\n 'Submission rejected: Cannot submit more than 100 documents at once',\n )\n }\n\n if (debug) {\n console.log(`📦 Preparing to submit ${documents.length} document(s)...`)\n }\n\n // For batch submission, each document must be signed and encoded separately\n // Build the submission payload according to MyInvois API format\n const crypto = await import('crypto')\n\n const submissionPayload = {\n documents: await Promise.all(\n documents.map(async doc => {\n // 1️⃣ Sign the single document (generateCompleteDocument expects an array)\n const signedDocument = generateCompleteDocument(\n [doc],\n signingCredentials,\n )\n\n // 2️⃣ Serialize\n const docJson = JSON.stringify(signedDocument)\n\n // 3️⃣ Hash\n const docHash = crypto\n .createHash('sha256')\n .update(docJson, 'utf8')\n .digest('hex')\n\n // 4️⃣ Base64 encode\n const docBase64 = Buffer.from(docJson, 'utf8').toString('base64')\n\n // 🚨 Enforce 300 KB per-document limit\n const rawSize = Buffer.byteLength(docBase64, 'base64')\n if (rawSize > 300 * 1024) {\n throw new Error(\n `Submission rejected: Document ${doc.eInvoiceCodeOrNumber} is ${rawSize} bytes – exceeds 300KB limit`,\n )\n }\n\n if (debug) {\n console.log('—'.repeat(60))\n console.log(`📄 Prepared document: ${doc.eInvoiceCodeOrNumber}`)\n console.log(` • JSON size : ${docJson.length} bytes`)\n console.log(` • Base64 size: ${docBase64.length} bytes`)\n }\n\n return {\n format: 'JSON',\n document: docBase64,\n documentHash: docHash,\n codeNumber: doc.eInvoiceCodeOrNumber,\n }\n }),\n ),\n }\n\n const payloadSize = Buffer.byteLength(JSON.stringify(submissionPayload))\n\n if (payloadSize > 5 * 1024 * 1024) {\n throw new Error(\n `Submission rejected: Payload is ${payloadSize} bytes – exceeds 5MB limit`,\n )\n }\n\n if (debug) {\n console.log('🚀 Submission payload structure:')\n console.log('- Format: JSON')\n console.log('- Documents count:', submissionPayload.documents.length)\n console.log('- Total payload size:', payloadSize, 'bytes')\n }\n\n // Submit to MyInvois API with proper headers\n const response = await fetch('/api/v1.0/documentsubmissions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(submissionPayload),\n })\n\n const responseData = (await response.json()) as SubmissionResponse\n\n if (debug) {\n console.log(`📡 API Response status: ${response.status}`)\n\n if (responseData.rejectedDocuments?.length > 0) {\n responseData.rejectedDocuments.forEach((doc, index) => {\n console.log(` Document ${index + 1}:`, doc.invoiceCodeNumber)\n if (doc.error) {\n console.log(` Error:`, doc.error.message)\n if (doc.error.details) {\n doc.error.details.forEach((detail, detailIndex) => {\n console.log(` Detail ${detailIndex + 1}:`, detail.message)\n })\n }\n }\n })\n }\n }\n\n const data = responseData as SubmissionResponse\n\n if (debug) {\n if (response.status !== 202) {\n console.error('❌ Submission failed with status:', response.status)\n console.error('❌ Response data:', JSON.stringify(data, null, 2))\n } else {\n console.log('✅ Submission successful!')\n console.log(`📋 Submission UID: ${data.submissionUid}`)\n console.log(\n `✅ Accepted documents: ${data.acceptedDocuments?.length || 0}`,\n )\n console.log(\n `❌ Rejected documents: ${data.rejectedDocuments?.length || 0}`,\n )\n }\n }\n\n return {\n data,\n status: response.status,\n }\n}\n\nexport async function getSubmissionStatus(\n context: Pick<SubmissionContext, 'fetch' | 'debug'>,\n submissionUid: string,\n pollInterval: number = 1000,\n maxRetries: number = 10,\n pageNo: number = 0,\n pageSize: number = 10,\n): Promise<{\n status: SubmissionStatus\n documentSummary?: DocumentSummary[]\n error?: {\n code: string\n message: string | null\n target: string\n details: {\n code: string\n message: string\n target: string\n }[]\n }\n}> {\n const { fetch, debug } = context\n\n try {\n const response = await fetch(\n `/api/v1.0/documentsubmissions/${submissionUid}?pageNo=${pageNo}&pageSize=${pageSize}`,\n )\n\n const data = (await response.json()) as GetSubmissionResponse\n\n if (debug) {\n console.log('Submission:', data)\n if (data.error) {\n console.log('Submission error details:', data.error.details)\n }\n }\n\n // If we have a successful response and status is completed, return success\n if (data.overallStatus === 'Valid') {\n return {\n status: data.overallStatus,\n documentSummary: data.documentSummary,\n }\n }\n if (data.overallStatus === 'Invalid') {\n return {\n status: 'Invalid',\n documentSummary: data.documentSummary,\n }\n }\n\n // If we have retries left, continue polling for any non-completed status or errors\n if (maxRetries > 0) {\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n return await getSubmissionStatus(\n context,\n submissionUid,\n pollInterval,\n maxRetries - 1,\n )\n }\n\n return {\n status: data.overallStatus || 'TimedOut',\n documentSummary: data.documentSummary,\n error:\n data.error ??\n ({\n code: 'Timeout',\n message: 'Submission timed out',\n target: 'submission',\n details: [],\n } satisfies StandardError),\n }\n } catch (error) {\n // Handle any request errors by retrying if we have retries left\n if (maxRetries > 0) {\n if (debug) {\n console.log('Request error, retrying...', error)\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n return await getSubmissionStatus(\n context,\n submissionUid,\n pollInterval,\n maxRetries - 1,\n )\n }\n\n // No retries left - return timeout\n return {\n status: 'TimedOut',\n documentSummary: [],\n error: {\n code: 'Timeout',\n message: 'Submission timed out after request errors',\n target: 'submission',\n details: [],\n },\n }\n }\n}\n\nexport async function performDocumentAction(\n context: Pick<SubmissionContext, 'fetch'>,\n documentUid: string,\n status: 'rejected' | 'cancelled',\n reason: string,\n): Promise<{\n uuid: string\n status: string\n error: StandardError\n}> {\n const { fetch } = context\n const response = await fetch(\n `/api/v1.0/documents/state/${documentUid}/state`,\n {\n method: 'POST',\n body: JSON.stringify({\n status,\n reason,\n }),\n },\n )\n\n const data = (await response.json()) as {\n uuid: string\n status: string\n error: StandardError\n }\n\n return data\n}\n"],"mappings":";;;AAkBA,eAAsB,eACpBA,SACAC,WAIC;CACD,MAAM,EAAE,OAAO,OAAO,oBAAoB,GAAG;AAG7C,KAAI,UAAU,SAAS,IACrB,OAAM,IAAI,MACR;AAIJ,KAAI,MACF,SAAQ,KAAK,yBAAyB,UAAU,OAAO,iBAAiB;CAK1E,MAAM,SAAS,MAAM,OAAO;CAE5B,MAAM,oBAAoB,EACxB,WAAW,MAAM,QAAQ,IACvB,UAAU,IAAI,OAAM,QAAO;EAEzB,MAAM,iB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AAiB,KAAK;EACvB;AAIH,MAAI,aAAa,GAAG;AAClB,SAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,aAAa;AAC9D,UAAO,MAAM,oBACX,SACA,eACA,cACA,aAAa,EACd;EACF;AAED,SAAO;GACL,QAAQ,KAAK,iBAAiB;GAC9B,iBAAiB,KAAK;GACtB,OACE,KAAK,SACJ;IACC,MAAM;IACN,SAAS;IACT,QAAQ;IACR,SAAS,CAAE;GACZ;EACJ;CACF,SAAQ,OAAO;AAEd,MAAI,aAAa,GAAG;AAClB,OAAI,MACF,SAAQ,IAAI,8BAA8B,MAAM;AAElD,SAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,aAAa;AAC9D,UAAO,MAAM,oBACX,SACA,eACA,cACA,aAAa,EACd;EACF;AAGD,SAAO;GACL,QAAQ;GACR,iBAAiB,CAAE;GACnB,OAAO;IACL,MAAM;IACN,SAAS;IACT,QAAQ;IACR,SAAS,CAAE;GACZ;EACF;CACF;AACF;AAED,eAAsB,sBACpBC,SACAC,aACAC,QACAC,QAKC;CACD,MAAM,EAAE,OAAO,GAAG;CAClB,MAAM,WAAW,MAAM,OACpB,4BAA4B,YAAY,SACzC;EACE,QAAQ;EACR,MAAM,KAAK,UAAU;GACnB;GACA;EACD,EAAC;CACH,EACF;CAED,MAAM,OAAQ,MAAM,SAAS,MAAM;AAMnC,QAAO;AACR"}
|
|
@@ -211,6 +211,8 @@ interface LegalMonetaryTotal {
|
|
|
211
211
|
taxExclusiveAmount: number;
|
|
212
212
|
/** Total amount inclusive of taxes. Max 18 digits, 2 decimal places. */
|
|
213
213
|
taxInclusiveAmount: number;
|
|
214
|
+
/** Rounding amount applied to the payable amount. Max 18 digits, 2 decimal places. */
|
|
215
|
+
payableRoundingAmount: number;
|
|
214
216
|
/** The final payable amount. Max 18 digits, 2 decimal places. */
|
|
215
217
|
payableAmount: number;
|
|
216
218
|
}
|
|
@@ -726,6 +728,10 @@ interface InvoiceSubmission {
|
|
|
726
728
|
_: number;
|
|
727
729
|
currencyID: string;
|
|
728
730
|
}[];
|
|
731
|
+
PayableRoundingAmount: {
|
|
732
|
+
_: number;
|
|
733
|
+
currencyID: string;
|
|
734
|
+
}[];
|
|
729
735
|
PayableAmount: {
|
|
730
736
|
_: number;
|
|
731
737
|
currencyID: string;
|
|
@@ -1172,4 +1178,4 @@ interface DocumentTypeVersionResponse {
|
|
|
1172
1178
|
}
|
|
1173
1179
|
//#endregion
|
|
1174
1180
|
export { Address, AllDocumentsV1_1, Buyer, CompleteInvoice, CreditNoteV1_1, DebitNoteV1_1, DocumentStatus, DocumentSummary, DocumentTypeResponse, DocumentTypeVersion, DocumentTypeVersionResponse, DocumentTypesResponse, DocumentValidationResult, DocumentValidationStepResult, FinalDocumentData, GetSubmissionResponse, InvoiceLineItem, InvoiceSubmission, InvoiceV1_1, LegalMonetaryTotal, RefundNoteV1_1, RegistrationType, ResponseDocument, SelfBilledCreditNoteV1_1, SelfBilledInvoiceV1_1, SelfBilledRefundNoteV1_1, SignedInfoObject, SignedInvoiceSubmission, SignedPropertiesData, SignedPropertiesObject, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus, Supplier, TaxCategory, TaxSubtotal, TaxTotal, UBLDocument, WorkflowParameter };
|
|
1175
|
-
//# sourceMappingURL=documents-
|
|
1181
|
+
//# sourceMappingURL=documents-BECak3KN.d.cts.map
|
|
@@ -211,6 +211,8 @@ interface LegalMonetaryTotal {
|
|
|
211
211
|
taxExclusiveAmount: number;
|
|
212
212
|
/** Total amount inclusive of taxes. Max 18 digits, 2 decimal places. */
|
|
213
213
|
taxInclusiveAmount: number;
|
|
214
|
+
/** Rounding amount applied to the payable amount. Max 18 digits, 2 decimal places. */
|
|
215
|
+
payableRoundingAmount: number;
|
|
214
216
|
/** The final payable amount. Max 18 digits, 2 decimal places. */
|
|
215
217
|
payableAmount: number;
|
|
216
218
|
}
|
|
@@ -726,6 +728,10 @@ interface InvoiceSubmission {
|
|
|
726
728
|
_: number;
|
|
727
729
|
currencyID: string;
|
|
728
730
|
}[];
|
|
731
|
+
PayableRoundingAmount: {
|
|
732
|
+
_: number;
|
|
733
|
+
currencyID: string;
|
|
734
|
+
}[];
|
|
729
735
|
PayableAmount: {
|
|
730
736
|
_: number;
|
|
731
737
|
currencyID: string;
|
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const require_documentManagement = require('./documentManagement-CyPwiyP4.cjs');
|
|
2
2
|
require('./formatIdValue-i67o4kyD.cjs');
|
|
3
|
-
require('./document-
|
|
4
|
-
const require_documentSubmission = require('./documentSubmission-
|
|
3
|
+
require('./document-DoQEvmcK.cjs');
|
|
4
|
+
const require_documentSubmission = require('./documentSubmission-DUsjqWhR.cjs');
|
|
5
5
|
const require_documentTypeManagement = require('./documentTypeManagement-D_-LiQVg.cjs');
|
|
6
6
|
const require_notificationManagement = require('./notificationManagement-DLBDn77E.cjs');
|
|
7
7
|
const require_platformLogin = require('./platformLogin-Ch6hFKoU.cjs');
|
package/dist/index.d.ts
CHANGED
|
@@ -51,11 +51,11 @@ import "./YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "./ZX-CDQOfsHh.js";
|
|
52
52
|
import "./XX-DOA-10JW.js";
|
|
53
53
|
import { UnitType, UnitTypeCode } from "./unit-types-VgYXIwTT.js";
|
|
54
|
-
import { Address, AllDocumentsV1_1, Buyer, CompleteInvoice, CreditNoteV1_1, DebitNoteV1_1, DocumentStatus, DocumentSummary, DocumentTypeResponse, DocumentTypeVersion, DocumentTypeVersionResponse, DocumentTypesResponse, DocumentValidationResult, DocumentValidationStepResult, FinalDocumentData, GetSubmissionResponse, InvoiceLineItem, InvoiceSubmission, InvoiceV1_1, LegalMonetaryTotal, RefundNoteV1_1, RegistrationType, ResponseDocument, SelfBilledCreditNoteV1_1, SelfBilledInvoiceV1_1, SelfBilledRefundNoteV1_1, SignedInfoObject, SignedInvoiceSubmission, SignedPropertiesData, SignedPropertiesObject, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus, Supplier, TaxCategory, TaxSubtotal, TaxTotal, UBLDocument, WorkflowParameter } from "./documents-
|
|
54
|
+
import { Address, AllDocumentsV1_1, Buyer, CompleteInvoice, CreditNoteV1_1, DebitNoteV1_1, DocumentStatus, DocumentSummary, DocumentTypeResponse, DocumentTypeVersion, DocumentTypeVersionResponse, DocumentTypesResponse, DocumentValidationResult, DocumentValidationStepResult, FinalDocumentData, GetSubmissionResponse, InvoiceLineItem, InvoiceSubmission, InvoiceV1_1, LegalMonetaryTotal, RefundNoteV1_1, RegistrationType, ResponseDocument, SelfBilledCreditNoteV1_1, SelfBilledInvoiceV1_1, SelfBilledRefundNoteV1_1, SignedInfoObject, SignedInvoiceSubmission, SignedPropertiesData, SignedPropertiesObject, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus, Supplier, TaxCategory, TaxSubtotal, TaxTotal, UBLDocument, WorkflowParameter } from "./documents-Dp19RgNX.js";
|
|
55
55
|
import { PaymentMode, PaymentModeCode, PaymentModeCodeEnum } from "./payment-modes-g3DzLmWb.js";
|
|
56
56
|
import { CanonicalizationMethod, Cert, CertDigest, DigestMethod, IssuerDigitalSignature, IssuerSerial, KeyInfo, QualifyingProperties, Reference, SignatureMethod, SignedInfo, SignedProperties, SignedSignatureProperties, SigningCertificate, Transform, X509Data } from "./signatures-CerHUrj3.js";
|
|
57
57
|
import { Notification, NotificationDeliveryAttempt, NotificationMetadata, NotificationResponse, NotificationSearchParams, NotificationStatus, NotificationStatusEnum, NotificationType, NotificationTypeEnum } from "./notifications-sFhgh3rJ.js";
|
|
58
|
-
import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "./taxpayer-
|
|
58
|
+
import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "./taxpayer-BdvCGHHC.js";
|
|
59
59
|
import { Fetch } from "./utils-C4FoVKLq.js";
|
|
60
60
|
import { ClientCredentials, TokenResponse } from "./index-CygwSf0x.js";
|
|
61
61
|
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { getDocument, getDocumentDetails, searchDocuments } from "./documentManagement-CeNbp3qm.js";
|
|
2
2
|
import "./formatIdValue-qTxJqj9o.js";
|
|
3
|
-
import "./document-
|
|
4
|
-
import { getSubmissionStatus, performDocumentAction, submitDocument } from "./documentSubmission-
|
|
3
|
+
import "./document-D4O7JY0G.js";
|
|
4
|
+
import { getSubmissionStatus, performDocumentAction, submitDocument } from "./documentSubmission-uJ7yPWub.js";
|
|
5
5
|
import { getDocumentType, getDocumentTypeVersion, getDocumentTypes } from "./documentTypeManagement-cBtVCOY3.js";
|
|
6
6
|
import { getNotifications } from "./notificationManagement-n4Z5e-My.js";
|
|
7
7
|
import { platformLogin } from "./platformLogin-CqI9OLYP.js";
|
package/dist/index18.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
require('./formatIdValue-i67o4kyD.cjs');
|
|
2
|
-
require('./document-
|
|
3
|
-
const require_documentSubmission = require('./documentSubmission-
|
|
2
|
+
require('./document-DoQEvmcK.cjs');
|
|
3
|
+
const require_documentSubmission = require('./documentSubmission-DUsjqWhR.cjs');
|
|
4
4
|
|
|
5
5
|
exports.getSubmissionStatus = require_documentSubmission.getSubmissionStatus;
|
|
6
6
|
exports.performDocumentAction = require_documentSubmission.performDocumentAction;
|
package/dist/index33.cjs
CHANGED
|
@@ -1,18 +1,5 @@
|
|
|
1
|
+
const require_apiQueue = require('./apiQueue-DgKWaQDS.cjs');
|
|
1
2
|
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
*/
|
|
6
|
-
let UnitTypeCodeEnum_1X = /* @__PURE__ */ function(UnitTypeCodeEnum_1X$1) {
|
|
7
|
-
UnitTypeCodeEnum_1X$1["Group"] = "10";
|
|
8
|
-
UnitTypeCodeEnum_1X$1["Outfit"] = "11";
|
|
9
|
-
UnitTypeCodeEnum_1X$1["Ration"] = "13";
|
|
10
|
-
UnitTypeCodeEnum_1X$1["Shot"] = "14";
|
|
11
|
-
UnitTypeCodeEnum_1X$1["StickMilitary"] = "15";
|
|
12
|
-
UnitTypeCodeEnum_1X$1["FixedRate"] = "1I";
|
|
13
|
-
return UnitTypeCodeEnum_1X$1;
|
|
14
|
-
}({});
|
|
15
|
-
|
|
16
|
-
//#endregion
|
|
17
|
-
exports.UnitTypeCodeEnum_1X = UnitTypeCodeEnum_1X;
|
|
18
|
-
//# sourceMappingURL=index33.cjs.map
|
|
3
|
+
exports.categorizeRequest = require_apiQueue.categorizeRequest;
|
|
4
|
+
exports.clearQueue = require_apiQueue.clearQueue;
|
|
5
|
+
exports.queueRequest = require_apiQueue.queueRequest;
|
package/dist/index34.cjs
CHANGED
|
@@ -1,38 +1,13 @@
|
|
|
1
1
|
|
|
2
|
-
//#region src/
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
UnitTypeCodeEnum_2X$1["DecilitrePerGram"] = "22";
|
|
10
|
-
UnitTypeCodeEnum_2X$1["GramPerCubicCentimetre"] = "23";
|
|
11
|
-
UnitTypeCodeEnum_2X$1["TheoreticalPound"] = "24";
|
|
12
|
-
UnitTypeCodeEnum_2X$1["GramPerSquareCentimetre"] = "25";
|
|
13
|
-
UnitTypeCodeEnum_2X$1["TheoreticalTon"] = "27";
|
|
14
|
-
UnitTypeCodeEnum_2X$1["KilogramPerSquareMetre"] = "28";
|
|
15
|
-
UnitTypeCodeEnum_2X$1["RadianPerSecond"] = "2A";
|
|
16
|
-
UnitTypeCodeEnum_2X$1["RadianPerSecondSquared"] = "2B";
|
|
17
|
-
UnitTypeCodeEnum_2X$1["Roentgen"] = "2C";
|
|
18
|
-
UnitTypeCodeEnum_2X$1["VoltAC"] = "2G";
|
|
19
|
-
UnitTypeCodeEnum_2X$1["VoltDC"] = "2H";
|
|
20
|
-
UnitTypeCodeEnum_2X$1["BritishThermalUnitInternationalTablePerHour"] = "2I";
|
|
21
|
-
UnitTypeCodeEnum_2X$1["CubicCentimetrePerSecond"] = "2J";
|
|
22
|
-
UnitTypeCodeEnum_2X$1["CubicFootPerHour"] = "2K";
|
|
23
|
-
UnitTypeCodeEnum_2X$1["CubicFootPerMinute"] = "2L";
|
|
24
|
-
UnitTypeCodeEnum_2X$1["CentimetrePerSecond"] = "2M";
|
|
25
|
-
UnitTypeCodeEnum_2X$1["Decibel"] = "2N";
|
|
26
|
-
UnitTypeCodeEnum_2X$1["Kilobyte"] = "2P";
|
|
27
|
-
UnitTypeCodeEnum_2X$1["Kilobecquerel"] = "2Q";
|
|
28
|
-
UnitTypeCodeEnum_2X$1["Kilocurie"] = "2R";
|
|
29
|
-
UnitTypeCodeEnum_2X$1["Megagram"] = "2U";
|
|
30
|
-
UnitTypeCodeEnum_2X$1["MetrePerMinute"] = "2X";
|
|
31
|
-
UnitTypeCodeEnum_2X$1["Milliroentgen"] = "2Y";
|
|
32
|
-
UnitTypeCodeEnum_2X$1["Millivolt"] = "2Z";
|
|
33
|
-
return UnitTypeCodeEnum_2X$1;
|
|
34
|
-
}({});
|
|
2
|
+
//#region src/utils/base64.ts
|
|
3
|
+
function encodeToBase64(content) {
|
|
4
|
+
return Buffer.from(content).toString("base64");
|
|
5
|
+
}
|
|
6
|
+
function decodeFromBase64(content) {
|
|
7
|
+
return Buffer.from(content, "base64").toString("utf-8");
|
|
8
|
+
}
|
|
35
9
|
|
|
36
10
|
//#endregion
|
|
37
|
-
exports.
|
|
11
|
+
exports.decodeFromBase64 = decodeFromBase64;
|
|
12
|
+
exports.encodeToBase64 = encodeToBase64;
|
|
38
13
|
//# sourceMappingURL=index34.cjs.map
|
package/dist/index34.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index34.cjs","names":[],"sources":["../src/
|
|
1
|
+
{"version":3,"file":"index34.cjs","names":["content: string"],"sources":["../src/utils/base64.ts"],"sourcesContent":["export function encodeToBase64(content: string): string {\n return Buffer.from(content).toString('base64')\n}\n\nexport function decodeFromBase64(content: string): string {\n return Buffer.from(content, 'base64').toString('utf-8')\n}\n"],"mappings":";;AAAA,SAAgB,eAAeA,SAAyB;AACtD,QAAO,OAAO,KAAK,QAAQ,CAAC,SAAS,SAAS;AAC/C;AAED,SAAgB,iBAAiBA,SAAyB;AACxD,QAAO,OAAO,KAAK,SAAS,SAAS,CAAC,SAAS,QAAQ;AACxD"}
|
package/dist/index35.cjs
CHANGED
|
@@ -1,19 +1,5 @@
|
|
|
1
|
+
const require_certificate = require('./certificate-CWmfCPdt.cjs');
|
|
1
2
|
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
*/
|
|
6
|
-
let UnitTypeCodeEnum_3X = /* @__PURE__ */ function(UnitTypeCodeEnum_3X$1) {
|
|
7
|
-
UnitTypeCodeEnum_3X$1["KilopascalSquareMetrePerGram"] = "33";
|
|
8
|
-
UnitTypeCodeEnum_3X$1["KilopascalPerMillimetre"] = "34";
|
|
9
|
-
UnitTypeCodeEnum_3X$1["MillilitrePerSquareCentimetreSecond"] = "35";
|
|
10
|
-
UnitTypeCodeEnum_3X$1["OuncePerSquareFoot"] = "37";
|
|
11
|
-
UnitTypeCodeEnum_3X$1["OuncePerSquareFootPer0_01inch"] = "38";
|
|
12
|
-
UnitTypeCodeEnum_3X$1["Megajoule"] = "3B";
|
|
13
|
-
UnitTypeCodeEnum_3X$1["Manmonth"] = "3C";
|
|
14
|
-
return UnitTypeCodeEnum_3X$1;
|
|
15
|
-
}({});
|
|
16
|
-
|
|
17
|
-
//#endregion
|
|
18
|
-
exports.UnitTypeCodeEnum_3X = UnitTypeCodeEnum_3X;
|
|
19
|
-
//# sourceMappingURL=index35.cjs.map
|
|
3
|
+
exports.extractCertificateInfo = require_certificate.extractCertificateInfo;
|
|
4
|
+
exports.getPemFromP12 = require_certificate.getPemFromP12;
|
|
5
|
+
exports.validateKeyPair = require_certificate.validateKeyPair;
|