@devly-cl/sii-client 0.7.1 → 0.7.11
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 +84 -1
- package/dist/application/document-status.d.ts +5 -5
- package/dist/application/document-status.js +14 -9
- package/dist/application/dte-import-mapper.d.ts +8 -0
- package/dist/application/dte-import-mapper.js +25 -0
- package/dist/application/dte-import-model.d.ts +28 -0
- package/dist/application/dte-import-model.js +2 -0
- package/dist/application/dte-import.d.ts +37 -0
- package/dist/application/dte-import.js +352 -0
- package/dist/application/invoice-queries.d.ts +12 -6
- package/dist/application/invoice-queries.js +9 -5
- package/dist/application/issuance.d.ts +2 -2
- package/dist/application/issuance.js +26 -10
- package/dist/contracts.d.ts +32 -0
- package/dist/contracts.js +17 -0
- package/dist/domain/civil-date.d.ts +2 -0
- package/dist/domain/civil-date.js +10 -0
- package/dist/domain/document-status.d.ts +0 -4
- package/dist/domain/document-status.js +18 -11
- package/dist/domain/document.js +49 -9
- package/dist/domain/dte-arithmetic.d.ts +35 -0
- package/dist/domain/dte-arithmetic.js +78 -0
- package/dist/domain/dte-components.d.ts +9 -0
- package/dist/domain/dte-components.js +37 -0
- package/dist/domain/dte-detail.d.ts +111 -0
- package/dist/domain/dte-detail.js +2 -0
- package/dist/domain/dte-identity.d.ts +19 -0
- package/dist/domain/dte-identity.js +52 -0
- package/dist/domain/dte-money.d.ts +41 -0
- package/dist/domain/dte-money.js +81 -0
- package/dist/domain/dte-reconciliation-model.d.ts +87 -0
- package/dist/domain/dte-reconciliation-model.js +2 -0
- package/dist/domain/dte-reconciliation.d.ts +15 -0
- package/dist/domain/dte-reconciliation.js +390 -0
- package/dist/domain/dte-validation.d.ts +7 -0
- package/dist/domain/dte-validation.js +84 -0
- package/dist/domain/invoice-xml.d.ts +17 -57
- package/dist/domain/invoice-xml.js +0 -10
- package/dist/domain/invoicing.d.ts +30 -4
- package/dist/domain/invoicing.js +75 -21
- package/dist/domain/issued-invoice.d.ts +0 -6
- package/dist/domain/rcv-document.d.ts +0 -4
- package/dist/domain/received-invoice.d.ts +1 -4
- package/dist/index.d.ts +19 -9
- package/dist/index.js +20 -4
- package/dist/infrastructure/document-status-gateway.d.ts +6 -4
- package/dist/infrastructure/document-status-gateway.js +34 -13
- package/dist/infrastructure/document-status-parser.js +38 -12
- package/dist/infrastructure/dte-xml-mapper.d.ts +16 -0
- package/dist/infrastructure/dte-xml-mapper.js +381 -0
- package/dist/infrastructure/dte-xml.d.ts +40 -4
- package/dist/infrastructure/dte-xml.js +117 -196
- package/dist/infrastructure/facturador-gateway.d.ts +10 -7
- package/dist/infrastructure/facturador-gateway.js +256 -56
- package/dist/infrastructure/facturador.d.ts +1 -1
- package/dist/infrastructure/facturador.js +18 -10
- package/dist/infrastructure/invoice-pdf.js +10 -3
- package/dist/infrastructure/rcv-gateway.d.ts +7 -4
- package/dist/infrastructure/rcv-gateway.js +53 -12
- package/dist/infrastructure/rcv-normalization.d.ts +8 -1
- package/dist/infrastructure/rcv-normalization.js +54 -12
- package/dist/infrastructure/read-options.d.ts +3 -0
- package/dist/infrastructure/read-options.js +25 -0
- package/dist/infrastructure/sii-client.d.ts +98 -13
- package/dist/infrastructure/sii-client.js +182 -31
- package/dist/infrastructure/sii-http-session.d.ts +2 -2
- package/dist/infrastructure/sii-http-session.js +134 -37
- package/dist/sii-error.d.ts +5 -0
- package/dist/sii-error.js +39 -13
- package/package.json +2 -2
|
@@ -18,7 +18,6 @@ class SiiClient {
|
|
|
18
18
|
#rcv;
|
|
19
19
|
#facturador;
|
|
20
20
|
#issuance;
|
|
21
|
-
#documentQueries;
|
|
22
21
|
#companyLookup;
|
|
23
22
|
#disposal;
|
|
24
23
|
constructor(options) {
|
|
@@ -26,41 +25,173 @@ class SiiClient {
|
|
|
26
25
|
this.#rcv = new rcv_gateway_1.RcvGateway(this.#session);
|
|
27
26
|
this.#facturador = new facturador_gateway_1.FacturadorGateway(this.#session, () => this.dispose());
|
|
28
27
|
this.#issuance = new issuance_1.DocumentIssuance(this.#facturador);
|
|
29
|
-
this.#documentQueries = new document_status_2.DocumentQueries(new document_status_gateway_1.DocumentStatusGateway(this.#session));
|
|
30
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Autentica acceso personal y comprueba que la identidad puede operar sobre la empresa fijada en la instancia.
|
|
31
|
+
* Credenciales sólo en memoria; login no se reintenta automáticamente.
|
|
32
|
+
*/
|
|
31
33
|
login(credentials) {
|
|
32
34
|
return this.#session.login(credentials, async (identity) => (await this.#rcv.companies(identity)).data.some(company => `${company.usrEmpRut}-${company.usrEmpDv}`.toUpperCase() === this.#session.company.formatted));
|
|
33
35
|
}
|
|
34
|
-
|
|
36
|
+
/**
|
|
37
|
+
* Consulta las empresas autorizadas para la sesión personal. La autorización de actor, tenant y recurso pertenece al consumidor.
|
|
38
|
+
*/
|
|
39
|
+
async getAuthorizedCompanies() {
|
|
40
|
+
return this.#rcv.companies();
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Consulta razón social, direcciones y giros observados del RUT indicado, sin preparar ni emitir facturas.
|
|
44
|
+
*/
|
|
35
45
|
getCompanyInfo(rut) {
|
|
36
46
|
if (this.#companyLookup || this.#issuance.pendingWrite)
|
|
37
47
|
return Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS'));
|
|
38
48
|
const lookup = this.#facturador.companyInfo(rut).catch(error => {
|
|
39
49
|
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, {
|
|
50
|
+
throw new sii_error_1.SiiError(error.diagnostics.reason === 'RESPONSE_TOO_LARGE' ? 'SII_PROTOCOL_CHANGED' : error.code, error.httpStatus, {
|
|
51
|
+
...error.diagnostics,
|
|
52
|
+
stage: 'COMPANY_LOOKUP'
|
|
53
|
+
});
|
|
41
54
|
}
|
|
42
55
|
throw error;
|
|
43
56
|
});
|
|
44
57
|
this.#companyLookup = lookup;
|
|
45
|
-
void lookup.then(() => {
|
|
58
|
+
void lookup.then(() => {
|
|
59
|
+
this.#companyLookup = undefined;
|
|
60
|
+
}, () => {
|
|
61
|
+
this.#companyLookup = undefined;
|
|
62
|
+
});
|
|
46
63
|
return lookup;
|
|
47
64
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
65
|
+
/**
|
|
66
|
+
* Consulta el resumen RCV de toda la empresa para un período YYYYMM. El consumidor debe autorizar este alcance agregado.
|
|
67
|
+
*/
|
|
68
|
+
getSummary(input) {
|
|
69
|
+
return this.#rcv.summary(input);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Consulta facturas emitidas 33/34 en RCV; complete indica si los detalles observados cubren el resumen del proveedor.
|
|
73
|
+
*/
|
|
74
|
+
getIssuedInvoices(input) {
|
|
75
|
+
return this.#rcv.issuedInvoices(input);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Consulta facturas recibidas 33/34 en RCV; complete=false exige tratar el resultado como parcial.
|
|
79
|
+
*/
|
|
80
|
+
getReceivedInvoices(input) {
|
|
81
|
+
return this.#rcv.receivedInvoices(input);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Consulta documentos emitidos 33/34/61 en RCV, con identidades normalizadas y cobertura explícita.
|
|
85
|
+
*/
|
|
86
|
+
getIssuedDocuments(input) {
|
|
87
|
+
return this.#rcv.issuedDocuments(input);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Consulta documentos recibidos 33/34/61 en RCV; cada emisor conserva su identidad fiscal.
|
|
91
|
+
*/
|
|
92
|
+
getReceivedDocuments(input) {
|
|
93
|
+
return this.#rcv.receivedDocuments(input);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Consulta RCV emitido con importes enteros exactos como strings; mantiene las mismas reglas de autorización y cobertura.
|
|
97
|
+
*/
|
|
98
|
+
getIssuedDocumentsExact(input) {
|
|
99
|
+
return this.#rcv.issuedDocumentsExact(input);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Consulta RCV recibido con importes enteros exactos como strings, sin convertir primero los números fuente a Number.
|
|
103
|
+
*/
|
|
104
|
+
getReceivedDocumentsExact(input) {
|
|
105
|
+
return this.#rcv.receivedDocumentsExact(input);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Descarga XML de factura emitida 33/34 y comprueba su identidad.
|
|
109
|
+
* @param options reconcile=false omite la interpretación aritmética; por defecto conserva el comportamiento histórico.
|
|
110
|
+
*/
|
|
111
|
+
getIssuedInvoiceXml(input, options) {
|
|
112
|
+
return this.#facturador.issuedInvoiceXml(input, options);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Descarga XML de factura recibida 33/34 y comprueba emisor, receptor, tipo y folio.
|
|
116
|
+
* @param options reconcile=false entrega los datos declarados sin conciliación; identidad y autorización siguen siendo obligatorias.
|
|
117
|
+
*/
|
|
118
|
+
getReceivedInvoiceXml(input, options) {
|
|
119
|
+
return this.#facturador.receivedInvoiceXml(input, options);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Descarga XML emitido 33/34/61, con encabezado fiscal e importes numéricos seguros.
|
|
123
|
+
* @param options reconcile=false permite leer hechos sin exigir una referencia fiscal interpretable para una nota de crédito.
|
|
124
|
+
*/
|
|
125
|
+
getIssuedDocumentXml(input, options) {
|
|
126
|
+
return this.#facturador.issuedDocumentXml(input, options);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Descarga XML recibido 33/34/61 y comprueba también que la empresa autorizada es su receptor.
|
|
130
|
+
* @param options reconcile=false omite conciliación y requisitos de interpretación de referencias; conserva controles técnicos y de identidad.
|
|
131
|
+
*/
|
|
132
|
+
getReceivedDocumentXml(input, options) {
|
|
133
|
+
return this.#facturador.receivedDocumentXml(input, options);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Descarga XML emitido 33/34/61 conservando importes de hasta 18 dígitos como strings exactos.
|
|
137
|
+
* @param options reconcile=false omite el intento de conciliación numérica; los bytes originales se conservan.
|
|
138
|
+
*/
|
|
139
|
+
getIssuedDocumentXmlExact(input, options) {
|
|
140
|
+
return this.#facturador.issuedDocumentXmlExact(input, options);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Descarga XML recibido 33/34/61 con importes exactos y comprobación de emisor y receptor.
|
|
144
|
+
* @param options reconcile=false devuelve sólo los hechos declarados; no modifica precios, cantidades ni bytes.
|
|
145
|
+
*/
|
|
146
|
+
getReceivedDocumentXmlExact(input, options) {
|
|
147
|
+
return this.#facturador.receivedDocumentXmlExact(input, options);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Descarga PDF emitido 33/34 como stream, después de verificar empresa e identidad en el historial del proveedor.
|
|
151
|
+
*/
|
|
152
|
+
getIssuedInvoicePdf(input, options) {
|
|
153
|
+
return this.#facturador.issuedInvoicePdf(input, options);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Descarga PDF recibido 33/34 como stream y verifica también al proveedor solicitado. El consumidor debe consumir o cerrar el stream.
|
|
157
|
+
*/
|
|
158
|
+
getReceivedInvoicePdf(input, options) {
|
|
159
|
+
return this.#facturador.receivedInvoicePdf(input, options);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Consulta evidencia del documento recibida por el SII. fiscalVerdict permanece NOT_OBSERVED; no acredita aceptación tributaria.
|
|
163
|
+
*/
|
|
164
|
+
getDocumentStatus(input, options) {
|
|
165
|
+
return this.#translate(new document_status_2.DocumentQueries(new document_status_gateway_1.DocumentStatusGateway(this.#session, options)).getDocumentStatus(input));
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Consulta eventos del receptor verificando identidad y acceso en el rol solicitado. Un reporte de pago no registra un pago en el consumidor.
|
|
169
|
+
*/
|
|
170
|
+
getDocumentRecipientEvents(input, options) {
|
|
171
|
+
return this.#translate(new document_status_2.DocumentQueries(new document_status_gateway_1.DocumentStatusGateway(this.#session, options)).getDocumentRecipientEvents(input));
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Valida y prepara una factura tipo 33 para aprobación, sin firmarla ni enviarla. La preparación es de uso único y vence a los cinco minutos.
|
|
175
|
+
*/
|
|
176
|
+
prepareInvoice(input) {
|
|
177
|
+
return this.#companyLookup ? Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS')) : this.#translate(this.#issuance.prepareInvoice(input));
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Prepara una nota de crédito de anulación contra una factura tipo 33 original. Conserva las comprobaciones estrictas de contenido.
|
|
181
|
+
*/
|
|
182
|
+
prepareCancellationCreditNote(input) {
|
|
183
|
+
return this.#companyLookup ? Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS')) : this.#translate(this.#issuance.prepareCancellationCreditNote(input));
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Firma y envía exclusivamente el contenido preparado y aprobado.
|
|
187
|
+
* Exige beforeSend para respaldar documento e identidad antes del envío; no reintenta escrituras ante resultados desconocidos.
|
|
188
|
+
*/
|
|
189
|
+
signAndSend(input) {
|
|
190
|
+
return this.#companyLookup ? Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS')) : this.#translate(this.#issuance.signAndSend(input));
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Espera operaciones pendientes, cierra la sesión remota y libera recursos. Puede rechazar con SII_LOGOUT_FAILED aunque la limpieza local termine.
|
|
194
|
+
*/
|
|
64
195
|
dispose() {
|
|
65
196
|
if (!this.#disposal) {
|
|
66
197
|
this.#issuance.clearPreparation();
|
|
@@ -80,24 +211,44 @@ class SiiClient {
|
|
|
80
211
|
});
|
|
81
212
|
}
|
|
82
213
|
/** @deprecated Use getAuthorizedCompanies. */
|
|
83
|
-
getEmpresasAutorizadas() {
|
|
214
|
+
getEmpresasAutorizadas() {
|
|
215
|
+
return this.getAuthorizedCompanies();
|
|
216
|
+
}
|
|
84
217
|
/** @deprecated Use getSummary. */
|
|
85
|
-
getResumen(input) {
|
|
218
|
+
getResumen(input) {
|
|
219
|
+
return this.getSummary(input);
|
|
220
|
+
}
|
|
86
221
|
/** @deprecated Use getIssuedInvoices. */
|
|
87
|
-
getFacturasEmitidas(input) {
|
|
222
|
+
getFacturasEmitidas(input) {
|
|
223
|
+
return this.getIssuedInvoices(input);
|
|
224
|
+
}
|
|
88
225
|
/** @deprecated Use getReceivedInvoices. */
|
|
89
|
-
getFacturasRecibidas(input) {
|
|
226
|
+
getFacturasRecibidas(input) {
|
|
227
|
+
return this.getReceivedInvoices(input);
|
|
228
|
+
}
|
|
90
229
|
/** @deprecated Use getIssuedInvoiceXml. */
|
|
91
|
-
getXmlFacturaEmitida(input) {
|
|
230
|
+
getXmlFacturaEmitida(input, options) {
|
|
231
|
+
return this.getIssuedInvoiceXml(input, options);
|
|
232
|
+
}
|
|
92
233
|
/** @deprecated Use getReceivedInvoiceXml. */
|
|
93
|
-
getXmlFacturaRecibida(input) {
|
|
234
|
+
getXmlFacturaRecibida(input, options) {
|
|
235
|
+
return this.getReceivedInvoiceXml(input, options);
|
|
236
|
+
}
|
|
94
237
|
/** @deprecated Use getIssuedDocumentXml. */
|
|
95
|
-
getXmlDocumentoEmitido(input) {
|
|
238
|
+
getXmlDocumentoEmitido(input, options) {
|
|
239
|
+
return this.getIssuedDocumentXml(input, options);
|
|
240
|
+
}
|
|
96
241
|
/** @deprecated Use prepareInvoice. */
|
|
97
|
-
prepararFactura(input) {
|
|
242
|
+
prepararFactura(input) {
|
|
243
|
+
return this.prepareInvoice(input);
|
|
244
|
+
}
|
|
98
245
|
/** @deprecated Use prepareCancellationCreditNote. */
|
|
99
|
-
prepararNotaCreditoAnulacion(input) {
|
|
246
|
+
prepararNotaCreditoAnulacion(input) {
|
|
247
|
+
return this.prepareCancellationCreditNote(input);
|
|
248
|
+
}
|
|
100
249
|
/** @deprecated Use signAndSend. */
|
|
101
|
-
firmarYEnviar(input) {
|
|
250
|
+
firmarYEnviar(input) {
|
|
251
|
+
return this.signAndSend(input);
|
|
252
|
+
}
|
|
102
253
|
}
|
|
103
254
|
exports.SiiClient = SiiClient;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { parseRut } from '../domain/rut';
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
2
|
+
import type { InvoicePdfResult, SiiClientOptions, SiiCredentials, SiiSession } from '../contracts';
|
|
3
|
+
import { type SiiDiagnostics, SiiError } from '../sii-error';
|
|
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
6
|
export declare const DOCUMENT_STATUS_FORM = "https://palena.sii.cl/cgi_dte/UPL/DTEauth?6";
|
|
@@ -9,7 +9,7 @@ const promises_1 = require("node:timers/promises");
|
|
|
9
9
|
const promises_2 = require("node:stream/promises");
|
|
10
10
|
const tough_cookie_1 = require("tough-cookie");
|
|
11
11
|
const rut_1 = require("../domain/rut");
|
|
12
|
-
const
|
|
12
|
+
const contracts_1 = require("../contracts");
|
|
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/';
|
|
@@ -60,13 +60,40 @@ class SiiHttpSession {
|
|
|
60
60
|
throw new TypeError('Clave inválida');
|
|
61
61
|
this.#used = true;
|
|
62
62
|
try {
|
|
63
|
-
const body = new URLSearchParams({
|
|
63
|
+
const body = new URLSearchParams({
|
|
64
|
+
rut: identity.rut,
|
|
65
|
+
dv: identity.dv,
|
|
66
|
+
referencia: exports.RCV,
|
|
67
|
+
'411': '',
|
|
68
|
+
rutcntr: identity.formatted,
|
|
69
|
+
clave
|
|
70
|
+
});
|
|
64
71
|
await this.request(AUTH, async (response) => {
|
|
65
72
|
await response.body?.cancel();
|
|
73
|
+
const redirected = response.status >= 300 && response.status < 400;
|
|
74
|
+
if (redirected) {
|
|
75
|
+
try {
|
|
76
|
+
const location = response.headers.get('location');
|
|
77
|
+
const target = new URL(location ?? '', AUTH);
|
|
78
|
+
if (!location || target.protocol !== 'https:' || !(target.hostname === 'sii.cl' || target.hostname.endsWith('.sii.cl')) || target.username || target.password || target.port)
|
|
79
|
+
throw new Error();
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
throw this.failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', 'CAutInicio.cgi', 'SESSION_REQUIRED', response);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
66
85
|
const cookies = await this.cookies(exports.RCV);
|
|
67
86
|
if (!cookies.some(c => c.key === 'TOKEN' && c.value))
|
|
68
|
-
throw this.failure('LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', 'LOGIN_NOT_CONFIRMED', response);
|
|
69
|
-
}, {
|
|
87
|
+
throw this.failure(redirected ? 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' : 'LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', redirected ? 'SESSION_REQUIRED' : 'LOGIN_NOT_CONFIRMED', response);
|
|
88
|
+
}, {
|
|
89
|
+
method: 'POST',
|
|
90
|
+
headers: {
|
|
91
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
92
|
+
Origin: 'https://zeusr.sii.cl',
|
|
93
|
+
Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${exports.RCV}`
|
|
94
|
+
},
|
|
95
|
+
body: body.toString()
|
|
96
|
+
}, false, true);
|
|
70
97
|
await this.request(SESSION, async (response) => {
|
|
71
98
|
const sessionEnvelope = await this.json(response, 'aaSessionService/load');
|
|
72
99
|
const session = isRecord(sessionEnvelope) && isRecord(sessionEnvelope.data) ? sessionEnvelope.data : undefined;
|
|
@@ -84,7 +111,9 @@ class SiiHttpSession {
|
|
|
84
111
|
return { usuarioRut: identity.formatted, empresaRut: this.company.formatted, representacion: false };
|
|
85
112
|
}
|
|
86
113
|
catch (error) {
|
|
87
|
-
|
|
114
|
+
// Preserve authentication failure; callers still observe cleanup failure through dispose().
|
|
115
|
+
await this.dispose().catch(() => {
|
|
116
|
+
});
|
|
88
117
|
throw error;
|
|
89
118
|
}
|
|
90
119
|
}
|
|
@@ -93,10 +122,17 @@ class SiiHttpSession {
|
|
|
93
122
|
throw new sii_error_1.SiiError('SESSION_REQUIRED');
|
|
94
123
|
return this.#identity;
|
|
95
124
|
}
|
|
96
|
-
cookies(url) {
|
|
125
|
+
cookies(url) {
|
|
126
|
+
return this.#jar.getCookies(url);
|
|
127
|
+
}
|
|
97
128
|
failure(code, endpoint, reason, response, extra = {}) {
|
|
98
|
-
return new sii_error_1.SiiError(code, response?.status, {
|
|
99
|
-
|
|
129
|
+
return new sii_error_1.SiiError(code, response?.status, {
|
|
130
|
+
traceId: this.#traceId, stage: ENDPOINT_STAGES[endpoint], endpoint, reason,
|
|
131
|
+
...(response ? {
|
|
132
|
+
httpStatus: response.status, ...responseFormat(response),
|
|
133
|
+
retryAfterMs: retryAfterMs(response)
|
|
134
|
+
} : {}), ...extra
|
|
135
|
+
});
|
|
100
136
|
}
|
|
101
137
|
abortFailure(signal, endpoint) {
|
|
102
138
|
return signal.reason instanceof sii_error_1.SiiError ? signal.reason : this.failure('SII_OPERATION_ABORTED', endpoint, 'OPERATION_ABORTED');
|
|
@@ -159,7 +195,8 @@ class SiiHttpSession {
|
|
|
159
195
|
return result;
|
|
160
196
|
}
|
|
161
197
|
catch (error) {
|
|
162
|
-
await response.body?.cancel().catch(() => {
|
|
198
|
+
await response.body?.cancel().catch(() => {
|
|
199
|
+
});
|
|
163
200
|
throw error;
|
|
164
201
|
}
|
|
165
202
|
}).catch(error => {
|
|
@@ -180,21 +217,30 @@ class SiiHttpSession {
|
|
|
180
217
|
}
|
|
181
218
|
const bytes = response.body ? await this.readBounded(response, endpoint, MAX_JSON_BYTES, 'SII_PROTOCOL_CHANGED', signal) : new Uint8Array();
|
|
182
219
|
try {
|
|
183
|
-
return JSON.parse(new TextDecoder().decode(bytes))
|
|
220
|
+
return JSON.parse(new TextDecoder().decode(bytes), (_key, value, context) => {
|
|
221
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || Number.isSafeInteger(value))
|
|
222
|
+
return value;
|
|
223
|
+
if (!context?.source || !/^-?\d{1,20}$/.test(context.source))
|
|
224
|
+
throw new TypeError('SII_UNSAFE_JSON_NUMBER');
|
|
225
|
+
return context.source;
|
|
226
|
+
});
|
|
184
227
|
}
|
|
185
228
|
catch {
|
|
186
229
|
throw this.failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
|
|
187
230
|
}
|
|
188
231
|
}
|
|
189
|
-
async readBounded(response, endpoint, limit =
|
|
232
|
+
async readBounded(response, endpoint, limit = contracts_1.MAX_DTE_XML_BYTES, oversizedCode = 'SII_XML_INVALID', signal) {
|
|
190
233
|
const reader = response.body?.getReader();
|
|
191
234
|
if (!reader)
|
|
192
235
|
throw this.failure('SII_XML_UNAVAILABLE', endpoint, 'EMPTY_RESPONSE', response, { responseType: 'EMPTY' });
|
|
193
236
|
let size = 0;
|
|
194
237
|
const chunks = [];
|
|
195
238
|
let cancellation;
|
|
196
|
-
const cancelSource = () => cancellation ??= reader.cancel().catch(() => {
|
|
197
|
-
|
|
239
|
+
const cancelSource = () => cancellation ??= reader.cancel().catch(() => {
|
|
240
|
+
});
|
|
241
|
+
const onAbort = () => {
|
|
242
|
+
void cancelSource();
|
|
243
|
+
};
|
|
198
244
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
199
245
|
try {
|
|
200
246
|
for (;;) {
|
|
@@ -240,21 +286,41 @@ class SiiHttpSession {
|
|
|
240
286
|
if (!cookies.some(c => c.value && ['TOKEN', 'NETSCAPE_LIVEWIRE.mac'].includes(c.key)))
|
|
241
287
|
return;
|
|
242
288
|
const headers = new Headers({ Referer: exports.RCV, Cookie: cookies.map(c => c.cookieString()).join('; ') });
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
289
|
+
for (let attempt = 1;; attempt++) {
|
|
290
|
+
try {
|
|
291
|
+
const response = await this.#fetch(LOGOUT, {
|
|
292
|
+
method: 'GET',
|
|
293
|
+
headers,
|
|
294
|
+
redirect: 'manual',
|
|
295
|
+
signal: AbortSignal.timeout(this.#timeoutMs)
|
|
296
|
+
});
|
|
297
|
+
if (!response.ok) {
|
|
298
|
+
await response.body?.cancel();
|
|
299
|
+
if (!(response.status >= 300 && response.status < 400 && response.headers.get('location') === 'https://homer.sii.cl/'))
|
|
300
|
+
throw this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'HTTP_ERROR', response, { attempts: attempt });
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
303
|
+
const page = Buffer.from(await this.readBounded(response, 'autTermino.cgi')).toString('latin1');
|
|
304
|
+
const codes = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/g);
|
|
305
|
+
if (codes?.some(code => code !== '01.01.205.529.269.28'))
|
|
306
|
+
throw this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'INVALID_RESPONSE', response, { attempts: attempt });
|
|
307
|
+
}
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
const failure = error instanceof sii_error_1.SiiError ? error : this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'TRANSPORT_ERROR', undefined, { attempts: attempt });
|
|
312
|
+
const waitMs = failure.diagnostics?.retryAfterMs ?? 500 * attempt;
|
|
313
|
+
const transient = failure.diagnostics?.reason === 'TRANSPORT_ERROR' || failure.diagnostics?.reason === 'TIMEOUT' || RETRYABLE.has(failure.httpStatus ?? 0);
|
|
314
|
+
if (!transient || attempt > this.#retries || waitMs > 5000)
|
|
315
|
+
throw failure;
|
|
316
|
+
await (0, promises_1.setTimeout)(waitMs);
|
|
317
|
+
}
|
|
254
318
|
}
|
|
255
319
|
}
|
|
256
|
-
catch {
|
|
257
|
-
|
|
320
|
+
catch (error) {
|
|
321
|
+
if (error instanceof sii_error_1.SiiError)
|
|
322
|
+
throw new sii_error_1.SiiError('SII_LOGOUT_FAILED', error.httpStatus, error.diagnostics);
|
|
323
|
+
throw this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'TRANSPORT_ERROR');
|
|
258
324
|
}
|
|
259
325
|
finally {
|
|
260
326
|
await this.#jar.removeAllCookies();
|
|
@@ -278,7 +344,12 @@ class SiiHttpSession {
|
|
|
278
344
|
let response;
|
|
279
345
|
try {
|
|
280
346
|
const timeout = AbortSignal.timeout(this.#timeoutMs);
|
|
281
|
-
response = await this.#fetch(url, {
|
|
347
|
+
response = await this.#fetch(url, {
|
|
348
|
+
...options,
|
|
349
|
+
headers,
|
|
350
|
+
redirect: 'manual',
|
|
351
|
+
signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout
|
|
352
|
+
});
|
|
282
353
|
}
|
|
283
354
|
catch (error) {
|
|
284
355
|
if (options.signal?.aborted)
|
|
@@ -299,13 +370,11 @@ class SiiHttpSession {
|
|
|
299
370
|
throw this.abortFailure(options.signal, endpoint);
|
|
300
371
|
}
|
|
301
372
|
if (canRetry && RETRYABLE.has(response.status) && attempt < this.#retries) {
|
|
302
|
-
const
|
|
303
|
-
const seconds = retryAfter === null ? NaN : Number(retryAfter);
|
|
304
|
-
const waitMs = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : Date.parse(retryAfter ?? '') - Date.now();
|
|
373
|
+
const waitMs = retryAfterMs(response);
|
|
305
374
|
await response.body?.cancel();
|
|
306
|
-
if (
|
|
375
|
+
if (waitMs !== undefined && waitMs > 5000)
|
|
307
376
|
throw this.failure('SII_RETRY_LATER', endpoint, 'RETRY_LATER', response, { attempts: attempt + 1 });
|
|
308
|
-
await (0, promises_1.setTimeout)(
|
|
377
|
+
await (0, promises_1.setTimeout)(waitMs ?? 250 * (attempt + 1), undefined, { signal: options.signal ?? undefined });
|
|
309
378
|
continue;
|
|
310
379
|
}
|
|
311
380
|
if (!response.ok && !(allowRedirect && response.status >= 300 && response.status < 400)) {
|
|
@@ -318,12 +387,40 @@ class SiiHttpSession {
|
|
|
318
387
|
}
|
|
319
388
|
}
|
|
320
389
|
exports.SiiHttpSession = SiiHttpSession;
|
|
390
|
+
function retryAfterMs(response) {
|
|
391
|
+
const raw = response.headers.get('retry-after');
|
|
392
|
+
if (!raw?.trim())
|
|
393
|
+
return undefined;
|
|
394
|
+
const value = /^\d+(?:\.\d+)?$/.test(raw.trim()) ? Number(raw) * 1000 : Date.parse(raw) - Date.now();
|
|
395
|
+
return Number.isFinite(value) && value >= 0 ? Math.min(2_592_000_000, Math.ceil(value)) : undefined;
|
|
396
|
+
}
|
|
321
397
|
const ENDPOINT_STAGES = {
|
|
322
|
-
'CAutInicio.cgi': 'AUTHENTICATION',
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
398
|
+
'CAutInicio.cgi': 'AUTHENTICATION',
|
|
399
|
+
'aaSessionService/load': 'SESSION_CHECK',
|
|
400
|
+
getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
|
|
401
|
+
getDatosInicio: 'RCV_INITIALIZATION',
|
|
402
|
+
getResumen: 'RCV_SUMMARY',
|
|
403
|
+
getDetalleCompra: 'RCV_DETAIL',
|
|
404
|
+
getDetalleVenta: 'RCV_DETAIL',
|
|
405
|
+
'mipeSelEmpresa.cgi': 'XML_COMPANY_SELECTION',
|
|
406
|
+
'mipeLaunchPage.cgi': 'XML_COMPANY_SELECTION',
|
|
407
|
+
'mipeDownLoad.cgi': 'XML_DOWNLOAD',
|
|
408
|
+
'autTermino.cgi': 'LOGOUT',
|
|
409
|
+
'mipeGenFacEx.cgi': 'DOCUMENT_PREPARATION',
|
|
410
|
+
'mipeDisplayPreView.cgi': 'DOCUMENT_REVIEW',
|
|
411
|
+
'mipeGenXMLFirma.cgi': 'DOCUMENT_SIGNING',
|
|
412
|
+
'getCertDigital.cgi': 'DOCUMENT_SIGNING',
|
|
413
|
+
'postFirmaDigital.cgi': 'DOCUMENT_SIGNING',
|
|
414
|
+
'mipeSendXML.cgi': 'DOCUMENT_SEND',
|
|
415
|
+
'mipeAdminDocsEmi.cgi': 'DOCUMENT_RECOVERY',
|
|
416
|
+
'mipeGesDocEmi.cgi': 'DOCUMENT_RECOVERY',
|
|
417
|
+
'mipeDisplayPDF.cgi': 'PDF_DOWNLOAD',
|
|
418
|
+
'mipeAdminDocsRcp.cgi': 'PDF_HISTORY',
|
|
419
|
+
'mipeShowPdf.cgi': 'PDF_DOWNLOAD',
|
|
420
|
+
DTEauth: 'DOCUMENT_STATUS',
|
|
421
|
+
QEstadoDTE: 'DOCUMENT_STATUS',
|
|
422
|
+
registrorechazodtej6ui: 'RECIPIENT_EVENTS',
|
|
423
|
+
validarAccesoReceptor: 'RECIPIENT_EVENTS',
|
|
327
424
|
};
|
|
328
425
|
const DOCUMENT_ENDPOINTS = new Map([
|
|
329
426
|
[exports.DOCUMENT_STATUS_FORM, 'DTEauth'], [exports.DOCUMENT_STATUS_URL, 'QEstadoDTE'],
|
package/dist/sii-error.d.ts
CHANGED
|
@@ -14,9 +14,14 @@ 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;
|
|
21
|
+
/**
|
|
22
|
+
* Error público del SDK con código estable, estado HTTP opcional y diagnósticos sanitizados.
|
|
23
|
+
* No conserva credenciales ni cuerpos del proveedor. description explica la etapa observada del fallo.
|
|
24
|
+
*/
|
|
20
25
|
export declare class SiiError extends Error {
|
|
21
26
|
readonly code: string;
|
|
22
27
|
readonly httpStatus?: number | undefined;
|
package/dist/sii-error.js
CHANGED
|
@@ -26,15 +26,29 @@ 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 = {
|
|
32
|
-
AUTHENTICATION: 'inicio de sesión',
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
33
|
+
AUTHENTICATION: 'inicio de sesión',
|
|
34
|
+
SESSION_CHECK: 'validación de sesión',
|
|
35
|
+
COMPANY_AUTHORIZATION: 'autorización de empresa',
|
|
36
|
+
RCV_INITIALIZATION: 'inicio del RCV',
|
|
37
|
+
RCV_SUMMARY: 'resumen del RCV',
|
|
38
|
+
RCV_DETAIL: 'detalle del RCV',
|
|
39
|
+
XML_COMPANY_SELECTION: 'selección de empresa en el facturador',
|
|
40
|
+
XML_DOWNLOAD: 'descarga del XML',
|
|
41
|
+
XML_PARSE: 'validación del XML',
|
|
42
|
+
LOGOUT: 'cierre de sesión',
|
|
43
|
+
DOCUMENT_PREPARATION: 'preparación del documento',
|
|
44
|
+
DOCUMENT_REVIEW: 'revisión del documento',
|
|
45
|
+
DOCUMENT_SIGNING: 'firma del documento',
|
|
46
|
+
DOCUMENT_SEND: 'envío del documento',
|
|
47
|
+
DOCUMENT_RECOVERY: 'recuperación del documento emitido',
|
|
48
|
+
PDF_HISTORY: 'búsqueda de factura en el historial',
|
|
49
|
+
PDF_DOWNLOAD: 'descarga del PDF',
|
|
50
|
+
DOCUMENT_STATUS: 'consulta de recepción y contenido del DTE',
|
|
51
|
+
RECIPIENT_EVENTS: 'consulta de eventos del DTE',
|
|
38
52
|
COMPANY_LOOKUP: 'consulta de datos de empresa por RUT',
|
|
39
53
|
};
|
|
40
54
|
const REASON_LABELS = {
|
|
@@ -56,19 +70,31 @@ const REASON_LABELS = {
|
|
|
56
70
|
COMPANY_IDENTITY_MISMATCH: 'SII devolvió datos de otro RUT; no se entregaron.',
|
|
57
71
|
COMPANY_INFO_UNAVAILABLE: 'SII no entregó datos utilizables para este RUT. No confirma inexistencia del contribuyente.',
|
|
58
72
|
RESPONSE_TOO_LARGE: 'La respuesta de SII supera el límite permitido para este tipo de respuesta y no se procesó.',
|
|
59
|
-
HTTP_ERROR: 'SII respondió con un error HTTP.',
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
73
|
+
HTTP_ERROR: 'SII respondió con un error HTTP.',
|
|
74
|
+
TIMEOUT: 'SII no respondió dentro del tiempo permitido.',
|
|
75
|
+
TRANSPORT_ERROR: 'No se pudo completar la comunicación con SII.',
|
|
76
|
+
RETRY_LATER: 'SII pidió esperar antes de volver a consultar.',
|
|
77
|
+
CAPTCHA_REQUIRED: 'SII requiere resolver un CAPTCHA en su sitio.',
|
|
78
|
+
SESSION_REQUIRED: 'SII requiere autenticación interactiva o una sesión válida.',
|
|
79
|
+
LOGIN_NOT_CONFIRMED: 'SII no confirmó el inicio de sesión.',
|
|
80
|
+
PERSONAL_SESSION_REQUIRED: 'SII no confirmó una sesión personal.',
|
|
81
|
+
SESSION_IDENTITY_MISMATCH: 'La sesión de SII no corresponde al usuario solicitado.',
|
|
82
|
+
COMPANY_NOT_AUTHORIZED: 'SII no autorizó el acceso a la empresa solicitada.',
|
|
64
83
|
COMPANY_SELECTION_REQUIRED: 'SII no confirmó la selección de empresa en el facturador.',
|
|
65
|
-
PROVIDER_REJECTED: 'SII rechazó la solicitud.',
|
|
84
|
+
PROVIDER_REJECTED: 'SII rechazó la solicitud.',
|
|
85
|
+
INVALID_RESPONSE: 'SII devolvió una respuesta que no cumple el contrato esperado.',
|
|
66
86
|
DOCUMENT_CONTENT_MISMATCH: 'El contenido fiscal recibido difiere del contenido aprobado. No se envió el documento.',
|
|
67
87
|
CERTIFICATE_UNAVAILABLE: 'SII no devolvió un certificado centralizado utilizable para esta identidad.',
|
|
68
|
-
CERTIFICATE_PASSWORD_INVALID: 'SII rechazó la clave del certificado centralizado.',
|
|
88
|
+
CERTIFICATE_PASSWORD_INVALID: 'SII rechazó la clave del certificado centralizado.',
|
|
89
|
+
CERTIFICATE_EXPIRED: 'El certificado centralizado está expirado.',
|
|
90
|
+
CERTIFICATE_REVOKED: 'El certificado centralizado está revocado.',
|
|
69
91
|
SIGNATURE_INVALID: 'SII no devolvió un XML firmado válido para el documento aprobado. No se envió.',
|
|
70
92
|
ISSUANCE_OUTCOME_UNKNOWN: 'El envío comenzó pero no se confirmó su resultado. Conserve el XML y consulte el historial antes de volver a emitir; repetir puede duplicar el documento.',
|
|
71
93
|
};
|
|
94
|
+
/**
|
|
95
|
+
* Error público del SDK con código estable, estado HTTP opcional y diagnósticos sanitizados.
|
|
96
|
+
* No conserva credenciales ni cuerpos del proveedor. description explica la etapa observada del fallo.
|
|
97
|
+
*/
|
|
72
98
|
class SiiError extends Error {
|
|
73
99
|
code;
|
|
74
100
|
httpStatus;
|