@devly-cl/sii-client 0.6.0 → 0.7.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +113 -251
- package/dist/application/document-status.d.ts +13 -0
- package/dist/application/document-status.js +50 -0
- package/dist/application/invoice-queries.d.ts +11 -5
- package/dist/application/invoice-queries.js +13 -9
- package/dist/domain/company-info.d.ts +13 -0
- package/dist/domain/company-info.js +2 -0
- package/dist/domain/document-status.d.ts +93 -0
- package/dist/domain/document-status.js +69 -0
- package/dist/domain/document.d.ts +4 -0
- package/dist/domain/document.js +38 -3
- package/dist/domain/dte-reconciliation.d.ts +5 -0
- package/dist/domain/dte-reconciliation.js +351 -0
- package/dist/domain/invoice-xml.d.ts +133 -1
- package/dist/domain/invoicing.d.ts +78 -5
- package/dist/domain/invoicing.js +143 -26
- package/dist/domain/rcv-document.d.ts +17 -0
- package/dist/domain/rcv-document.js +2 -0
- package/dist/index.d.ts +9 -4
- package/dist/index.js +5 -1
- package/dist/infrastructure/document-status-gateway.d.ts +13 -0
- package/dist/infrastructure/document-status-gateway.js +127 -0
- package/dist/infrastructure/document-status-parser.d.ts +12 -0
- package/dist/infrastructure/document-status-parser.js +258 -0
- package/dist/infrastructure/dte-xml.js +148 -30
- package/dist/infrastructure/facturador-gateway.d.ts +4 -1
- package/dist/infrastructure/facturador-gateway.js +113 -15
- package/dist/infrastructure/facturador.d.ts +4 -1
- package/dist/infrastructure/facturador.js +22 -4
- package/dist/infrastructure/rcv-gateway.d.ts +3 -0
- package/dist/infrastructure/rcv-gateway.js +9 -5
- package/dist/infrastructure/rcv-normalization.d.ts +7 -0
- package/dist/infrastructure/rcv-normalization.js +9 -1
- package/dist/infrastructure/sii-client.d.ts +10 -1
- package/dist/infrastructure/sii-client.js +29 -3
- package/dist/infrastructure/sii-http-session.d.ts +5 -1
- package/dist/infrastructure/sii-http-session.js +75 -27
- package/dist/sii-error.d.ts +4 -3
- package/dist/sii-error.js +11 -4
- package/package.json +45 -45
- package/dist/domain/sii-error.d.ts +0 -27
- package/dist/domain/sii-error.js +0 -82
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.normalizeIssuedInvoice = normalizeIssuedInvoice;
|
|
4
|
+
exports.normalizeIssuedDocument = normalizeIssuedDocument;
|
|
4
5
|
exports.normalizeReceivedInvoice = normalizeReceivedInvoice;
|
|
6
|
+
exports.normalizeReceivedDocument = normalizeReceivedDocument;
|
|
5
7
|
const rut_1 = require("../domain/rut");
|
|
6
8
|
function integer(value) {
|
|
7
9
|
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
|
|
@@ -25,6 +27,9 @@ function date(value) {
|
|
|
25
27
|
}
|
|
26
28
|
/** Campos del proveedor validados; emisor y periodo vienen de la consulta autorizada. */
|
|
27
29
|
function normalizeIssuedInvoice(row, issuerRut, period, type) {
|
|
30
|
+
return normalizeIssuedDocument(row, issuerRut, period, type);
|
|
31
|
+
}
|
|
32
|
+
function normalizeIssuedDocument(row, issuerRut, period, type) {
|
|
28
33
|
if (row.detTipoDoc !== type || integer(row.detNroDoc) === 0 || integer(row.detRutDoc) === 0 || typeof row.detDvDoc !== 'string' || !/^[\dKk]$/.test(row.detDvDoc)) {
|
|
29
34
|
throw new TypeError('SII_INVALID_RESPONSE');
|
|
30
35
|
}
|
|
@@ -47,9 +52,12 @@ function normalizeIssuedInvoice(row, issuerRut, period, type) {
|
|
|
47
52
|
}
|
|
48
53
|
/** In purchases detRutDoc identifies the supplier; the authorized company is the receiver. */
|
|
49
54
|
function normalizeReceivedInvoice(row, receiverRut, period, type) {
|
|
55
|
+
return normalizeReceivedDocument(row, receiverRut, period, type);
|
|
56
|
+
}
|
|
57
|
+
function normalizeReceivedDocument(row, receiverRut, period, type) {
|
|
50
58
|
// getDetalleCompra returns detTipoDoc:null for the requested type (observed in RCV).
|
|
51
59
|
if (row.detTipoDoc != null && row.detTipoDoc !== type)
|
|
52
60
|
throw new TypeError('SII_INVALID_RESPONSE');
|
|
53
|
-
const invoice =
|
|
61
|
+
const invoice = normalizeIssuedDocument({ ...row, detTipoDoc: type }, receiverRut, period, type);
|
|
54
62
|
return { ...invoice, issuerRut: invoice.receiverRut, issuerName: invoice.receiverName, receiverRut, receiverName: null };
|
|
55
63
|
}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { type PreparedDocument, type SentDocument } from '../domain/document';
|
|
2
|
+
import { type DocumentStatusQuery, type DocumentStatusResult, type RecipientEventsQuery, type RecipientEventsResult, type DocumentQueryOptions } from '../domain/document-status';
|
|
2
3
|
import type { InvoiceInput } from '../domain/invoicing';
|
|
4
|
+
import type { CompanyInfo } from '../domain/company-info';
|
|
3
5
|
import type { IssuedInvoicesQuery, IssuedInvoicesResult } from '../domain/issued-invoice';
|
|
4
6
|
import type { ReceivedInvoicesQuery, ReceivedInvoicesResult } from '../domain/received-invoice';
|
|
5
|
-
import type {
|
|
7
|
+
import type { RcvDocumentsQuery, RcvDocumentsResult } from '../domain/rcv-document';
|
|
8
|
+
import type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentXmlQuery, ReceivedDocumentXmlQuery, IssuedDocumentXmlResult } from '../domain/invoice-xml';
|
|
6
9
|
import type { AuthorizedCompany, SummaryQuery, SiiResponse, SiiClientOptions, SiiCredentials, SiiSession, IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from '../contracts';
|
|
7
10
|
import { type SignDocumentInput } from '../application/issuance';
|
|
8
11
|
export { SiiError } from '../sii-error';
|
|
@@ -15,14 +18,20 @@ export declare class SiiClient {
|
|
|
15
18
|
constructor(options: SiiClientOptions);
|
|
16
19
|
login(credentials: SiiCredentials): Promise<SiiSession>;
|
|
17
20
|
getAuthorizedCompanies(): Promise<SiiResponse<AuthorizedCompany>>;
|
|
21
|
+
getCompanyInfo(rut: string): Promise<CompanyInfo>;
|
|
18
22
|
getSummary(input: SummaryQuery): Promise<SiiResponse>;
|
|
19
23
|
getIssuedInvoices(input: IssuedInvoicesQuery): Promise<IssuedInvoicesResult>;
|
|
20
24
|
getReceivedInvoices(input: ReceivedInvoicesQuery): Promise<ReceivedInvoicesResult>;
|
|
25
|
+
getIssuedDocuments(input: RcvDocumentsQuery): Promise<RcvDocumentsResult>;
|
|
26
|
+
getReceivedDocuments(input: RcvDocumentsQuery): Promise<RcvDocumentsResult>;
|
|
21
27
|
getIssuedInvoiceXml(input: IssuedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
|
|
22
28
|
getReceivedInvoiceXml(input: ReceivedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
|
|
23
29
|
getIssuedDocumentXml(input: IssuedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
|
|
30
|
+
getReceivedDocumentXml(input: ReceivedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
|
|
24
31
|
getIssuedInvoicePdf(input: IssuedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
|
|
25
32
|
getReceivedInvoicePdf(input: ReceivedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
|
|
33
|
+
getDocumentStatus(input: DocumentStatusQuery, options?: DocumentQueryOptions): Promise<DocumentStatusResult>;
|
|
34
|
+
getDocumentRecipientEvents(input: RecipientEventsQuery, options?: DocumentQueryOptions): Promise<RecipientEventsResult>;
|
|
26
35
|
prepareInvoice(input: InvoiceInput): Promise<PreparedDocument>;
|
|
27
36
|
prepareCancellationCreditNote(input: {
|
|
28
37
|
factura: IssuedInvoiceXmlQuery;
|
|
@@ -3,10 +3,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.SiiClient = exports.SiiError = void 0;
|
|
4
4
|
const sii_error_1 = require("../sii-error");
|
|
5
5
|
const document_1 = require("../domain/document");
|
|
6
|
+
const document_status_1 = require("../domain/document-status");
|
|
6
7
|
const issuance_1 = require("../application/issuance");
|
|
8
|
+
const document_status_2 = require("../application/document-status");
|
|
7
9
|
const sii_http_session_1 = require("./sii-http-session");
|
|
8
10
|
const rcv_gateway_1 = require("./rcv-gateway");
|
|
9
11
|
const facturador_gateway_1 = require("./facturador-gateway");
|
|
12
|
+
const document_status_gateway_1 = require("./document-status-gateway");
|
|
10
13
|
var sii_error_2 = require("../sii-error");
|
|
11
14
|
Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_error_2.SiiError; } });
|
|
12
15
|
/** One company and personal session; composition and compatibility stay at this boundary. */
|
|
@@ -15,28 +18,49 @@ class SiiClient {
|
|
|
15
18
|
#rcv;
|
|
16
19
|
#facturador;
|
|
17
20
|
#issuance;
|
|
21
|
+
#documentQueries;
|
|
22
|
+
#companyLookup;
|
|
18
23
|
#disposal;
|
|
19
24
|
constructor(options) {
|
|
20
25
|
this.#session = new sii_http_session_1.SiiHttpSession(options);
|
|
21
26
|
this.#rcv = new rcv_gateway_1.RcvGateway(this.#session);
|
|
22
27
|
this.#facturador = new facturador_gateway_1.FacturadorGateway(this.#session, () => this.dispose());
|
|
23
28
|
this.#issuance = new issuance_1.DocumentIssuance(this.#facturador);
|
|
29
|
+
this.#documentQueries = new document_status_2.DocumentQueries(new document_status_gateway_1.DocumentStatusGateway(this.#session));
|
|
24
30
|
}
|
|
25
31
|
login(credentials) {
|
|
26
32
|
return this.#session.login(credentials, async (identity) => (await this.#rcv.companies(identity)).data.some(company => `${company.usrEmpRut}-${company.usrEmpDv}`.toUpperCase() === this.#session.company.formatted));
|
|
27
33
|
}
|
|
28
34
|
async getAuthorizedCompanies() { return this.#rcv.companies(); }
|
|
35
|
+
getCompanyInfo(rut) {
|
|
36
|
+
if (this.#companyLookup || this.#issuance.pendingWrite)
|
|
37
|
+
return Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS'));
|
|
38
|
+
const lookup = this.#facturador.companyInfo(rut).catch(error => {
|
|
39
|
+
if (error instanceof sii_error_1.SiiError && error.diagnostics?.endpoint === 'mipeGenFacEx.cgi') {
|
|
40
|
+
throw new sii_error_1.SiiError(error.diagnostics.reason === 'RESPONSE_TOO_LARGE' ? 'SII_PROTOCOL_CHANGED' : error.code, error.httpStatus, { ...error.diagnostics, stage: 'COMPANY_LOOKUP' });
|
|
41
|
+
}
|
|
42
|
+
throw error;
|
|
43
|
+
});
|
|
44
|
+
this.#companyLookup = lookup;
|
|
45
|
+
void lookup.then(() => { this.#companyLookup = undefined; }, () => { this.#companyLookup = undefined; });
|
|
46
|
+
return lookup;
|
|
47
|
+
}
|
|
29
48
|
getSummary(input) { return this.#rcv.summary(input); }
|
|
30
49
|
getIssuedInvoices(input) { return this.#rcv.issuedInvoices(input); }
|
|
31
50
|
getReceivedInvoices(input) { return this.#rcv.receivedInvoices(input); }
|
|
51
|
+
getIssuedDocuments(input) { return this.#rcv.issuedDocuments(input); }
|
|
52
|
+
getReceivedDocuments(input) { return this.#rcv.receivedDocuments(input); }
|
|
32
53
|
getIssuedInvoiceXml(input) { return this.#facturador.issuedInvoiceXml(input); }
|
|
33
54
|
getReceivedInvoiceXml(input) { return this.#facturador.receivedInvoiceXml(input); }
|
|
34
55
|
getIssuedDocumentXml(input) { return this.#facturador.issuedDocumentXml(input); }
|
|
56
|
+
getReceivedDocumentXml(input) { return this.#facturador.receivedDocumentXml(input); }
|
|
35
57
|
getIssuedInvoicePdf(input, options) { return this.#facturador.issuedInvoicePdf(input, options); }
|
|
36
58
|
getReceivedInvoicePdf(input, options) { return this.#facturador.receivedInvoicePdf(input, options); }
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
59
|
+
getDocumentStatus(input, options) { return this.#translate(this.#documentQueries.getDocumentStatus(input, options)); }
|
|
60
|
+
getDocumentRecipientEvents(input, options) { return this.#translate(this.#documentQueries.getDocumentRecipientEvents(input, options)); }
|
|
61
|
+
prepareInvoice(input) { return this.#companyLookup ? Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS')) : this.#translate(this.#issuance.prepareInvoice(input)); }
|
|
62
|
+
prepareCancellationCreditNote(input) { return this.#companyLookup ? Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS')) : this.#translate(this.#issuance.prepareCancellationCreditNote(input)); }
|
|
63
|
+
signAndSend(input) { return this.#companyLookup ? Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS')) : this.#translate(this.#issuance.signAndSend(input)); }
|
|
40
64
|
dispose() {
|
|
41
65
|
if (!this.#disposal) {
|
|
42
66
|
this.#issuance.clearPreparation();
|
|
@@ -50,6 +74,8 @@ class SiiClient {
|
|
|
50
74
|
throw new sii_error_1.SiiError(error.code);
|
|
51
75
|
if (error instanceof document_1.DocumentContentMismatchError)
|
|
52
76
|
throw this.#session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
77
|
+
if (error instanceof document_status_1.DocumentQueryError)
|
|
78
|
+
throw this.#session.failure(error.code, 'validarAccesoReceptor', error.code === 'SII_DOCUMENT_IDENTITY_MISMATCH' ? 'DOCUMENT_IDENTITY_MISMATCH' : 'DOCUMENT_ACCESS_DENIED');
|
|
53
79
|
throw error;
|
|
54
80
|
});
|
|
55
81
|
}
|
|
@@ -3,6 +3,10 @@ import { SiiError, type SiiDiagnostics } from '../sii-error';
|
|
|
3
3
|
import type { SiiClientOptions, SiiCredentials, SiiSession, InvoicePdfResult } from '../contracts';
|
|
4
4
|
export declare const RCV = "https://www4.sii.cl/consdcvinternetui/";
|
|
5
5
|
export declare const FACTURADOR = "https://www1.sii.cl/cgi-bin/Portal001/";
|
|
6
|
+
export declare const DOCUMENT_STATUS_FORM = "https://palena.sii.cl/cgi_dte/UPL/DTEauth?6";
|
|
7
|
+
export declare const DOCUMENT_STATUS_URL = "https://palena.sii.cl/cgi_dte/UPL/QEstadoDTE";
|
|
8
|
+
export declare const RECIPIENT_EVENTS_PORTAL = "https://www4.sii.cl/registrorechazodtej6ui/";
|
|
9
|
+
export declare const RECIPIENT_EVENTS_URL = "https://www4.sii.cl/registrorechazodtej6ui/services/data/facadeService/validarAccesoReceptor";
|
|
6
10
|
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
7
11
|
/** Owns one personal HTTP session; body consumption belongs to the tracked request. */
|
|
8
12
|
export declare class SiiHttpSession {
|
|
@@ -17,7 +21,7 @@ export declare class SiiHttpSession {
|
|
|
17
21
|
/** Track the whole PDF operation, including an unconsumed stream, until its resources close. */
|
|
18
22
|
pdfOperation(endpoint: SiiDiagnostics['endpoint'], operation: (signal: AbortSignal, trackStream: (stream: InvoicePdfResult['stream']) => void) => Promise<InvoicePdfResult>, signal?: AbortSignal): Promise<InvoicePdfResult>;
|
|
19
23
|
request<T>(url: string, consume: (response: Response) => Promise<T>, options?: RequestInit, canRetry?: boolean, allowRedirect?: boolean): Promise<T>;
|
|
20
|
-
json(response: Response, endpoint: SiiDiagnostics['endpoint']): Promise<unknown>;
|
|
24
|
+
json(response: Response, endpoint: SiiDiagnostics['endpoint'], signal?: AbortSignal): Promise<unknown>;
|
|
21
25
|
readBounded(response: Response, endpoint: SiiDiagnostics['endpoint'], limit?: number, oversizedCode?: string, signal?: AbortSignal): Promise<Uint8Array>;
|
|
22
26
|
dispose(pendingWrite?: Promise<unknown>): Promise<void>;
|
|
23
27
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SiiHttpSession = exports.FACTURADOR = exports.RCV = void 0;
|
|
3
|
+
exports.SiiHttpSession = exports.RECIPIENT_EVENTS_URL = exports.RECIPIENT_EVENTS_PORTAL = exports.DOCUMENT_STATUS_URL = exports.DOCUMENT_STATUS_FORM = exports.FACTURADOR = exports.RCV = void 0;
|
|
4
4
|
exports.isRecord = isRecord;
|
|
5
5
|
exports.endpointFor = endpointFor;
|
|
6
6
|
exports.responseFormat = responseFormat;
|
|
@@ -13,6 +13,10 @@ const invoice_xml_1 = require("../domain/invoice-xml");
|
|
|
13
13
|
const sii_error_1 = require("../sii-error");
|
|
14
14
|
exports.RCV = 'https://www4.sii.cl/consdcvinternetui/';
|
|
15
15
|
exports.FACTURADOR = 'https://www1.sii.cl/cgi-bin/Portal001/';
|
|
16
|
+
exports.DOCUMENT_STATUS_FORM = 'https://palena.sii.cl/cgi_dte/UPL/DTEauth?6';
|
|
17
|
+
exports.DOCUMENT_STATUS_URL = 'https://palena.sii.cl/cgi_dte/UPL/QEstadoDTE';
|
|
18
|
+
exports.RECIPIENT_EVENTS_PORTAL = 'https://www4.sii.cl/registrorechazodtej6ui/';
|
|
19
|
+
exports.RECIPIENT_EVENTS_URL = `${exports.RECIPIENT_EVENTS_PORTAL}services/data/facadeService/validarAccesoReceptor`;
|
|
16
20
|
const AUTH = 'https://zeusr.sii.cl/cgi_AUT2000/CAutInicio.cgi';
|
|
17
21
|
const LOGOUT = 'https://zeusr.sii.cl/cgi_AUT2000/autTermino.cgi';
|
|
18
22
|
const SESSION = 'https://www4.sii.cl/common-1.0/services/aaSessionService/load';
|
|
@@ -59,10 +63,22 @@ class SiiHttpSession {
|
|
|
59
63
|
const body = new URLSearchParams({ rut: identity.rut, dv: identity.dv, referencia: exports.RCV, '411': '', rutcntr: identity.formatted, clave });
|
|
60
64
|
await this.request(AUTH, async (response) => {
|
|
61
65
|
await response.body?.cancel();
|
|
66
|
+
const redirected = response.status >= 300 && response.status < 400;
|
|
67
|
+
if (redirected) {
|
|
68
|
+
try {
|
|
69
|
+
const location = response.headers.get('location');
|
|
70
|
+
const target = new URL(location ?? '', AUTH);
|
|
71
|
+
if (!location || target.protocol !== 'https:' || !(target.hostname === 'sii.cl' || target.hostname.endsWith('.sii.cl')) || target.username || target.password || target.port)
|
|
72
|
+
throw new Error();
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
throw this.failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', 'CAutInicio.cgi', 'SESSION_REQUIRED', response);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
62
78
|
const cookies = await this.cookies(exports.RCV);
|
|
63
79
|
if (!cookies.some(c => c.key === 'TOKEN' && c.value))
|
|
64
|
-
throw this.failure('LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', 'LOGIN_NOT_CONFIRMED', response);
|
|
65
|
-
}, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: 'https://zeusr.sii.cl', Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${exports.RCV}` }, body: body.toString() });
|
|
80
|
+
throw this.failure(redirected ? 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' : 'LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', redirected ? 'SESSION_REQUIRED' : 'LOGIN_NOT_CONFIRMED', response);
|
|
81
|
+
}, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: 'https://zeusr.sii.cl', Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${exports.RCV}` }, body: body.toString() }, false, true);
|
|
66
82
|
await this.request(SESSION, async (response) => {
|
|
67
83
|
const sessionEnvelope = await this.json(response, 'aaSessionService/load');
|
|
68
84
|
const session = isRecord(sessionEnvelope) && isRecord(sessionEnvelope.data) ? sessionEnvelope.data : undefined;
|
|
@@ -80,7 +96,8 @@ class SiiHttpSession {
|
|
|
80
96
|
return { usuarioRut: identity.formatted, empresaRut: this.company.formatted, representacion: false };
|
|
81
97
|
}
|
|
82
98
|
catch (error) {
|
|
83
|
-
|
|
99
|
+
// Preserve authentication failure; callers still observe cleanup failure through dispose().
|
|
100
|
+
await this.dispose().catch(() => { });
|
|
84
101
|
throw error;
|
|
85
102
|
}
|
|
86
103
|
}
|
|
@@ -92,7 +109,7 @@ class SiiHttpSession {
|
|
|
92
109
|
cookies(url) { return this.#jar.getCookies(url); }
|
|
93
110
|
failure(code, endpoint, reason, response, extra = {}) {
|
|
94
111
|
return new sii_error_1.SiiError(code, response?.status, { traceId: this.#traceId, stage: ENDPOINT_STAGES[endpoint], endpoint, reason,
|
|
95
|
-
...(response ? { httpStatus: response.status, ...responseFormat(response) } : {}), ...extra });
|
|
112
|
+
...(response ? { httpStatus: response.status, ...responseFormat(response), retryAfterMs: retryAfterMs(response) } : {}), ...extra });
|
|
96
113
|
}
|
|
97
114
|
abortFailure(signal, endpoint) {
|
|
98
115
|
return signal.reason instanceof sii_error_1.SiiError ? signal.reason : this.failure('SII_OPERATION_ABORTED', endpoint, 'OPERATION_ABORTED');
|
|
@@ -169,12 +186,12 @@ class SiiHttpSession {
|
|
|
169
186
|
void request.then(() => this.#requests.delete(request), () => this.#requests.delete(request));
|
|
170
187
|
return request;
|
|
171
188
|
}
|
|
172
|
-
async json(response, endpoint) {
|
|
189
|
+
async json(response, endpoint, signal) {
|
|
173
190
|
if (!response.headers.get('content-type')?.toLowerCase().includes('json')) {
|
|
174
191
|
await response.body?.cancel();
|
|
175
192
|
throw this.failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpoint, 'SESSION_REQUIRED', response);
|
|
176
193
|
}
|
|
177
|
-
const bytes = response.body ? await this.readBounded(response, endpoint, MAX_JSON_BYTES, 'SII_PROTOCOL_CHANGED') : new Uint8Array();
|
|
194
|
+
const bytes = response.body ? await this.readBounded(response, endpoint, MAX_JSON_BYTES, 'SII_PROTOCOL_CHANGED', signal) : new Uint8Array();
|
|
178
195
|
try {
|
|
179
196
|
return JSON.parse(new TextDecoder().decode(bytes));
|
|
180
197
|
}
|
|
@@ -211,7 +228,7 @@ class SiiHttpSession {
|
|
|
211
228
|
return Buffer.concat(chunks, size);
|
|
212
229
|
}
|
|
213
230
|
catch (error) {
|
|
214
|
-
throw signal?.aborted ? this.abortFailure(signal, endpoint) : error instanceof sii_error_1.SiiError ? error : this.failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response);
|
|
231
|
+
throw signal?.aborted ? this.abortFailure(signal, endpoint) : error instanceof sii_error_1.SiiError ? error : this.failure('SII_TRANSPORT_ERROR', endpoint, error instanceof Error && error.name === 'TimeoutError' ? 'TIMEOUT' : 'TRANSPORT_ERROR', response);
|
|
215
232
|
}
|
|
216
233
|
finally {
|
|
217
234
|
signal?.removeEventListener('abort', onAbort);
|
|
@@ -236,21 +253,36 @@ class SiiHttpSession {
|
|
|
236
253
|
if (!cookies.some(c => c.value && ['TOKEN', 'NETSCAPE_LIVEWIRE.mac'].includes(c.key)))
|
|
237
254
|
return;
|
|
238
255
|
const headers = new Headers({ Referer: exports.RCV, Cookie: cookies.map(c => c.cookieString()).join('; ') });
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
256
|
+
for (let attempt = 1;; attempt++) {
|
|
257
|
+
try {
|
|
258
|
+
const response = await this.#fetch(LOGOUT, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
|
|
259
|
+
if (!response.ok) {
|
|
260
|
+
await response.body?.cancel();
|
|
261
|
+
if (!(response.status >= 300 && response.status < 400 && response.headers.get('location') === 'https://homer.sii.cl/'))
|
|
262
|
+
throw this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'HTTP_ERROR', response, { attempts: attempt });
|
|
263
|
+
}
|
|
264
|
+
else {
|
|
265
|
+
const page = Buffer.from(await this.readBounded(response, 'autTermino.cgi')).toString('latin1');
|
|
266
|
+
const codes = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/g);
|
|
267
|
+
if (codes?.some(code => code !== '01.01.205.529.269.28'))
|
|
268
|
+
throw this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'INVALID_RESPONSE', response, { attempts: attempt });
|
|
269
|
+
}
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
const failure = error instanceof sii_error_1.SiiError ? error : this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'TRANSPORT_ERROR', undefined, { attempts: attempt });
|
|
274
|
+
const waitMs = failure.diagnostics?.retryAfterMs ?? 500 * attempt;
|
|
275
|
+
const transient = failure.diagnostics?.reason === 'TRANSPORT_ERROR' || failure.diagnostics?.reason === 'TIMEOUT' || RETRYABLE.has(failure.httpStatus ?? 0);
|
|
276
|
+
if (!transient || attempt > this.#retries || waitMs > 5000)
|
|
277
|
+
throw failure;
|
|
278
|
+
await (0, promises_1.setTimeout)(waitMs);
|
|
279
|
+
}
|
|
250
280
|
}
|
|
251
281
|
}
|
|
252
|
-
catch {
|
|
253
|
-
|
|
282
|
+
catch (error) {
|
|
283
|
+
if (error instanceof sii_error_1.SiiError)
|
|
284
|
+
throw new sii_error_1.SiiError('SII_LOGOUT_FAILED', error.httpStatus, error.diagnostics);
|
|
285
|
+
throw this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'TRANSPORT_ERROR');
|
|
254
286
|
}
|
|
255
287
|
finally {
|
|
256
288
|
await this.#jar.removeAllCookies();
|
|
@@ -295,13 +327,11 @@ class SiiHttpSession {
|
|
|
295
327
|
throw this.abortFailure(options.signal, endpoint);
|
|
296
328
|
}
|
|
297
329
|
if (canRetry && RETRYABLE.has(response.status) && attempt < this.#retries) {
|
|
298
|
-
const
|
|
299
|
-
const seconds = retryAfter === null ? NaN : Number(retryAfter);
|
|
300
|
-
const waitMs = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : Date.parse(retryAfter ?? '') - Date.now();
|
|
330
|
+
const waitMs = retryAfterMs(response);
|
|
301
331
|
await response.body?.cancel();
|
|
302
|
-
if (
|
|
332
|
+
if (waitMs !== undefined && waitMs > 5000)
|
|
303
333
|
throw this.failure('SII_RETRY_LATER', endpoint, 'RETRY_LATER', response, { attempts: attempt + 1 });
|
|
304
|
-
await (0, promises_1.setTimeout)(
|
|
334
|
+
await (0, promises_1.setTimeout)(waitMs ?? 250 * (attempt + 1), undefined, { signal: options.signal ?? undefined });
|
|
305
335
|
continue;
|
|
306
336
|
}
|
|
307
337
|
if (!response.ok && !(allowRedirect && response.status >= 300 && response.status < 400)) {
|
|
@@ -314,15 +344,33 @@ class SiiHttpSession {
|
|
|
314
344
|
}
|
|
315
345
|
}
|
|
316
346
|
exports.SiiHttpSession = SiiHttpSession;
|
|
347
|
+
function retryAfterMs(response) {
|
|
348
|
+
const raw = response.headers.get('retry-after');
|
|
349
|
+
if (!raw?.trim())
|
|
350
|
+
return undefined;
|
|
351
|
+
const value = /^\d+(?:\.\d+)?$/.test(raw.trim()) ? Number(raw) * 1000 : Date.parse(raw) - Date.now();
|
|
352
|
+
return Number.isFinite(value) && value >= 0 ? Math.min(2_592_000_000, Math.ceil(value)) : undefined;
|
|
353
|
+
}
|
|
317
354
|
const ENDPOINT_STAGES = {
|
|
318
355
|
'CAutInicio.cgi': 'AUTHENTICATION', 'aaSessionService/load': 'SESSION_CHECK', getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
|
|
319
356
|
getDatosInicio: 'RCV_INITIALIZATION', getResumen: 'RCV_SUMMARY', getDetalleCompra: 'RCV_DETAIL', getDetalleVenta: 'RCV_DETAIL',
|
|
320
357
|
'mipeSelEmpresa.cgi': 'XML_COMPANY_SELECTION', 'mipeLaunchPage.cgi': 'XML_COMPANY_SELECTION', 'mipeDownLoad.cgi': 'XML_DOWNLOAD', 'autTermino.cgi': 'LOGOUT',
|
|
321
358
|
'mipeGenFacEx.cgi': 'DOCUMENT_PREPARATION', 'mipeDisplayPreView.cgi': 'DOCUMENT_REVIEW', 'mipeGenXMLFirma.cgi': 'DOCUMENT_SIGNING', 'getCertDigital.cgi': 'DOCUMENT_SIGNING', 'postFirmaDigital.cgi': 'DOCUMENT_SIGNING', 'mipeSendXML.cgi': 'DOCUMENT_SEND', 'mipeAdminDocsEmi.cgi': 'DOCUMENT_RECOVERY', 'mipeGesDocEmi.cgi': 'DOCUMENT_RECOVERY', 'mipeDisplayPDF.cgi': 'PDF_DOWNLOAD', 'mipeAdminDocsRcp.cgi': 'PDF_HISTORY', 'mipeShowPdf.cgi': 'PDF_DOWNLOAD',
|
|
359
|
+
DTEauth: 'DOCUMENT_STATUS', QEstadoDTE: 'DOCUMENT_STATUS', registrorechazodtej6ui: 'RECIPIENT_EVENTS', validarAccesoReceptor: 'RECIPIENT_EVENTS',
|
|
322
360
|
};
|
|
361
|
+
const DOCUMENT_ENDPOINTS = new Map([
|
|
362
|
+
[exports.DOCUMENT_STATUS_FORM, 'DTEauth'], [exports.DOCUMENT_STATUS_URL, 'QEstadoDTE'],
|
|
363
|
+
[exports.RECIPIENT_EVENTS_PORTAL, 'registrorechazodtej6ui'], [exports.RECIPIENT_EVENTS_URL, 'validarAccesoReceptor'],
|
|
364
|
+
]);
|
|
323
365
|
function endpointFor(url) {
|
|
324
|
-
const
|
|
366
|
+
const parsed = new URL(url);
|
|
367
|
+
const documentEndpoint = DOCUMENT_ENDPOINTS.get(parsed.href);
|
|
368
|
+
if (documentEndpoint)
|
|
369
|
+
return documentEndpoint;
|
|
370
|
+
const path = parsed.pathname;
|
|
325
371
|
const endpoint = path.endsWith('/aaSessionService/load') ? 'aaSessionService/load' : path.slice(path.lastIndexOf('/') + 1);
|
|
372
|
+
if (['DTEauth', 'QEstadoDTE', 'registrorechazodtej6ui', 'validarAccesoReceptor'].includes(endpoint))
|
|
373
|
+
throw new TypeError('Endpoint SII desconocido');
|
|
326
374
|
if (!Object.hasOwn(ENDPOINT_STAGES, endpoint))
|
|
327
375
|
throw new TypeError('Endpoint SII desconocido');
|
|
328
376
|
return endpoint;
|
package/dist/sii-error.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
declare const STAGES: readonly ["AUTHENTICATION", "SESSION_CHECK", "COMPANY_AUTHORIZATION", "RCV_INITIALIZATION", "RCV_SUMMARY", "RCV_DETAIL", "XML_COMPANY_SELECTION", "XML_DOWNLOAD", "XML_PARSE", "LOGOUT", "DOCUMENT_PREPARATION", "DOCUMENT_REVIEW", "DOCUMENT_SIGNING", "DOCUMENT_SEND", "DOCUMENT_RECOVERY", "PDF_HISTORY", "PDF_DOWNLOAD"];
|
|
2
|
-
declare const ENDPOINTS: readonly ["CAutInicio.cgi", "aaSessionService/load", "getDcvEmpresasAutorizadas", "getDatosInicio", "getResumen", "getDetalleCompra", "getDetalleVenta", "mipeSelEmpresa.cgi", "mipeLaunchPage.cgi", "mipeDownLoad.cgi", "autTermino.cgi", "mipeGenFacEx.cgi", "mipeDisplayPreView.cgi", "mipeGenXMLFirma.cgi", "getCertDigital.cgi", "postFirmaDigital.cgi", "mipeSendXML.cgi", "mipeAdminDocsEmi.cgi", "mipeGesDocEmi.cgi", "mipeDisplayPDF.cgi", "mipeAdminDocsRcp.cgi", "mipeShowPdf.cgi"];
|
|
3
|
-
declare const REASONS: readonly ["DOCUMENT_LIMIT_EXCEEDED", "DOCUMENT_NOT_FOUND", "EMPTY_RESPONSE", "HTML_RESPONSE", "PROVIDER_ERROR_PAGE", "UNEXPECTED_PDF", "UNEXPECTED_ARCHIVE", "UNEXPECTED_FORMAT", "INVALID_XML", "XML_IDENTITY_MISMATCH", "RESPONSE_TOO_LARGE", "HTTP_ERROR", "TIMEOUT", "TRANSPORT_ERROR", "RETRY_LATER", "CAPTCHA_REQUIRED", "SESSION_REQUIRED", "LOGIN_NOT_CONFIRMED", "PERSONAL_SESSION_REQUIRED", "SESSION_IDENTITY_MISMATCH", "COMPANY_NOT_AUTHORIZED", "COMPANY_SELECTION_REQUIRED", "PROVIDER_REJECTED", "INVALID_RESPONSE", "DOCUMENT_CONTENT_MISMATCH", "CERTIFICATE_UNAVAILABLE", "CERTIFICATE_PASSWORD_INVALID", "CERTIFICATE_EXPIRED", "CERTIFICATE_REVOKED", "SIGNATURE_INVALID", "ISSUANCE_OUTCOME_UNKNOWN", "INVALID_PDF", "PDF_IDENTITY_MISMATCH", "OPERATION_ABORTED"];
|
|
1
|
+
declare const STAGES: readonly ["AUTHENTICATION", "SESSION_CHECK", "COMPANY_AUTHORIZATION", "RCV_INITIALIZATION", "RCV_SUMMARY", "RCV_DETAIL", "XML_COMPANY_SELECTION", "XML_DOWNLOAD", "XML_PARSE", "LOGOUT", "DOCUMENT_PREPARATION", "DOCUMENT_REVIEW", "DOCUMENT_SIGNING", "DOCUMENT_SEND", "DOCUMENT_RECOVERY", "PDF_HISTORY", "PDF_DOWNLOAD", "DOCUMENT_STATUS", "RECIPIENT_EVENTS", "COMPANY_LOOKUP"];
|
|
2
|
+
declare const ENDPOINTS: readonly ["CAutInicio.cgi", "aaSessionService/load", "getDcvEmpresasAutorizadas", "getDatosInicio", "getResumen", "getDetalleCompra", "getDetalleVenta", "mipeSelEmpresa.cgi", "mipeLaunchPage.cgi", "mipeDownLoad.cgi", "autTermino.cgi", "mipeGenFacEx.cgi", "mipeDisplayPreView.cgi", "mipeGenXMLFirma.cgi", "getCertDigital.cgi", "postFirmaDigital.cgi", "mipeSendXML.cgi", "mipeAdminDocsEmi.cgi", "mipeGesDocEmi.cgi", "mipeDisplayPDF.cgi", "mipeAdminDocsRcp.cgi", "mipeShowPdf.cgi", "DTEauth", "QEstadoDTE", "registrorechazodtej6ui", "validarAccesoReceptor"];
|
|
3
|
+
declare const REASONS: readonly ["DOCUMENT_LIMIT_EXCEEDED", "DOCUMENT_NOT_FOUND", "EMPTY_RESPONSE", "HTML_RESPONSE", "PROVIDER_ERROR_PAGE", "UNEXPECTED_PDF", "UNEXPECTED_ARCHIVE", "UNEXPECTED_FORMAT", "INVALID_XML", "XML_IDENTITY_MISMATCH", "RESPONSE_TOO_LARGE", "HTTP_ERROR", "TIMEOUT", "TRANSPORT_ERROR", "RETRY_LATER", "CAPTCHA_REQUIRED", "SESSION_REQUIRED", "LOGIN_NOT_CONFIRMED", "PERSONAL_SESSION_REQUIRED", "SESSION_IDENTITY_MISMATCH", "COMPANY_NOT_AUTHORIZED", "COMPANY_SELECTION_REQUIRED", "PROVIDER_REJECTED", "INVALID_RESPONSE", "DOCUMENT_CONTENT_MISMATCH", "CERTIFICATE_UNAVAILABLE", "CERTIFICATE_PASSWORD_INVALID", "CERTIFICATE_EXPIRED", "CERTIFICATE_REVOKED", "SIGNATURE_INVALID", "ISSUANCE_OUTCOME_UNKNOWN", "INVALID_PDF", "PDF_IDENTITY_MISMATCH", "OPERATION_ABORTED", "DOCUMENT_IDENTITY_MISMATCH", "DOCUMENT_ACCESS_DENIED", "COMPANY_IDENTITY_MISMATCH", "COMPANY_INFO_UNAVAILABLE"];
|
|
4
4
|
declare const RESPONSE_TYPES: readonly ["XML", "HTML", "PDF", "ZIP", "JSON", "EMPTY", "UNKNOWN"];
|
|
5
5
|
declare const CONTENT_TYPES: readonly ["application/xml", "text/xml", "application/octet-stream", "text/html", "application/pdf", "application/zip", "application/json", "text/plain"];
|
|
6
6
|
export interface SiiDiagnostics {
|
|
@@ -14,6 +14,7 @@ export interface SiiDiagnostics {
|
|
|
14
14
|
readonly siiMessageCode?: string;
|
|
15
15
|
readonly siiResponseCode?: number;
|
|
16
16
|
readonly attempts?: number;
|
|
17
|
+
readonly retryAfterMs?: number;
|
|
17
18
|
}
|
|
18
19
|
/** Only bounded, known protocol values cross this boundary. Never provider text or URLs. */
|
|
19
20
|
export declare function sanitizeSiiDiagnostics(value: unknown): SiiDiagnostics | undefined;
|
package/dist/sii-error.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.SiiError = void 0;
|
|
4
4
|
exports.sanitizeSiiDiagnostics = sanitizeSiiDiagnostics;
|
|
5
|
-
const STAGES = ['AUTHENTICATION', 'SESSION_CHECK', 'COMPANY_AUTHORIZATION', 'RCV_INITIALIZATION', 'RCV_SUMMARY', 'RCV_DETAIL', 'XML_COMPANY_SELECTION', 'XML_DOWNLOAD', 'XML_PARSE', 'LOGOUT', 'DOCUMENT_PREPARATION', 'DOCUMENT_REVIEW', 'DOCUMENT_SIGNING', 'DOCUMENT_SEND', 'DOCUMENT_RECOVERY', 'PDF_HISTORY', 'PDF_DOWNLOAD'];
|
|
6
|
-
const ENDPOINTS = ['CAutInicio.cgi', 'aaSessionService/load', 'getDcvEmpresasAutorizadas', 'getDatosInicio', 'getResumen', 'getDetalleCompra', 'getDetalleVenta', 'mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeDownLoad.cgi', 'autTermino.cgi', 'mipeGenFacEx.cgi', 'mipeDisplayPreView.cgi', 'mipeGenXMLFirma.cgi', 'getCertDigital.cgi', 'postFirmaDigital.cgi', 'mipeSendXML.cgi', 'mipeAdminDocsEmi.cgi', 'mipeGesDocEmi.cgi', 'mipeDisplayPDF.cgi', 'mipeAdminDocsRcp.cgi', 'mipeShowPdf.cgi'];
|
|
7
|
-
const REASONS = ['DOCUMENT_LIMIT_EXCEEDED', 'DOCUMENT_NOT_FOUND', 'EMPTY_RESPONSE', 'HTML_RESPONSE', 'PROVIDER_ERROR_PAGE', 'UNEXPECTED_PDF', 'UNEXPECTED_ARCHIVE', 'UNEXPECTED_FORMAT', 'INVALID_XML', 'XML_IDENTITY_MISMATCH', 'RESPONSE_TOO_LARGE', 'HTTP_ERROR', 'TIMEOUT', 'TRANSPORT_ERROR', 'RETRY_LATER', 'CAPTCHA_REQUIRED', 'SESSION_REQUIRED', 'LOGIN_NOT_CONFIRMED', 'PERSONAL_SESSION_REQUIRED', 'SESSION_IDENTITY_MISMATCH', 'COMPANY_NOT_AUTHORIZED', 'COMPANY_SELECTION_REQUIRED', 'PROVIDER_REJECTED', 'INVALID_RESPONSE', 'DOCUMENT_CONTENT_MISMATCH', 'CERTIFICATE_UNAVAILABLE', 'CERTIFICATE_PASSWORD_INVALID', 'CERTIFICATE_EXPIRED', 'CERTIFICATE_REVOKED', 'SIGNATURE_INVALID', 'ISSUANCE_OUTCOME_UNKNOWN', 'INVALID_PDF', 'PDF_IDENTITY_MISMATCH', 'OPERATION_ABORTED'];
|
|
5
|
+
const STAGES = ['AUTHENTICATION', 'SESSION_CHECK', 'COMPANY_AUTHORIZATION', 'RCV_INITIALIZATION', 'RCV_SUMMARY', 'RCV_DETAIL', 'XML_COMPANY_SELECTION', 'XML_DOWNLOAD', 'XML_PARSE', 'LOGOUT', 'DOCUMENT_PREPARATION', 'DOCUMENT_REVIEW', 'DOCUMENT_SIGNING', 'DOCUMENT_SEND', 'DOCUMENT_RECOVERY', 'PDF_HISTORY', 'PDF_DOWNLOAD', 'DOCUMENT_STATUS', 'RECIPIENT_EVENTS', 'COMPANY_LOOKUP'];
|
|
6
|
+
const ENDPOINTS = ['CAutInicio.cgi', 'aaSessionService/load', 'getDcvEmpresasAutorizadas', 'getDatosInicio', 'getResumen', 'getDetalleCompra', 'getDetalleVenta', 'mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeDownLoad.cgi', 'autTermino.cgi', 'mipeGenFacEx.cgi', 'mipeDisplayPreView.cgi', 'mipeGenXMLFirma.cgi', 'getCertDigital.cgi', 'postFirmaDigital.cgi', 'mipeSendXML.cgi', 'mipeAdminDocsEmi.cgi', 'mipeGesDocEmi.cgi', 'mipeDisplayPDF.cgi', 'mipeAdminDocsRcp.cgi', 'mipeShowPdf.cgi', 'DTEauth', 'QEstadoDTE', 'registrorechazodtej6ui', 'validarAccesoReceptor'];
|
|
7
|
+
const REASONS = ['DOCUMENT_LIMIT_EXCEEDED', 'DOCUMENT_NOT_FOUND', 'EMPTY_RESPONSE', 'HTML_RESPONSE', 'PROVIDER_ERROR_PAGE', 'UNEXPECTED_PDF', 'UNEXPECTED_ARCHIVE', 'UNEXPECTED_FORMAT', 'INVALID_XML', 'XML_IDENTITY_MISMATCH', 'RESPONSE_TOO_LARGE', 'HTTP_ERROR', 'TIMEOUT', 'TRANSPORT_ERROR', 'RETRY_LATER', 'CAPTCHA_REQUIRED', 'SESSION_REQUIRED', 'LOGIN_NOT_CONFIRMED', 'PERSONAL_SESSION_REQUIRED', 'SESSION_IDENTITY_MISMATCH', 'COMPANY_NOT_AUTHORIZED', 'COMPANY_SELECTION_REQUIRED', 'PROVIDER_REJECTED', 'INVALID_RESPONSE', 'DOCUMENT_CONTENT_MISMATCH', 'CERTIFICATE_UNAVAILABLE', 'CERTIFICATE_PASSWORD_INVALID', 'CERTIFICATE_EXPIRED', 'CERTIFICATE_REVOKED', 'SIGNATURE_INVALID', 'ISSUANCE_OUTCOME_UNKNOWN', 'INVALID_PDF', 'PDF_IDENTITY_MISMATCH', 'OPERATION_ABORTED', 'DOCUMENT_IDENTITY_MISMATCH', 'DOCUMENT_ACCESS_DENIED', 'COMPANY_IDENTITY_MISMATCH', 'COMPANY_INFO_UNAVAILABLE'];
|
|
8
8
|
const RESPONSE_TYPES = ['XML', 'HTML', 'PDF', 'ZIP', 'JSON', 'EMPTY', 'UNKNOWN'];
|
|
9
9
|
const CONTENT_TYPES = ['application/xml', 'text/xml', 'application/octet-stream', 'text/html', 'application/pdf', 'application/zip', 'application/json', 'text/plain'];
|
|
10
10
|
function member(values, value) {
|
|
@@ -26,6 +26,7 @@ function sanitizeSiiDiagnostics(value) {
|
|
|
26
26
|
...(typeof raw.siiMessageCode === 'string' && /^\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}$/.test(raw.siiMessageCode) ? { siiMessageCode: raw.siiMessageCode } : {}),
|
|
27
27
|
...(typeof raw.siiResponseCode === 'number' && Number.isInteger(raw.siiResponseCode) && Math.abs(raw.siiResponseCode) <= 999999 ? { siiResponseCode: raw.siiResponseCode } : {}),
|
|
28
28
|
...(typeof raw.attempts === 'number' && Number.isInteger(raw.attempts) && raw.attempts >= 1 && raw.attempts <= 3 ? { attempts: raw.attempts } : {}),
|
|
29
|
+
...(typeof raw.retryAfterMs === 'number' && Number.isSafeInteger(raw.retryAfterMs) && raw.retryAfterMs >= 0 && raw.retryAfterMs <= 2_592_000_000 ? { retryAfterMs: raw.retryAfterMs } : {}),
|
|
29
30
|
});
|
|
30
31
|
}
|
|
31
32
|
const STAGE_LABELS = {
|
|
@@ -34,6 +35,8 @@ const STAGE_LABELS = {
|
|
|
34
35
|
XML_COMPANY_SELECTION: 'selección de empresa en el facturador', XML_DOWNLOAD: 'descarga del XML', XML_PARSE: 'validación del XML', LOGOUT: 'cierre de sesión',
|
|
35
36
|
DOCUMENT_PREPARATION: 'preparación del documento', DOCUMENT_REVIEW: 'revisión del documento', DOCUMENT_SIGNING: 'firma del documento', DOCUMENT_SEND: 'envío del documento', DOCUMENT_RECOVERY: 'recuperación del documento emitido',
|
|
36
37
|
PDF_HISTORY: 'búsqueda de factura en el historial', PDF_DOWNLOAD: 'descarga del PDF',
|
|
38
|
+
DOCUMENT_STATUS: 'consulta de recepción y contenido del DTE', RECIPIENT_EVENTS: 'consulta de eventos del DTE',
|
|
39
|
+
COMPANY_LOOKUP: 'consulta de datos de empresa por RUT',
|
|
37
40
|
};
|
|
38
41
|
const REASON_LABELS = {
|
|
39
42
|
DOCUMENT_LIMIT_EXCEEDED: 'SII rechazó la consulta porque devuelve demasiados documentos. No confirmó si el XML individual está disponible.',
|
|
@@ -48,7 +51,11 @@ const REASON_LABELS = {
|
|
|
48
51
|
XML_IDENTITY_MISMATCH: 'El XML recibido corresponde a otro documento y no se guardó.',
|
|
49
52
|
INVALID_PDF: 'SII no entregó una respuesta PDF válida para esta solicitud.',
|
|
50
53
|
PDF_IDENTITY_MISMATCH: 'El historial no identifica de forma única la factura solicitada. No se descargó el PDF.',
|
|
51
|
-
OPERATION_ABORTED: 'El consumidor canceló la
|
|
54
|
+
OPERATION_ABORTED: 'El consumidor canceló la operación.',
|
|
55
|
+
DOCUMENT_IDENTITY_MISMATCH: 'SII devolvió otra identidad documental; no se entregaron sus datos.',
|
|
56
|
+
DOCUMENT_ACCESS_DENIED: 'SII no confirmó el acceso al documento en el rol solicitado.',
|
|
57
|
+
COMPANY_IDENTITY_MISMATCH: 'SII devolvió datos de otro RUT; no se entregaron.',
|
|
58
|
+
COMPANY_INFO_UNAVAILABLE: 'SII no entregó datos utilizables para este RUT. No confirma inexistencia del contribuyente.',
|
|
52
59
|
RESPONSE_TOO_LARGE: 'La respuesta de SII supera el límite permitido para este tipo de respuesta y no se procesó.',
|
|
53
60
|
HTTP_ERROR: 'SII respondió con un error HTTP.', TIMEOUT: 'SII no respondió dentro del tiempo permitido.',
|
|
54
61
|
TRANSPORT_ERROR: 'No se pudo completar la comunicación con SII.', RETRY_LATER: 'SII pidió esperar antes de volver a consultar.',
|
package/package.json
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@devly-cl/sii-client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Cliente HTTP del SII para acceso personal, RCV, XML, PDF por streaming y emisión de facturas y notas de crédito, independiente de framework.",
|
|
5
|
-
"license": "UNLICENSED",
|
|
6
|
-
"type": "commonjs",
|
|
7
|
-
"engines": {
|
|
8
|
-
"node": ">=22.13.0"
|
|
9
|
-
},
|
|
10
|
-
"main": "./dist/index.js",
|
|
11
|
-
"types": "./dist/index.d.ts",
|
|
12
|
-
"exports": {
|
|
13
|
-
".": {
|
|
14
|
-
"types": "./dist/index.d.ts",
|
|
15
|
-
"require": "./dist/index.js",
|
|
16
|
-
"import": "./dist/index.js"
|
|
17
|
-
}
|
|
18
|
-
},
|
|
19
|
-
"files": [
|
|
20
|
-
"dist",
|
|
21
|
-
"README.md"
|
|
22
|
-
],
|
|
23
|
-
"publishConfig": {
|
|
24
|
-
"access": "public",
|
|
25
|
-
"registry": "https://registry.npmjs.org"
|
|
26
|
-
},
|
|
27
|
-
"scripts": {
|
|
28
|
-
"build": "tsc -p tsconfig.json",
|
|
29
|
-
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
30
|
-
"test": "npm run build && node test/check.mjs && node test/invoices.mjs && node test/xml.mjs && node test/logout.mjs && node test/credit-note-xml.mjs && node test/facturador.mjs && node test/invoicing.mjs && node test/issuance.mjs && node test/issuance-edges.mjs && node test/api-naming.mjs && node test/company-selection.mjs && node test/transport-lifecycle.mjs && node test/application.mjs && node test/architecture.mjs && node test/pdf.mjs && node test/pdf-http.mjs",
|
|
31
|
-
"check:example": "tsc --strict --noEmit --target ES2022 --module Node16 --moduleResolution Node16 --types node examples/consulta-rcv.ts examples/facturacion.ts examples/consulta-pdf.ts",
|
|
32
|
-
"check": "npm run typecheck && npm test && npm run check:example",
|
|
33
|
-
"test:live": "npm run build && node scripts/live-check.mjs",
|
|
34
|
-
"prepack": "npm run check"
|
|
35
|
-
},
|
|
36
|
-
"dependencies": {
|
|
37
|
-
"parse5": "7.3.0",
|
|
38
|
-
"saxes": "^6.0.0",
|
|
39
|
-
"tough-cookie": "6.0.2"
|
|
40
|
-
},
|
|
41
|
-
"devDependencies": {
|
|
42
|
-
"@types/node": "22.20.2",
|
|
43
|
-
"typescript": "5.9.3"
|
|
44
|
-
}
|
|
45
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@devly-cl/sii-client",
|
|
3
|
+
"version": "0.7.9",
|
|
4
|
+
"description": "Cliente HTTP del SII para acceso personal, RCV, XML, PDF por streaming y emisión de facturas y notas de crédito, independiente de framework.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "commonjs",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.13.0"
|
|
9
|
+
},
|
|
10
|
+
"main": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"require": "./dist/index.js",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public",
|
|
25
|
+
"registry": "https://registry.npmjs.org"
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "tsc -p tsconfig.json",
|
|
29
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
30
|
+
"test": "npm run build && node test/check.mjs && node test/invoices.mjs && node test/rcv-documents.mjs && node test/xml.mjs && node test/reconciliation.mjs && node --test test/rounding.mjs && node test/logout.mjs && node --test test/session-lifecycle.mjs && node test/credit-note-xml.mjs && node test/facturador.mjs && node test/invoicing.mjs && node test/invoice-optionals.mjs && node test/invoice-optionals-http.mjs && node test/issuance.mjs && node test/issuance-edges.mjs && node test/api-naming.mjs && node test/company-selection.mjs && node test/company-info.mjs && node test/transport-lifecycle.mjs && node test/application.mjs && node test/architecture.mjs && node test/pdf.mjs && node test/pdf-http.mjs && node test/document-status.mjs",
|
|
31
|
+
"check:example": "tsc --strict --noEmit --target ES2022 --module Node16 --moduleResolution Node16 --types node examples/consulta-rcv.ts examples/facturacion.ts examples/factura-opcionales.ts examples/consulta-pdf.ts examples/consulta-estado-documento.ts examples/consulta-empresa.ts",
|
|
32
|
+
"check": "npm run typecheck && npm test && npm run check:example",
|
|
33
|
+
"test:live": "npm run build && node scripts/live-check.mjs",
|
|
34
|
+
"prepack": "npm run check"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"parse5": "7.3.0",
|
|
38
|
+
"saxes": "^6.0.0",
|
|
39
|
+
"tough-cookie": "6.0.2"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@types/node": "22.20.2",
|
|
43
|
+
"typescript": "5.9.3"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
declare const STAGES: readonly ["AUTHENTICATION", "SESSION_CHECK", "COMPANY_AUTHORIZATION", "RCV_INITIALIZATION", "RCV_SUMMARY", "RCV_DETAIL", "XML_COMPANY_SELECTION", "XML_DOWNLOAD", "XML_PARSE", "LOGOUT", "DOCUMENT_PREPARATION", "DOCUMENT_REVIEW", "DOCUMENT_SIGNING", "DOCUMENT_SEND", "DOCUMENT_RECOVERY"];
|
|
2
|
-
declare const ENDPOINTS: readonly ["CAutInicio.cgi", "aaSessionService/load", "getDcvEmpresasAutorizadas", "getDatosInicio", "getResumen", "getDetalleCompra", "getDetalleVenta", "mipeSelEmpresa.cgi", "mipeLaunchPage.cgi", "mipeDownLoad.cgi", "autTermino.cgi", "mipeGenFacEx.cgi", "mipeDisplayPreView.cgi", "mipeGenXMLFirma.cgi", "getCertDigital.cgi", "postFirmaDigital.cgi", "mipeSendXML.cgi", "mipeAdminDocsEmi.cgi", "mipeGesDocEmi.cgi", "mipeDisplayPDF.cgi"];
|
|
3
|
-
declare const REASONS: readonly ["DOCUMENT_LIMIT_EXCEEDED", "DOCUMENT_NOT_FOUND", "EMPTY_RESPONSE", "HTML_RESPONSE", "PROVIDER_ERROR_PAGE", "UNEXPECTED_PDF", "UNEXPECTED_ARCHIVE", "UNEXPECTED_FORMAT", "INVALID_XML", "XML_IDENTITY_MISMATCH", "RESPONSE_TOO_LARGE", "HTTP_ERROR", "TIMEOUT", "TRANSPORT_ERROR", "RETRY_LATER", "CAPTCHA_REQUIRED", "SESSION_REQUIRED", "LOGIN_NOT_CONFIRMED", "PERSONAL_SESSION_REQUIRED", "SESSION_IDENTITY_MISMATCH", "COMPANY_NOT_AUTHORIZED", "COMPANY_SELECTION_REQUIRED", "PROVIDER_REJECTED", "INVALID_RESPONSE", "DOCUMENT_CONTENT_MISMATCH", "CERTIFICATE_UNAVAILABLE", "CERTIFICATE_PASSWORD_INVALID", "CERTIFICATE_EXPIRED", "CERTIFICATE_REVOKED", "SIGNATURE_INVALID", "ISSUANCE_OUTCOME_UNKNOWN"];
|
|
4
|
-
declare const RESPONSE_TYPES: readonly ["XML", "HTML", "PDF", "ZIP", "JSON", "EMPTY", "UNKNOWN"];
|
|
5
|
-
declare const CONTENT_TYPES: readonly ["application/xml", "text/xml", "application/octet-stream", "text/html", "application/pdf", "application/zip", "application/json", "text/plain"];
|
|
6
|
-
export interface SiiDiagnostics {
|
|
7
|
-
readonly traceId: string;
|
|
8
|
-
readonly stage: typeof STAGES[number];
|
|
9
|
-
readonly endpoint: typeof ENDPOINTS[number];
|
|
10
|
-
readonly reason: typeof REASONS[number];
|
|
11
|
-
readonly responseType?: typeof RESPONSE_TYPES[number];
|
|
12
|
-
readonly contentType?: typeof CONTENT_TYPES[number];
|
|
13
|
-
readonly httpStatus?: number;
|
|
14
|
-
readonly siiMessageCode?: string;
|
|
15
|
-
readonly siiResponseCode?: number;
|
|
16
|
-
readonly attempts?: number;
|
|
17
|
-
}
|
|
18
|
-
/** Only bounded, known protocol values cross this boundary. Never provider text or URLs. */
|
|
19
|
-
export declare function sanitizeSiiDiagnostics(value: unknown): SiiDiagnostics | undefined;
|
|
20
|
-
export declare class SiiError extends Error {
|
|
21
|
-
readonly code: string;
|
|
22
|
-
readonly httpStatus?: number | undefined;
|
|
23
|
-
readonly diagnostics?: SiiDiagnostics;
|
|
24
|
-
readonly description?: string;
|
|
25
|
-
constructor(code: string, httpStatus?: number | undefined, diagnostics?: unknown);
|
|
26
|
-
}
|
|
27
|
-
export {};
|