@devly-cl/sii-client 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +36 -4
  2. package/dist/application/invoice-queries.d.ts +17 -0
  3. package/dist/application/invoice-queries.js +51 -0
  4. package/dist/application/issuance.d.ts +40 -0
  5. package/dist/application/issuance.js +79 -0
  6. package/dist/contracts.d.ts +66 -0
  7. package/dist/contracts.js +2 -0
  8. package/dist/domain/document.d.ts +47 -0
  9. package/dist/domain/document.js +38 -0
  10. package/dist/domain/invoice-xml.d.ts +0 -10
  11. package/dist/domain/invoice-xml.js +0 -170
  12. package/dist/domain/issued-invoice.d.ts +1 -2
  13. package/dist/domain/issued-invoice.js +4 -43
  14. package/dist/domain/received-invoice.d.ts +1 -3
  15. package/dist/domain/received-invoice.js +0 -10
  16. package/dist/index.d.ts +5 -3
  17. package/dist/index.js +4 -3
  18. package/dist/infrastructure/dte-xml.d.ts +11 -0
  19. package/dist/infrastructure/dte-xml.js +173 -0
  20. package/dist/infrastructure/facturador-gateway.d.ts +28 -0
  21. package/dist/infrastructure/facturador-gateway.js +411 -0
  22. package/dist/infrastructure/facturador.d.ts +10 -3
  23. package/dist/infrastructure/facturador.js +16 -2
  24. package/dist/infrastructure/invoice-pdf.d.ts +9 -0
  25. package/dist/infrastructure/invoice-pdf.js +171 -0
  26. package/dist/infrastructure/rcv-gateway.d.ts +17 -0
  27. package/dist/infrastructure/rcv-gateway.js +105 -0
  28. package/dist/infrastructure/rcv-normalization.d.ts +6 -0
  29. package/dist/infrastructure/rcv-normalization.js +55 -0
  30. package/dist/infrastructure/sii-client.d.ts +22 -121
  31. package/dist/infrastructure/sii-client.js +45 -774
  32. package/dist/infrastructure/sii-http-session.d.ts +25 -0
  33. package/dist/infrastructure/sii-http-session.js +344 -0
  34. package/dist/sii-error.d.ts +27 -0
  35. package/dist/sii-error.js +86 -0
  36. package/package.json +4 -4
@@ -1,538 +1,58 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SiiClient = exports.SiiError = void 0;
4
- const node_crypto_1 = require("node:crypto");
5
- const promises_1 = require("node:timers/promises");
6
- const tough_cookie_1 = require("tough-cookie");
7
- const parse5_1 = require("parse5");
8
- const rut_1 = require("../domain/rut");
9
- const sii_error_1 = require("../domain/sii-error");
10
- var sii_error_2 = require("../domain/sii-error");
4
+ const sii_error_1 = require("../sii-error");
5
+ const document_1 = require("../domain/document");
6
+ const issuance_1 = require("../application/issuance");
7
+ const sii_http_session_1 = require("./sii-http-session");
8
+ const rcv_gateway_1 = require("./rcv-gateway");
9
+ const facturador_gateway_1 = require("./facturador-gateway");
10
+ var sii_error_2 = require("../sii-error");
11
11
  Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_error_2.SiiError; } });
12
- const issued_invoice_1 = require("../domain/issued-invoice");
13
- const received_invoice_1 = require("../domain/received-invoice");
14
- const invoice_xml_1 = require("../domain/invoice-xml");
15
- const invoice_xml_2 = require("../domain/invoice-xml");
16
- const invoicing_1 = require("../domain/invoicing");
17
- const facturador_1 = require("./facturador");
18
- const AUTH = 'https://zeusr.sii.cl/cgi_AUT2000/CAutInicio.cgi';
19
- const LOGOUT = 'https://zeusr.sii.cl/cgi_AUT2000/autTermino.cgi';
20
- const RCV = 'https://www4.sii.cl/consdcvinternetui/';
21
- const SESSION = 'https://www4.sii.cl/common-1.0/services/aaSessionService/load';
22
- const NAMESPACE = 'cl.sii.sdi.lob.diii.consdcv.data.api.interfaces.FacadeService/';
23
- const RETRYABLE = new Set([429, 502, 503, 504]);
24
- const STATES = new Set(['REGISTRO', 'PENDIENTE', 'NO_INCLUIR', 'RECLAMADO']);
25
- const FACTURADOR = 'https://www1.sii.cl/cgi-bin/Portal001/';
26
- const FACTURADOR_DESTINATION = 'OPCION=2&TIPO=4';
27
- const ENDPOINT_STAGES = {
28
- 'CAutInicio.cgi': 'AUTHENTICATION', 'aaSessionService/load': 'SESSION_CHECK', getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
29
- getDatosInicio: 'RCV_INITIALIZATION', getResumen: 'RCV_SUMMARY', getDetalleCompra: 'RCV_DETAIL', getDetalleVenta: 'RCV_DETAIL',
30
- 'mipeSelEmpresa.cgi': 'XML_COMPANY_SELECTION', 'mipeLaunchPage.cgi': 'XML_COMPANY_SELECTION', 'mipeDownLoad.cgi': 'XML_DOWNLOAD', 'autTermino.cgi': 'LOGOUT',
31
- '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': 'DOCUMENT_RECOVERY',
32
- };
33
- function endpointFor(url) {
34
- const path = new URL(url).pathname;
35
- const endpoint = path.endsWith('/aaSessionService/load') ? 'aaSessionService/load' : path.slice(path.lastIndexOf('/') + 1);
36
- if (!Object.hasOwn(ENDPOINT_STAGES, endpoint))
37
- throw new TypeError('Endpoint SII desconocido');
38
- return endpoint;
39
- }
40
- function responseFormat(response, bytes) {
41
- const contentType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
42
- const prefix = bytes ? Buffer.from(bytes.subarray(0, 512)).toString('latin1').trimStart() : '';
43
- const responseType = bytes?.length === 0 ? 'EMPTY'
44
- : prefix.startsWith('%PDF-') ? 'PDF'
45
- : bytes && bytes[0] === 0x50 && bytes[1] === 0x4b && [0x03, 0x05, 0x07].includes(bytes[2] ?? -1) ? 'ZIP'
46
- : /^(?:<!doctype\s+html|<html|<head|<body|<script|<div)\b/i.test(prefix) ? 'HTML'
47
- : contentType === 'text/html' ? 'HTML'
48
- : contentType === 'application/pdf' ? 'PDF'
49
- : contentType === 'application/zip' ? 'ZIP'
50
- : contentType?.includes('json') ? 'JSON'
51
- : /^(?:application|text)\/xml$/.test(contentType ?? '') || /^<(?:\?xml|DTE|EnvioDTE|SetDTE)\b/i.test(prefix) ? 'XML' : 'UNKNOWN';
52
- // The sanitizer copies only known MIME values.
53
- return { responseType, ...(contentType ? { contentType: contentType } : {}) };
54
- }
55
- function isRecord(value) {
56
- return typeof value === 'object' && value !== null && !Array.isArray(value);
57
- }
58
- function assertPeriod(periodo) {
59
- if (typeof periodo !== 'string' || !/^\d{4}(0[1-9]|1[0-2])$/.test(periodo) || Number(periodo.slice(0, 4)) < 2017)
60
- throw new TypeError('Periodo inválido: YYYYMM');
61
- }
62
- function htmlElements(root) {
63
- const pending = [root];
64
- const elements = [];
65
- for (let node = pending.pop(); node; node = pending.pop()) {
66
- if ('tagName' in node && node.namespaceURI === 'http://www.w3.org/1999/xhtml')
67
- elements.push(node);
68
- if ('childNodes' in node)
69
- for (const child of node.childNodes)
70
- pending.push(child);
71
- }
72
- return elements;
73
- }
74
- /** Read the observed selector inertly; never execute scripts or forward arbitrary form fields. */
75
- function companySelection(page, company, expectedDestination = FACTURADOR_DESTINATION) {
76
- const attr = (element, name) => element.attrs.find(a => a.name === name)?.value;
77
- const forms = htmlElements((0, parse5_1.parse)(page)).filter(e => e.tagName === 'form' && attr(e, 'name') === 'fPrmEmpPOP');
78
- const form = forms[0];
79
- if (!form)
80
- return undefined;
81
- if (forms.length !== 1 || attr(form, 'method')?.toLowerCase() !== 'post')
82
- return 'INVALID_RESPONSE';
83
- try {
84
- if (new URL(attr(form, 'action') ?? '', FACTURADOR).href !== `${FACTURADOR}mipeSelEmpresa.cgi`)
85
- return 'INVALID_RESPONSE';
86
- }
87
- catch {
88
- return 'INVALID_RESPONSE';
89
- }
90
- const controls = htmlElements(form);
91
- const selects = controls.filter(e => e.tagName === 'select' && attr(e, 'name') === 'RUT_EMP');
92
- const destinations = controls.filter(e => e.tagName === 'input' && attr(e, 'name') === 'DESDE_DONDE_URL');
93
- const select = selects[0], destination = destinations[0];
94
- if (selects.length !== 1 || destinations.length !== 1 || !select || !destination
95
- || attr(select, 'disabled') !== undefined || attr(select, 'multiple') !== undefined || attr(select, 'form') !== undefined
96
- || attr(destination, 'type')?.toLowerCase() !== 'hidden' || attr(destination, 'disabled') !== undefined || attr(destination, 'form') !== undefined
97
- || attr(destination, 'value') !== expectedDestination)
98
- return 'INVALID_RESPONSE';
99
- const options = htmlElements(select).filter(e => e.tagName === 'option' && attr(e, 'value')?.replace(/\./g, '').toUpperCase() === company);
100
- if (options.length > 1)
101
- return 'INVALID_RESPONSE';
102
- const option = options[0];
103
- if (!option || attr(option, 'disabled') !== undefined
104
- || (option.parentNode && 'tagName' in option.parentNode && option.parentNode.tagName === 'optgroup' && attr(option.parentNode, 'disabled') !== undefined))
105
- return 'COMPANY_NOT_AUTHORIZED';
106
- return new URLSearchParams({ DESDE_DONDE_URL: expectedDestination, RUT_EMP: company });
107
- }
108
- /** Una instancia = una empresa y una sesión personal. Nunca comparte cookies. */
12
+ /** One company and personal session; composition and compatibility stay at this boundary. */
109
13
  class SiiClient {
110
- #jar = new tough_cookie_1.CookieJar();
111
- #company;
112
- #fetch;
113
- #timeoutMs;
114
- #retries;
115
- #identity;
116
- #ready = false;
117
- #used = false;
118
- #closed = false;
119
- #facturadorReady = false;
120
- #requests = new Set();
14
+ #session;
15
+ #rcv;
16
+ #facturador;
17
+ #issuance;
121
18
  #disposal;
122
- #traceId = (0, node_crypto_1.randomUUID)();
123
- #write;
124
- #prepared;
125
- #failure(code, endpoint, reason, response, extra = {}) {
126
- return new sii_error_1.SiiError(code, response?.status, { traceId: this.#traceId, stage: ENDPOINT_STAGES[endpoint], endpoint, reason,
127
- ...(response ? { httpStatus: response.status, ...responseFormat(response) } : {}), ...extra });
128
- }
129
- constructor({ empresaRut, timeoutMs = 15000, retries = 1, fetchImpl = globalThis.fetch }) {
130
- this.#company = (0, rut_1.parseRut)(empresaRut);
131
- if (!Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 30000)
132
- throw new TypeError('timeoutMs inválido');
133
- if (!Number.isInteger(retries) || retries < 0 || retries > 2)
134
- throw new TypeError('retries inválido');
135
- if (typeof fetchImpl !== 'function')
136
- throw new TypeError('fetchImpl inválido');
137
- this.#fetch = fetchImpl;
138
- this.#timeoutMs = timeoutMs;
139
- this.#retries = retries;
140
- }
141
- async login({ rut, clave }) {
142
- if (this.#used || this.#closed)
143
- throw new sii_error_1.SiiError('NEW_INSTANCE_REQUIRED');
144
- const identity = (0, rut_1.parseRut)(rut);
145
- if (typeof clave !== 'string' || !clave || clave.length > 256)
146
- throw new TypeError('Clave inválida');
147
- this.#used = true;
148
- try {
149
- const body = new URLSearchParams({ rut: identity.rut, dv: identity.dv, referencia: RCV, '411': '', rutcntr: identity.formatted, clave });
150
- const response = await this.#request(AUTH, {
151
- method: 'POST',
152
- headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: 'https://zeusr.sii.cl', Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${RCV}` },
153
- body: body.toString(),
154
- });
155
- await response.body?.cancel();
156
- const cookies = await this.#jar.getCookies(RCV);
157
- if (!cookies.some(c => c.key === 'TOKEN' && c.value))
158
- throw this.#failure('LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', 'LOGIN_NOT_CONFIRMED', response);
159
- const sessionResponse = await this.#request(SESSION, {}, true);
160
- const sessionEnvelope = await this.#json(sessionResponse, 'aaSessionService/load');
161
- const session = isRecord(sessionEnvelope) && isRecord(sessionEnvelope.data) ? sessionEnvelope.data : undefined;
162
- if (session?.hayRepresentacion !== false)
163
- throw this.#failure('PERSONAL_SESSION_REQUIRED', 'aaSessionService/load', 'PERSONAL_SESSION_REQUIRED', sessionResponse);
164
- if (`${session?.rut}-${session?.dv}`.toUpperCase() !== identity.formatted)
165
- throw this.#failure('SESSION_IDENTITY_MISMATCH', 'aaSessionService/load', 'SESSION_IDENTITY_MISMATCH', sessionResponse);
166
- this.#identity = identity;
167
- const companies = await this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
168
- if (!companies.data.some(c => `${c.usrEmpRut}-${c.usrEmpDv}`.toUpperCase() === this.#company.formatted)) {
169
- throw this.#failure('COMPANY_NOT_AUTHORIZED', 'getDcvEmpresasAutorizadas', 'COMPANY_NOT_AUTHORIZED');
170
- }
171
- if (this.#closed)
172
- throw new sii_error_1.SiiError('CLIENT_CLOSED');
173
- this.#ready = true;
174
- return { usuarioRut: identity.formatted, empresaRut: this.#company.formatted, representacion: false };
175
- }
176
- catch (error) {
177
- await this.dispose();
178
- throw error;
19
+ constructor(options) {
20
+ this.#session = new sii_http_session_1.SiiHttpSession(options);
21
+ this.#rcv = new rcv_gateway_1.RcvGateway(this.#session);
22
+ this.#facturador = new facturador_gateway_1.FacturadorGateway(this.#session, () => this.dispose());
23
+ this.#issuance = new issuance_1.DocumentIssuance(this.#facturador);
24
+ }
25
+ login(credentials) {
26
+ 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
+ }
28
+ async getAuthorizedCompanies() { return this.#rcv.companies(); }
29
+ getSummary(input) { return this.#rcv.summary(input); }
30
+ getIssuedInvoices(input) { return this.#rcv.issuedInvoices(input); }
31
+ getReceivedInvoices(input) { return this.#rcv.receivedInvoices(input); }
32
+ getIssuedInvoiceXml(input) { return this.#facturador.issuedInvoiceXml(input); }
33
+ getReceivedInvoiceXml(input) { return this.#facturador.receivedInvoiceXml(input); }
34
+ getIssuedDocumentXml(input) { return this.#facturador.issuedDocumentXml(input); }
35
+ getIssuedInvoicePdf(input, options) { return this.#facturador.issuedInvoicePdf(input, options); }
36
+ getReceivedInvoicePdf(input, options) { return this.#facturador.receivedInvoicePdf(input, options); }
37
+ prepareInvoice(input) { return this.#translate(this.#issuance.prepareInvoice(input)); }
38
+ prepareCancellationCreditNote(input) { return this.#translate(this.#issuance.prepareCancellationCreditNote(input)); }
39
+ signAndSend(input) { return this.#translate(this.#issuance.signAndSend(input)); }
40
+ dispose() {
41
+ if (!this.#disposal) {
42
+ this.#issuance.clearPreparation();
43
+ this.#disposal = this.#session.dispose(this.#issuance.pendingWrite).finally(() => this.#facturador.clearPreparation());
179
44
  }
45
+ return this.#disposal;
180
46
  }
181
- async getAuthorizedCompanies() {
182
- const identity = this.#assertReady();
183
- return this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
184
- }
185
- async getSummary({ periodo, operacion, estado = 'REGISTRO' }) {
186
- this.#assertReady();
187
- assertPeriod(periodo);
188
- if (!['COMPRA', 'VENTA'].includes(operacion))
189
- throw new TypeError('Operación inválida');
190
- if (!STATES.has(estado) || (operacion === 'VENTA' && estado !== 'REGISTRO'))
191
- throw new TypeError('Estado inválido');
192
- return this.#call('getResumen', { rutEmisor: this.#company.rut, dvEmisor: this.#company.dv, ptributario: periodo, estadoContab: estado, operacion });
193
- }
194
- getIssuedInvoices(input) {
195
- return this.#getInvoices('VENTA', input, issued_invoice_1.normalizeIssuedInvoice);
196
- }
197
- /** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
198
- getReceivedInvoices(input) {
199
- return this.#getInvoices('COMPRA', input, received_invoice_1.normalizeReceivedInvoice);
200
- }
201
- async prepareInvoice(input) {
202
- this.#assertReady();
203
- const invoice = (0, invoicing_1.validateInvoice)(input);
204
- return this.#writeOperation(async () => {
205
- await this.#ensureInvoicingPortal('OPCION=33&TIPO=4');
206
- let page = await this.#portal('mipeGenFacEx.cgi', undefined, '?PTDC_CODIGO=33');
207
- let fields = this.#form(page, 'VIEW_EFXP', 'mipeDisplayPreView.cgi');
208
- this.#assertNewInvoice(fields);
209
- const issuerAddress = this.#assertOption(page, 'emisorDir', invoice.issuer.address, invoice.issuer.commune);
210
- this.#assertOption(page, 'emisorActEco', invoice.issuer.activityCode);
211
- const receiver = (0, rut_1.parseRut)(invoice.receiver.rut);
212
- fields.set('EFXP_RUT_RECEP', receiver.rut);
213
- fields.set('EFXP_DV_RECEP', receiver.dv);
214
- page = await this.#portal('mipeGenFacEx.cgi', fields);
215
- fields = this.#form(page, 'VIEW_EFXP', 'mipeDisplayPreView.cgi');
216
- this.#assertNewInvoice(fields);
217
- this.#assertOption(page, 'recptorDir', invoice.receiver.address, invoice.receiver.commune);
218
- this.#assertOption(page, 'recptoActEco', invoice.receiver.businessActivity, undefined, 1);
219
- if (fields.get('EFXP_RZN_SOC_RECEP')?.trim() && fields.get('EFXP_RZN_SOC_RECEP')?.trim() !== invoice.receiver.legalName)
220
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
221
- const totals = (0, invoicing_1.calculateInvoiceTotals)(invoice.items);
222
- const values = {
223
- PTDC_CODIGO: '33', EFXP_FCH_EMIS: invoice.issuedDate, CANT_DET: String(invoice.items.length), ES_BORR: 'FALSE',
224
- EFXP_DIR_ORIGEN: invoice.issuer.address, EFXP_CMNA_ORIGEN: invoice.issuer.commune, EFXP_CIUDAD_ORIGEN: invoice.issuer.city,
225
- EFXP_CDG_SII_SUCUR: issuerAddress[3]?.trim() === '0' ? '' : issuerAddress[3]?.trim() ?? '', EFXP_FONO_EMISOR: issuerAddress[4]?.trim() ?? '',
226
- EFXP_ACTECO: invoice.issuer.activityCode, EFXP_ACTECO_SELECT: invoice.issuer.activityCode, EFXP_TIPOVENTA_SELECT: String(invoice.saleType),
227
- EFXP_RUT_RECEP: receiver.rut, EFXP_DV_RECEP: receiver.dv, EFXP_RZN_SOC_RECEP: invoice.receiver.legalName,
228
- EFXP_DIR_RECEP: invoice.receiver.address, EFXP_CMNA_RECEP: invoice.receiver.commune, EFXP_CIUDAD_RECEP: invoice.receiver.city,
229
- EFXP_GIRO_RECEP: invoice.receiver.businessActivity, EFXP_CONTACTO: invoice.receiver.contact ?? '', EFXP_TIPOCOMPRA_SELECT: String(invoice.purchaseType),
230
- EFXP_RUT_SOLICITA: '', EFXP_DV_SOLICITA: '', EFXP_FMA_PAGO: String(invoice.paymentForm),
231
- EFXP_SUBTOTAL: String(totals.netAmount), EFXP_PCT_DESC: '0', EFXP_MNT_DESC: '0', MNT_NETO_TEMP: String(totals.netAmount), IVA_TEMP: String(totals.vatAmount),
232
- EFXP_MNT_NETO: String(totals.netAmount), EFXP_TASA_IVA: '19', EFXP_IVA: String(totals.vatAmount), EFXP_MNT_TOTAL: String(totals.totalAmount), EFXP_OTRO_IMP_TOTAL: '0',
233
- };
234
- for (const [key, value] of Object.entries(values))
235
- fields.set(key, value);
236
- for (const key of [...fields.keys()])
237
- if (/^(?:EFXP_(?:TPO_COD|COD|NMB|QTY|UNMD|PRC|OTRO_IMP|PCTD|SUBT|DSC_ITEM)_\d{2}|DESCRIP_\d{2}|.*_SI_NO)$/.test(key))
238
- fields.delete(key);
239
- for (const [index, item] of invoice.items.entries()) {
240
- const suffix = String(index + 1).padStart(2, '0');
241
- for (const [field, value] of Object.entries({ NMB: item.name, QTY: item.quantity, PRC: item.unitNetPriceClp, UNMD: item.unit ?? '', DSC_ITEM: item.description ?? '', PCTD: '', SUBT: String((0, invoicing_1.calculateInvoiceTotals)([item]).netAmount) }))
242
- fields.set(`EFXP_${field}_${suffix}`, value);
243
- if (item.description)
244
- fields.set(`DESCRIP_${suffix}`, 'SiChecked');
245
- }
246
- page = await this.#portal('mipeDisplayPreView.cgi', fields);
247
- const preview = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
248
- this.#assertFields(preview, { PTDC_CODIGO: '33', EFXP_FCH_EMIS: invoice.issuedDate, EFXP_RUT_RECEP: receiver.rut, EFXP_DV_RECEP: receiver.dv, EFXP_MNT_NETO: String(totals.netAmount), EFXP_IVA: String(totals.vatAmount), EFXP_MNT_TOTAL: String(totals.totalAmount) });
249
- return this.#keepPreparation({ issuerRut: this.#company.formatted, receiverRut: receiver.formatted, documentType: 33, issuedDate: invoice.issuedDate, ...totals, invoice, issuerLegalName: fields.get('EFXP_RZN_SOC')?.trim() ?? '', issuerBusinessActivity: fields.get('EFXP_GIRO_EMIS')?.trim() ?? '', issuerBranchCode: fields.get('EFXP_CDG_SII_SUCUR') ?? '' }, preview);
250
- });
251
- }
252
- async prepareCancellationCreditNote({ factura, issuedDate }) {
253
- this.#assertReady();
254
- if (factura.documentType !== 33 || !/^[1-9]\d{0,19}$/.test(factura.folio) || !/^\d{4}-\d{2}-\d{2}$/.test(issuedDate) || new Date(`${issuedDate}T00:00:00Z`).toISOString().slice(0, 10) !== issuedDate)
255
- throw new TypeError('Referencia o fecha de anulación inválida');
256
- return this.#writeOperation(async () => {
257
- const original = await this.getIssuedDocumentXml(factura);
258
- const query = new URLSearchParams({ RUT_RECP: '', FOLIO: factura.folio, RZN_SOC: '', FEC_DESDE: '', FEC_HASTA: '', TPO_DOC: '33', ESTADO: '', ORDEN: '', NUM_PAG: '1' });
259
- const history = await this.#portal('mipeAdminDocsEmi.cgi', undefined, `?${query}`);
260
- const codes = new Set();
261
- for (const element of htmlElements((0, parse5_1.parse)(history)))
262
- if (element.tagName === 'a') {
263
- const href = element.attrs.find(a => a.name === 'href')?.value;
264
- if (!href)
265
- continue;
266
- try {
267
- const link = new URL(href, FACTURADOR);
268
- if (link.origin === 'https://www1.sii.cl' && link.pathname === '/cgi-bin/Portal001/mipeGesDocEmi.cgi' && /^\d{1,20}$/.test(link.searchParams.get('CODIGO') ?? ''))
269
- codes.add(link.searchParams.get('CODIGO'));
270
- }
271
- catch { /* Non-document links are ignored. */ }
272
- }
273
- if (codes.size !== 1)
274
- throw this.#failure('SII_DOCUMENT_RECOVERY_FAILED', 'mipeAdminDocsEmi.cgi', codes.size === 0 ? 'DOCUMENT_NOT_FOUND' : 'INVALID_RESPONSE');
275
- const page = await this.#portal('mipeDisplayPreView.cgi', undefined, `?EHDR_CODIGO=${[...codes][0]}&TIPO_NOTA=61`);
276
- const fields = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
277
- const d = original.detail;
278
- this.#assertFields(fields, { PTDC_CODIGO: '61', EFXP_FCH_EMIS: issuedDate, EFXP_RUT_RECEP: (0, rut_1.parseRut)(d.receiverRut).rut, EFXP_DV_RECEP: (0, rut_1.parseRut)(d.receiverRut).dv, EFXP_TPO_DOC_REF_001: '33', EFXP_FOLIO_REF_001: d.folio, EFXP_FCH_REF_001: d.issuedDate, EFXP_CODIGO_REF_001: '1', EFXP_MNT_NETO: String(d.netAmount), EFXP_IVA: String(d.vatAmount), EFXP_MNT_TOTAL: String(d.totalAmount) });
279
- if (fields.get('EFXP_FOLIO_REF_002')?.trim() || fields.get('EFXP_FOLIO_REF_003')?.trim() || d.netAmount === null || d.vatAmount === null)
280
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
281
- return this.#keepPreparation({ issuerRut: d.issuerRut, receiverRut: d.receiverRut, documentType: 61, issuedDate, netAmount: d.netAmount, vatAmount: d.vatAmount, totalAmount: d.totalAmount, originalInvoice: d, reference: { documentType: 33, folio: d.folio, issuedDate: d.issuedDate, code: 1 } }, fields);
47
+ #translate(operation) {
48
+ return operation.catch(error => {
49
+ if (error instanceof issuance_1.IssuanceError)
50
+ throw new sii_error_1.SiiError(error.code);
51
+ if (error instanceof document_1.DocumentContentMismatchError)
52
+ throw this.#session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
53
+ throw error;
282
54
  });
283
55
  }
284
- signAndSend(input) {
285
- if (this.#write)
286
- return Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS'));
287
- const prepared = this.#prepared;
288
- if (!prepared || input.preparacionId !== prepared.public.preparacionId || Date.now() >= Date.parse(prepared.public.expiresAt))
289
- return Promise.reject(new sii_error_1.SiiError('SII_PREPARATION_UNAVAILABLE'));
290
- if (input.approvedHash !== prepared.public.contentHash)
291
- return Promise.reject(new sii_error_1.SiiError('SII_APPROVAL_MISMATCH'));
292
- if (typeof input.claveFirma !== 'string' || !input.claveFirma || input.claveFirma.length > 256 || typeof input.beforeSend !== 'function')
293
- return Promise.reject(new TypeError('Clave de firma o persistencia previa inválida'));
294
- this.#assertReady();
295
- return this.#writeOperation(async () => {
296
- this.#prepared = undefined;
297
- let sendStarted = false;
298
- try {
299
- const page = await this.#portal('mipeGenXMLFirma.cgi', prepared.fields);
300
- const fields = this.#form(page, 'frmSign', 'mipeSendXML.cgi');
301
- const folio = fields.get('EFXP_FOLIO') ?? '';
302
- if (!/^[1-9]\d{0,19}$/.test(folio))
303
- throw this.#failure('SII_SIGNATURE_INVALID', 'mipeGenXMLFirma.cgi', 'INVALID_RESPONSE');
304
- const plain = fields.get('txtPlainText') ?? '';
305
- const expected = { issuerRut: prepared.public.issuerRut, receiverRut: prepared.public.receiverRut, documentType: prepared.public.documentType, folio };
306
- let unsigned;
307
- try {
308
- unsigned = (0, invoice_xml_2.parseDteDocumentXml)((0, facturador_1.encodeUnsignedDteXml)(plain), expected);
309
- }
310
- catch {
311
- throw this.#failure('SII_SIGNATURE_INVALID', 'mipeGenXMLFirma.cgi', 'INVALID_XML');
312
- }
313
- this.#assertDocument(unsigned, prepared.public);
314
- const identity = this.#assertReady();
315
- const certificatePage = await this.#portal('getCertDigital.cgi', undefined, `?rut=${identity.rut}&dv=${identity.dv}`);
316
- let certs;
317
- try {
318
- certs = JSON.parse(certificatePage);
319
- }
320
- catch {
321
- throw this.#failure('SII_CERTIFICATE_UNAVAILABLE', 'getCertDigital.cgi', 'CERTIFICATE_UNAVAILABLE');
322
- }
323
- if (!Array.isArray(certs) || certs.length !== 1 || !isRecord(certs[0]) || typeof certs[0].nombre !== 'string' || !certs[0].nombre || certs[0].nombre.length > 256)
324
- throw this.#failure('SII_CERTIFICATE_UNAVAILABLE', 'getCertDigital.cgi', 'CERTIFICATE_UNAVAILABLE');
325
- const signing = new URLSearchParams({ nombre: certs[0].nombre, dato: plain, rut: identity.rut, dv: identity.dv, clave: input.claveFirma, nodo: 'dte:DTE', nodoId: 'dte:Documento', nameSpace: 'http://www.sii.cl/SiiDte' });
326
- const response = await this.#request(`${FACTURADOR}postFirmaDigital.cgi`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', Referer: `${FACTURADOR}mipeGenXMLFirma.cgi` }, body: signing.toString() });
327
- const signedBytes = await this.#readBounded(response, 'postFirmaDigital.cgi');
328
- if (!signedBytes.length)
329
- throw this.#failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'EMPTY_RESPONSE', response);
330
- let signed;
331
- try {
332
- signed = (0, invoice_xml_2.parseDteDocumentXml)(signedBytes, expected);
333
- }
334
- catch {
335
- const text = (0, facturador_1.readPortalHtml)(signedBytes);
336
- const reason = /clave no corresponde/i.test(text) ? 'CERTIFICATE_PASSWORD_INVALID' : /expirado/i.test(text) ? 'CERTIFICATE_EXPIRED' : /revocado/i.test(text) ? 'CERTIFICATE_REVOKED' : 'SIGNATURE_INVALID';
337
- throw this.#failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', reason, response);
338
- }
339
- this.#assertDocument(signed, prepared.public);
340
- if (!signed.detail.hasSignature)
341
- throw this.#failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'SIGNATURE_INVALID', response);
342
- const document = { ...signed, ...expected, issuedDate: prepared.public.issuedDate, contentHash: prepared.public.contentHash };
343
- await input.beforeSend(structuredClone(document));
344
- fields.set('txtSignText', Buffer.from(signed.xml).toString(signed.encoding === 'UTF-8' ? 'utf8' : 'latin1'));
345
- fields.set('nombre', certs[0].nombre);
346
- fields.set('clave', input.claveFirma);
347
- fields.set('nodo', 'dte:DTE');
348
- fields.set('nodoId', 'dte:Documento');
349
- fields.set('nameSpace', 'http://www.sii.cl/SiiDte');
350
- const body = (0, facturador_1.encodePortalForm)(fields);
351
- sendStarted = true;
352
- const sent = await this.#portal('mipeSendXML.cgi', body);
353
- if (!/DOCUMENTO\s+TRIBUTARIO\s+ELECTR[ÓO]NICO\s+ENVIADO\s+EXITOSAMENTE/i.test((0, facturador_1.readVisiblePortalText)(sent)))
354
- throw this.#failure('SII_ISSUANCE_OUTCOME_UNKNOWN', 'mipeSendXML.cgi', 'ISSUANCE_OUTCOME_UNKNOWN');
355
- return { ...document, status: 'ENVIADO' };
356
- }
357
- catch (error) {
358
- if (sendStarted)
359
- throw this.#failure('SII_ISSUANCE_OUTCOME_UNKNOWN', 'mipeSendXML.cgi', 'ISSUANCE_OUTCOME_UNKNOWN');
360
- throw error;
361
- }
362
- }).finally(() => this.dispose());
363
- }
364
- #writeOperation(action) {
365
- if (this.#write)
366
- return Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS'));
367
- const promise = action();
368
- this.#write = promise;
369
- void promise.then(() => { this.#write = undefined; }, () => { this.#write = undefined; });
370
- return promise;
371
- }
372
- #keepPreparation(content, fields) {
373
- const result = Object.freeze({ ...content, preparacionId: (0, node_crypto_1.randomUUID)(), contentHash: (0, invoicing_1.hashContent)(content), expiresAt: new Date(Date.now() + 300_000).toISOString() });
374
- const freeze = (value) => { if (value && typeof value === 'object') {
375
- for (const child of Object.values(value))
376
- freeze(child);
377
- Object.freeze(value);
378
- } };
379
- freeze(result);
380
- this.#prepared = { public: result, fields };
381
- return result;
382
- }
383
- async #portal(endpoint, fields, query = '') {
384
- const response = await this.#request(`${FACTURADOR}${endpoint}${query}`, fields === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Referer: `${FACTURADOR}${endpoint}` }, body: typeof fields === 'string' ? fields : (0, facturador_1.encodePortalForm)(fields) });
385
- const bytes = await this.#readBounded(response, endpoint);
386
- if (!bytes.length) {
387
- if (endpoint === 'mipeSelEmpresa.cgi')
388
- return '';
389
- throw this.#failure('SII_INVALID_RESPONSE', endpoint, 'EMPTY_RESPONSE', response);
390
- }
391
- const page = (0, facturador_1.readPortalHtml)(bytes);
392
- if (endpoint === 'mipeDisplayPreView.cgi' && /Redireccionando/i.test(page) && /\balert\s*\(/.test(page) && /(?:window\.)?history\.go\(\s*-1\s*\)/.test(page))
393
- throw this.#failure('SII_DOCUMENT_VALIDATION_REJECTED', endpoint, 'PROVIDER_REJECTED', response);
394
- const loginForm = htmlElements((0, parse5_1.parse)(page)).some(element => element.tagName === 'form' && /(?:^|\/)CAutInicio\.cgi(?:[?#]|$)/i.test(element.attrs.find(a => a.name === 'action')?.value ?? '') && htmlElements(element).some(control => control.tagName === 'input' && control.attrs.some(a => a.name === 'name' && a.value.toLowerCase() === 'clave')));
395
- if (loginForm)
396
- throw this.#failure('SESSION_REQUIRED', endpoint, 'SESSION_REQUIRED', response);
397
- if (/Error\s+al\s+Contribuyente/i.test(page))
398
- throw this.#failure('SII_SERVICE_ERROR', endpoint, 'PROVIDER_ERROR_PAGE', response, { ...(page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)?.[0] ? { siiMessageCode: page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)[0] } : {}) });
399
- return page;
400
- }
401
- #form(page, name, endpoint, alternative) {
402
- try {
403
- return (0, facturador_1.readForm)(page, name, endpoint);
404
- }
405
- catch {
406
- if (alternative) {
407
- try {
408
- return (0, facturador_1.readForm)(page, name, alternative);
409
- }
410
- catch { /* Only known form actions are allowed. */ }
411
- }
412
- const source = name === 'VIEW_EFXP' ? 'mipeGenFacEx.cgi' : name === 'PreViewDTE' ? 'mipeDisplayPreView.cgi' : 'mipeGenXMLFirma.cgi';
413
- throw this.#failure('SII_PROTOCOL_CHANGED', source, 'INVALID_RESPONSE');
414
- }
415
- }
416
- #assertOption(page, variable, value, commune, column = 0) {
417
- try {
418
- const rows = (0, facturador_1.readLiteralRows)(page, variable).filter(row => row[column]?.trim() === value && (commune === undefined || row[1]?.trim() === commune));
419
- if (rows.length === 1 && rows[0])
420
- return rows[0];
421
- }
422
- catch { /* No provider scripts execute. */ }
423
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
424
- }
425
- #assertFields(fields, expected) {
426
- for (const [key, value] of Object.entries(expected))
427
- if (fields.get(key)?.trim() !== value)
428
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
429
- }
430
- #assertNewInvoice(fields) {
431
- if (fields.get('PTDC_CODIGO') !== '33' || fields.get('EHDR_CODIGO')?.trim() || fields.get('EFXP_FOLIO')?.trim() || fields.get('ES_BORR')?.toUpperCase() !== 'FALSE' || fields.get('esCRED_EC')?.toUpperCase() !== 'FALSE' || fields.get('esFACT_TUR')?.toUpperCase() !== 'FALSE')
432
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
433
- }
434
- #assertDocument(document, approved) {
435
- const d = document.detail;
436
- const decimal = (value) => value == null ? null : value.replace(/^0+(?=\d)/, '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
437
- if (d.issuedDate !== approved.issuedDate || d.netAmount !== approved.netAmount || d.vatAmount !== approved.vatAmount || d.totalAmount !== approved.totalAmount || Number(d.vatRate) !== 19 || d.taxes.length || d.adjustments.length || d.exemptAmount || d.fiscalHeader?.noDebitReduction != null || d.fiscalHeader?.unapprovedFiscalFields.length)
438
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
439
- if (approved.invoice) {
440
- const items = approved.invoice.items;
441
- const header = d.fiscalHeader;
442
- const i = approved.invoice;
443
- const branch = (value) => (value ?? '').replace(/^0+(?=\d)/, '');
444
- if (branch(header?.issuer.branchCode) !== branch(approved.issuerBranchCode))
445
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
446
- if (!header || header.issuer.legalName !== approved.issuerLegalName || header.issuer.businessActivity !== approved.issuerBusinessActivity || header.issuer.address !== i.issuer.address || header.issuer.commune !== i.issuer.commune || header.issuer.city !== i.issuer.city || header.issuer.activityCode !== i.issuer.activityCode || header.receiver.legalName !== i.receiver.legalName || header.receiver.businessActivity !== i.receiver.businessActivity || header.receiver.address !== i.receiver.address || header.receiver.commune !== i.receiver.commune || header.receiver.city !== i.receiver.city || (header.receiver.contact ?? '') !== (i.receiver.contact ?? '') || header.paymentForm !== i.paymentForm || header.saleType !== i.saleType || header.purchaseType !== i.purchaseType)
447
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
448
- if (d.hasTransport || d.lines.length !== items.length || d.references.length || d.lines.some((line, i) => line.codes.length || line.name !== items[i]?.name || (line.description ?? '') !== (items[i]?.description ?? '') || decimal(line.quantity) !== decimal(items[i]?.quantity ?? null) || decimal(line.unitPrice) !== decimal(items[i]?.unitNetPriceClp ?? null) || (line.unit ?? '') !== (items[i]?.unit ?? '') || line.amount !== (0, invoicing_1.calculateInvoiceTotals)([items[i]]).netAmount || line.discountAmount || line.surchargeAmount || line.discountPercent && Number(line.discountPercent) || line.surchargePercent && Number(line.surchargePercent) || line.exemptIndicator))
449
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
450
- }
451
- else {
452
- const ref = d.references[0];
453
- if (!approved.reference || d.references.length !== 1 || ref?.documentType !== '33' || ref.folio !== approved.reference.folio || ref.date !== approved.reference.issuedDate || ref.code !== 1)
454
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
455
- const original = approved.originalInvoice;
456
- const header = d.fiscalHeader;
457
- const originalHeader = original?.fiscalHeader;
458
- const lines = (values) => values.map(line => ({ ...line, quantity: decimal(line.quantity), unitPrice: decimal(line.unitPrice), discountPercent: decimal(line.discountPercent), surchargePercent: decimal(line.surchargePercent) }));
459
- if (!original || !header || !originalHeader || (0, invoicing_1.hashContent)(lines(d.lines)) !== (0, invoicing_1.hashContent)(lines(original.lines)) || (0, invoicing_1.hashContent)(header.issuer) !== (0, invoicing_1.hashContent)(originalHeader.issuer) || (0, invoicing_1.hashContent)(header.receiver) !== (0, invoicing_1.hashContent)(originalHeader.receiver) || ['paymentForm', 'saleType', 'purchaseType'].some(field => header[field] !== null && header[field] !== originalHeader[field]))
460
- throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
461
- }
462
- }
463
- async #getInvoices(operacion, { periodo, tokenRecaptcha = 't-o-k-e-n-web' }, normalize) {
464
- this.#assertReady();
465
- assertPeriod(periodo);
466
- if (typeof tokenRecaptcha !== 'string' || !tokenRecaptcha.trim())
467
- throw new TypeError('tokenRecaptcha inválido');
468
- const initial = await this.#call('getDatosInicio', {});
469
- if (typeof initial.limiteDtes !== 'number' || !Number.isSafeInteger(initial.limiteDtes) || initial.limiteDtes < 1)
470
- throw this.#failure('SII_INVALID_RESPONSE', 'getDatosInicio', 'INVALID_RESPONSE');
471
- const summary = await this.getSummary({ periodo, operacion });
472
- const expected = new Map();
473
- let expectedCount = 0;
474
- for (const row of summary.data) {
475
- const type = row.rsmnTipoDocInteger;
476
- if (typeof type !== 'number' || !Number.isSafeInteger(type) || type < 1)
477
- throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
478
- if (type !== 33 && type !== 34)
479
- continue;
480
- const count = row.rsmnTotDoc;
481
- if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0 || (expected.has(type) && expected.get(type) !== count))
482
- throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
483
- if (!expected.has(type))
484
- expectedCount += count;
485
- if (!Number.isSafeInteger(expectedCount))
486
- throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
487
- expected.set(type, count);
488
- }
489
- const invoices = new Map();
490
- const incompleteDocumentTypes = [];
491
- for (const [type, count] of expected) {
492
- if (count === 0)
493
- continue;
494
- const method = operacion === 'COMPRA' ? 'getDetalleCompra' : 'getDetalleVenta';
495
- const details = await this.#call(method, {
496
- rutEmisor: this.#company.rut, dvEmisor: this.#company.dv, ptributario: periodo,
497
- codTipoDoc: String(type), operacion: operacion === 'COMPRA' ? 'COMPRA' : '', estadoContab: operacion === 'COMPRA' ? 'REGISTRO' : '', accionRecaptcha: operacion === 'COMPRA' ? 'RCV_DETC' : 'RCV_DETV', tokenRecaptcha,
498
- });
499
- let uniqueCount = 0;
500
- for (const row of details.data) {
501
- let invoice;
502
- try {
503
- invoice = normalize(row, this.#company.formatted, periodo, type);
504
- }
505
- catch {
506
- throw this.#failure('SII_INVALID_RESPONSE', method, 'INVALID_RESPONSE');
507
- }
508
- const key = `${invoice.issuerRut}:${invoice.documentType}:${invoice.folio}`;
509
- const previous = invoices.get(key);
510
- if (previous && JSON.stringify(previous) !== JSON.stringify(invoice))
511
- throw this.#failure('SII_INVALID_RESPONSE', method, 'INVALID_RESPONSE');
512
- if (!previous) {
513
- invoices.set(key, invoice);
514
- uniqueCount++;
515
- }
516
- }
517
- if (count > initial.limiteDtes || uniqueCount !== count)
518
- incompleteDocumentTypes.push(type);
519
- }
520
- return { data: [...invoices.values()], complete: incompleteDocumentTypes.length === 0, expectedCount, observedAt: new Date().toISOString(), incompleteDocumentTypes };
521
- }
522
- /** Original DTE from the free SII facturador; RCV membership alone does not guarantee XML availability. */
523
- getIssuedInvoiceXml(input) {
524
- if (![33, 34].includes(input.documentType))
525
- return Promise.reject(new TypeError('Identidad de factura inválida'));
526
- return this.#getInvoiceXml(input);
527
- }
528
- getReceivedInvoiceXml(input) {
529
- if (![33, 34].includes(input.documentType))
530
- return Promise.reject(new TypeError('Identidad de factura inválida'));
531
- return this.#getInvoiceXml(input, (0, rut_1.parseRut)(input.issuerRut));
532
- }
533
- getIssuedDocumentXml(input) {
534
- return this.#getDocumentXml(input);
535
- }
536
56
  /** @deprecated Use getAuthorizedCompanies. */
537
57
  getEmpresasAutorizadas() { return this.getAuthorizedCompanies(); }
538
58
  /** @deprecated Use getSummary. */
@@ -553,254 +73,5 @@ class SiiClient {
553
73
  prepararNotaCreditoAnulacion(input) { return this.prepareCancellationCreditNote(input); }
554
74
  /** @deprecated Use signAndSend. */
555
75
  firmarYEnviar(input) { return this.signAndSend(input); }
556
- #getInvoiceXml(input, supplier) {
557
- return this.#getDocumentXml(input, supplier, true);
558
- }
559
- async #getDocumentXml({ documentType, folio }, supplier, legacy = false) {
560
- this.#assertReady();
561
- if (![33, 34, 61].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
562
- throw new TypeError('Identidad de documento inválida');
563
- await this.#ensureInvoicingPortal();
564
- // A filtered backup is a read: no emission, cancellation or representation endpoint is called.
565
- const query = new URLSearchParams({ ORIGEN: supplier ? 'RCP' : 'ENV', ...(supplier ? { RUT_EMI: supplier.rut } : { RUT_RECP: '' }), FOLIO: folio, RZN_SOC: '', FEC_DESDE: '', FEC_HASTA: '', TPO_DOC: String(documentType), ESTADO: '', ORDEN: '', DOWNLOAD: 'XML' });
566
- const response = await this.#request(`${FACTURADOR}mipeDownLoad.cgi?${query}`, {}, true);
567
- const bytes = await this.#readBounded(response, 'mipeDownLoad.cgi');
568
- const format = responseFormat(response, bytes);
569
- if (format.responseType === 'EMPTY')
570
- throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', 'EMPTY_RESPONSE', response, format);
571
- if (format.responseType === 'PDF' || format.responseType === 'ZIP')
572
- throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', format.responseType === 'PDF' ? 'UNEXPECTED_PDF' : 'UNEXPECTED_ARCHIVE', response, format);
573
- if (format.responseType !== 'XML' && !(format.responseType === 'UNKNOWN' && format.contentType === 'application/octet-stream')) {
574
- const page = Buffer.from(bytes).toString('latin1');
575
- const siiMessageCode = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)?.[0];
576
- const evidence = { ...format, ...(siiMessageCode ? { siiMessageCode } : {}) };
577
- if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
578
- throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', 'mipeDownLoad.cgi', 'CAPTCHA_REQUIRED', response, evidence);
579
- const reason = /demasiados\s+documentos/i.test(page) ? 'DOCUMENT_LIMIT_EXCEEDED'
580
- : /no\s+se\s+encontraron\s+documentos/i.test(page) ? 'DOCUMENT_NOT_FOUND'
581
- : /error\s+al\s+contribuyente/i.test(page) ? 'PROVIDER_ERROR_PAGE'
582
- : format.responseType === 'HTML' ? 'HTML_RESPONSE' : 'UNEXPECTED_FORMAT';
583
- throw this.#failure(reason === 'DOCUMENT_NOT_FOUND' ? 'SII_XML_UNAVAILABLE' : 'SII_SERVICE_ERROR', 'mipeDownLoad.cgi', reason, response, evidence);
584
- }
585
- try {
586
- const identity = { issuerRut: supplier?.formatted ?? this.#company.formatted, ...(supplier ? { receiverRut: this.#company.formatted } : {}), folio };
587
- if (legacy) {
588
- if (documentType !== 33 && documentType !== 34)
589
- throw new invoice_xml_1.DteXmlError('SII_XML_INVALID');
590
- return (0, invoice_xml_1.parseDteXml)(bytes, { ...identity, documentType });
591
- }
592
- return (0, invoice_xml_2.parseDteDocumentXml)(bytes, { ...identity, documentType });
593
- }
594
- catch (error) {
595
- const code = error instanceof invoice_xml_1.DteXmlError ? error.code : 'SII_XML_INVALID';
596
- throw this.#failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, { ...format, stage: 'XML_PARSE' });
597
- }
598
- }
599
- async #ensureInvoicingPortal(destination = FACTURADOR_DESTINATION) {
600
- if (!this.#facturadorReady || destination !== FACTURADOR_DESTINATION) {
601
- let url = `${FACTURADOR}mipeSelEmpresa.cgi?DESDE_DONDE_URL=${encodeURIComponent(destination)}`;
602
- let options = {}, submitted = false;
603
- for (let hop = 0;; hop++) {
604
- const response = await this.#request(url, options, destination === FACTURADOR_DESTINATION && options.method !== 'POST', true);
605
- const location = response.headers.get('location');
606
- if (response.status >= 300 && response.status < 400) {
607
- await response.body?.cancel();
608
- if (!location || hop >= 4)
609
- throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
610
- const next = new URL(location, url);
611
- if (next.origin !== 'https://www1.sii.cl' || !['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeGenFacEx.cgi', 'mipeAdminDocsEmi.cgi'].some(path => next.pathname === `/cgi-bin/Portal001/${path}`))
612
- throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpointFor(url), 'SESSION_REQUIRED', response);
613
- url = next.href;
614
- options = {};
615
- continue;
616
- }
617
- const page = response.body ? Buffer.from(await this.#readBounded(response, endpointFor(url))).toString('latin1') : '';
618
- if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
619
- throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', endpointFor(url), 'CAPTCHA_REQUIRED', response);
620
- const selection = companySelection(page, this.#company.formatted, destination);
621
- if (typeof selection === 'string')
622
- throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), selection, response);
623
- if (selection) {
624
- if (submitted || hop >= 4)
625
- throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
626
- submitted = true;
627
- url = `${FACTURADOR}mipeSelEmpresa.cgi`;
628
- options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: selection.toString() };
629
- continue;
630
- }
631
- break;
632
- }
633
- const cookies = await this.#jar.getCookies(FACTURADOR);
634
- if (cookies.find(c => c.key === 'NETSCAPE_LIVEWIRE.rcmp')?.value !== this.#company.rut || cookies.find(c => c.key === 'NETSCAPE_LIVEWIRE.dcmp')?.value.toUpperCase() !== this.#company.dv)
635
- throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', 'mipeSelEmpresa.cgi', 'COMPANY_SELECTION_REQUIRED');
636
- this.#facturadorReady = true;
637
- }
638
- }
639
- /** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
640
- dispose() {
641
- if (this.#disposal)
642
- return this.#disposal;
643
- this.#closed = true;
644
- this.#ready = false;
645
- this.#identity = undefined;
646
- this.#facturadorReady = false;
647
- this.#prepared = undefined;
648
- this.#disposal = (async () => {
649
- try {
650
- // An in-flight login can still issue session cookies after local closure.
651
- await Promise.allSettled([...this.#requests, ...(this.#write ? [this.#write] : [])]);
652
- const cookies = await this.#jar.getCookies(LOGOUT);
653
- if (!cookies.some(c => c.value && ['TOKEN', 'NETSCAPE_LIVEWIRE.mac'].includes(c.key)))
654
- return;
655
- const headers = new Headers({ Referer: RCV, Cookie: cookies.map(c => c.cookieString()).join('; ') });
656
- const response = await this.#fetch(LOGOUT, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
657
- if (!response.ok) {
658
- await response.body?.cancel();
659
- if (!(response.status >= 300 && response.status < 400 && response.headers.get('location') === 'https://homer.sii.cl/'))
660
- throw new sii_error_1.SiiError('SII_LOGOUT_FAILED');
661
- }
662
- else {
663
- const page = Buffer.from(await this.#readBounded(response, 'autTermino.cgi')).toString('latin1');
664
- const codes = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/g);
665
- // Observed 2026-10-01: this code means the remote session is already absent.
666
- if (codes?.some(code => code !== '01.01.205.529.269.28'))
667
- throw new sii_error_1.SiiError('SII_LOGOUT_FAILED');
668
- }
669
- }
670
- catch {
671
- // Preserve the operation's original error; expose cleanup failure without secrets.
672
- process.emitWarning('SII_LOGOUT_FAILED', { code: 'SII_LOGOUT_FAILED' });
673
- }
674
- finally {
675
- await this.#jar.removeAllCookies();
676
- }
677
- })();
678
- return this.#disposal;
679
- }
680
- #assertReady() {
681
- if (!this.#ready || this.#closed || !this.#identity)
682
- throw new sii_error_1.SiiError('SESSION_REQUIRED');
683
- return this.#identity;
684
- }
685
- async #call(method, data) {
686
- const token = (await this.#jar.getCookies(RCV)).find(c => c.key === 'TOKEN')?.value;
687
- if (!token)
688
- throw this.#failure('SESSION_REQUIRED', method, 'SESSION_REQUIRED');
689
- const response = await this.#request(`${RCV}services/data/facadeService/${method}`, {
690
- method: 'POST',
691
- headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/plain, */*', Referer: RCV },
692
- body: JSON.stringify({ metaData: { namespace: NAMESPACE + method, conversationId: token, transactionId: (0, node_crypto_1.randomUUID)(), page: null }, data }),
693
- }, true);
694
- const result = await this.#json(response, method);
695
- if (!isRecord(result))
696
- throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
697
- const status = result.respEstado;
698
- const rawMeta = result.metaData ?? {};
699
- if (!isRecord(status) || !isRecord(rawMeta) || (rawMeta.errors != null && !Array.isArray(rawMeta.errors))) {
700
- throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
701
- }
702
- if (status.codRespuesta === 98)
703
- throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', method, 'CAPTCHA_REQUIRED', response, { siiResponseCode: 98 });
704
- // RCV shows "No hay información" for this empty-summary response (observed 2026-10-01).
705
- const emptySummary = method === 'getResumen' && status.codRespuesta === 3 && status.codError == null && result.data === null;
706
- if ((!emptySummary && status.codRespuesta !== 0) || (Array.isArray(rawMeta.errors) && rawMeta.errors.length))
707
- throw this.#failure('SII_SERVICE_ERROR', method, 'PROVIDER_REJECTED', response, { ...(typeof status.codRespuesta === 'number' ? { siiResponseCode: status.codRespuesta } : {}) });
708
- const rows = emptySummary ? [] : result.data;
709
- if (!Array.isArray(rows) || !rows.every(isRecord))
710
- throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
711
- const { conversationId: _secret, ...metaData } = rawMeta;
712
- return { ...result, data: rows, metaData };
713
- }
714
- async #json(response, endpoint) {
715
- if (!response.headers.get('content-type')?.toLowerCase().includes('json')) {
716
- await response.body?.cancel();
717
- throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpoint, 'SESSION_REQUIRED', response);
718
- }
719
- try {
720
- return await response.json();
721
- }
722
- catch {
723
- throw this.#failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
724
- }
725
- }
726
- async #readBounded(response, endpoint) {
727
- const reader = response.body?.getReader();
728
- if (!reader)
729
- throw this.#failure('SII_XML_UNAVAILABLE', endpoint, 'EMPTY_RESPONSE', response, { responseType: 'EMPTY' });
730
- let size = 0;
731
- const chunks = [];
732
- try {
733
- for (;;) {
734
- const { done, value } = await reader.read();
735
- if (done)
736
- break;
737
- size += value.byteLength;
738
- if (size > invoice_xml_1.MAX_DTE_XML_BYTES) {
739
- await reader.cancel();
740
- throw this.#failure('SII_XML_INVALID', endpoint, 'RESPONSE_TOO_LARGE', response);
741
- }
742
- chunks.push(value);
743
- }
744
- return Buffer.concat(chunks, size);
745
- }
746
- catch (error) {
747
- throw error instanceof sii_error_1.SiiError ? error : this.#failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response);
748
- }
749
- finally {
750
- reader.releaseLock();
751
- }
752
- }
753
- #request(url, options = {}, canRetry = false, allowRedirect = false) {
754
- const request = this.#sendRequest(url, options, canRetry, allowRedirect);
755
- this.#requests.add(request);
756
- void request.then(() => this.#requests.delete(request), () => this.#requests.delete(request));
757
- return request;
758
- }
759
- async #sendRequest(url, options, canRetry, allowRedirect) {
760
- const endpoint = endpointFor(url);
761
- for (let attempt = 0;; attempt++) {
762
- if (this.#closed)
763
- throw new sii_error_1.SiiError('CLIENT_CLOSED');
764
- const headers = new Headers(options.headers);
765
- const cookie = await this.#jar.getCookieString(url);
766
- if (this.#closed)
767
- throw new sii_error_1.SiiError('CLIENT_CLOSED');
768
- if (cookie)
769
- headers.set('Cookie', cookie);
770
- let response;
771
- try {
772
- response = await this.#fetch(url, { ...options, headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
773
- }
774
- catch (error) {
775
- if (!canRetry || attempt >= this.#retries)
776
- throw this.#failure('SII_TRANSPORT_ERROR', endpoint, error instanceof Error && error.name === 'TimeoutError' ? 'TIMEOUT' : 'TRANSPORT_ERROR', undefined, { attempts: attempt + 1 });
777
- await (0, promises_1.setTimeout)(250 * (attempt + 1));
778
- continue;
779
- }
780
- for (const setCookie of response.headers.getSetCookie()) {
781
- await this.#jar.setCookie(setCookie, url, { ignoreError: true });
782
- }
783
- if (this.#closed) {
784
- await response.body?.cancel();
785
- throw new sii_error_1.SiiError('CLIENT_CLOSED');
786
- }
787
- if (canRetry && RETRYABLE.has(response.status) && attempt < this.#retries) {
788
- const retryAfter = response.headers.get('retry-after');
789
- const seconds = retryAfter === null ? NaN : Number(retryAfter);
790
- const waitMs = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : Date.parse(retryAfter ?? '') - Date.now();
791
- await response.body?.cancel();
792
- if (Number.isFinite(waitMs) && waitMs > 5000)
793
- throw this.#failure('SII_RETRY_LATER', endpoint, 'RETRY_LATER', response, { attempts: attempt + 1 });
794
- await (0, promises_1.setTimeout)(Number.isFinite(waitMs) ? Math.max(0, waitMs) : 250 * (attempt + 1));
795
- continue;
796
- }
797
- if (!response.ok && !(allowRedirect && response.status >= 300 && response.status < 400)) {
798
- await response.body?.cancel();
799
- const redirect = response.status >= 300 && response.status < 400;
800
- throw this.#failure(redirect ? 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' : 'SII_HTTP_ERROR', endpoint, redirect ? 'SESSION_REQUIRED' : 'HTTP_ERROR', response, { attempts: attempt + 1 });
801
- }
802
- return response;
803
- }
804
- }
805
76
  }
806
77
  exports.SiiClient = SiiClient;