@devly-cl/sii-client 0.4.4 → 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.
- package/README.md +118 -26
- package/dist/application/invoice-queries.d.ts +17 -0
- package/dist/application/invoice-queries.js +51 -0
- package/dist/application/issuance.d.ts +40 -0
- package/dist/application/issuance.js +79 -0
- package/dist/contracts.d.ts +66 -0
- package/dist/contracts.js +2 -0
- package/dist/domain/document.d.ts +47 -0
- package/dist/domain/document.js +38 -0
- package/dist/domain/invoice-xml.d.ts +58 -11
- package/dist/domain/invoice-xml.js +0 -138
- package/dist/domain/invoicing.d.ts +52 -0
- package/dist/domain/invoicing.js +157 -0
- package/dist/domain/issued-invoice.d.ts +16 -9
- package/dist/domain/issued-invoice.js +4 -43
- package/dist/domain/received-invoice.d.ts +11 -7
- package/dist/domain/received-invoice.js +0 -10
- package/dist/domain/sii-error.d.ts +3 -3
- package/dist/domain/sii-error.js +10 -4
- package/dist/index.d.ts +13 -3
- package/dist/index.js +12 -3
- package/dist/infrastructure/dte-xml.d.ts +11 -0
- package/dist/infrastructure/dte-xml.js +173 -0
- package/dist/infrastructure/facturador-gateway.d.ts +28 -0
- package/dist/infrastructure/facturador-gateway.js +411 -0
- package/dist/infrastructure/facturador.d.ts +18 -0
- package/dist/infrastructure/facturador.js +231 -0
- package/dist/infrastructure/invoice-pdf.d.ts +9 -0
- package/dist/infrastructure/invoice-pdf.js +171 -0
- package/dist/infrastructure/rcv-gateway.d.ts +17 -0
- package/dist/infrastructure/rcv-gateway.js +105 -0
- package/dist/infrastructure/rcv-normalization.d.ts +6 -0
- package/dist/infrastructure/rcv-normalization.js +55 -0
- package/dist/infrastructure/sii-client.d.ts +52 -54
- package/dist/infrastructure/sii-client.js +66 -487
- package/dist/infrastructure/sii-http-session.d.ts +25 -0
- package/dist/infrastructure/sii-http-session.js +344 -0
- package/dist/sii-error.d.ts +27 -0
- package/dist/sii-error.js +86 -0
- package/package.json +4 -4
|
@@ -1,498 +1,77 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.SiiClient = exports.SiiError = void 0;
|
|
4
|
-
const
|
|
5
|
-
const
|
|
6
|
-
const
|
|
7
|
-
const
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
var sii_error_2 = require("../
|
|
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
|
-
|
|
13
|
-
const received_invoice_1 = require("../domain/received-invoice");
|
|
14
|
-
const invoice_xml_1 = require("../domain/invoice-xml");
|
|
15
|
-
const AUTH = 'https://zeusr.sii.cl/cgi_AUT2000/CAutInicio.cgi';
|
|
16
|
-
const LOGOUT = 'https://zeusr.sii.cl/cgi_AUT2000/autTermino.cgi';
|
|
17
|
-
const RCV = 'https://www4.sii.cl/consdcvinternetui/';
|
|
18
|
-
const SESSION = 'https://www4.sii.cl/common-1.0/services/aaSessionService/load';
|
|
19
|
-
const NAMESPACE = 'cl.sii.sdi.lob.diii.consdcv.data.api.interfaces.FacadeService/';
|
|
20
|
-
const RETRYABLE = new Set([429, 502, 503, 504]);
|
|
21
|
-
const STATES = new Set(['REGISTRO', 'PENDIENTE', 'NO_INCLUIR', 'RECLAMADO']);
|
|
22
|
-
const FACTURADOR = 'https://www1.sii.cl/cgi-bin/Portal001/';
|
|
23
|
-
const FACTURADOR_DESTINATION = 'OPCION=2&TIPO=4';
|
|
24
|
-
const ENDPOINT_STAGES = {
|
|
25
|
-
'CAutInicio.cgi': 'AUTHENTICATION', 'aaSessionService/load': 'SESSION_CHECK', getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
|
|
26
|
-
getDatosInicio: 'RCV_INITIALIZATION', getResumen: 'RCV_SUMMARY', getDetalleCompra: 'RCV_DETAIL', getDetalleVenta: 'RCV_DETAIL',
|
|
27
|
-
'mipeSelEmpresa.cgi': 'XML_COMPANY_SELECTION', 'mipeLaunchPage.cgi': 'XML_COMPANY_SELECTION', 'mipeDownLoad.cgi': 'XML_DOWNLOAD', 'autTermino.cgi': 'LOGOUT',
|
|
28
|
-
};
|
|
29
|
-
function endpointFor(url) {
|
|
30
|
-
const path = new URL(url).pathname;
|
|
31
|
-
const endpoint = path.endsWith('/aaSessionService/load') ? 'aaSessionService/load' : path.slice(path.lastIndexOf('/') + 1);
|
|
32
|
-
if (!Object.hasOwn(ENDPOINT_STAGES, endpoint))
|
|
33
|
-
throw new TypeError('Endpoint SII desconocido');
|
|
34
|
-
return endpoint;
|
|
35
|
-
}
|
|
36
|
-
function responseFormat(response, bytes) {
|
|
37
|
-
const contentType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
|
|
38
|
-
const prefix = bytes ? Buffer.from(bytes.subarray(0, 512)).toString('latin1').trimStart() : '';
|
|
39
|
-
const responseType = bytes?.length === 0 ? 'EMPTY'
|
|
40
|
-
: prefix.startsWith('%PDF-') ? 'PDF'
|
|
41
|
-
: bytes && bytes[0] === 0x50 && bytes[1] === 0x4b && [0x03, 0x05, 0x07].includes(bytes[2] ?? -1) ? 'ZIP'
|
|
42
|
-
: /^(?:<!doctype\s+html|<html|<head|<body|<script|<div)\b/i.test(prefix) ? 'HTML'
|
|
43
|
-
: contentType === 'text/html' ? 'HTML'
|
|
44
|
-
: contentType === 'application/pdf' ? 'PDF'
|
|
45
|
-
: contentType === 'application/zip' ? 'ZIP'
|
|
46
|
-
: contentType?.includes('json') ? 'JSON'
|
|
47
|
-
: /^(?:application|text)\/xml$/.test(contentType ?? '') || /^<(?:\?xml|DTE|EnvioDTE|SetDTE)\b/i.test(prefix) ? 'XML' : 'UNKNOWN';
|
|
48
|
-
// The sanitizer copies only known MIME values.
|
|
49
|
-
return { responseType, ...(contentType ? { contentType: contentType } : {}) };
|
|
50
|
-
}
|
|
51
|
-
function isRecord(value) {
|
|
52
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
53
|
-
}
|
|
54
|
-
function assertPeriod(periodo) {
|
|
55
|
-
if (typeof periodo !== 'string' || !/^\d{4}(0[1-9]|1[0-2])$/.test(periodo) || Number(periodo.slice(0, 4)) < 2017)
|
|
56
|
-
throw new TypeError('Periodo inválido: YYYYMM');
|
|
57
|
-
}
|
|
58
|
-
function htmlElements(root) {
|
|
59
|
-
const pending = [root];
|
|
60
|
-
const elements = [];
|
|
61
|
-
for (let node = pending.pop(); node; node = pending.pop()) {
|
|
62
|
-
if ('tagName' in node && node.namespaceURI === 'http://www.w3.org/1999/xhtml')
|
|
63
|
-
elements.push(node);
|
|
64
|
-
if ('childNodes' in node)
|
|
65
|
-
for (const child of node.childNodes)
|
|
66
|
-
pending.push(child);
|
|
67
|
-
}
|
|
68
|
-
return elements;
|
|
69
|
-
}
|
|
70
|
-
/** Read the observed selector inertly; never execute scripts or forward arbitrary form fields. */
|
|
71
|
-
function companySelection(page, company) {
|
|
72
|
-
const attr = (element, name) => element.attrs.find(a => a.name === name)?.value;
|
|
73
|
-
const forms = htmlElements((0, parse5_1.parse)(page)).filter(e => e.tagName === 'form' && attr(e, 'name') === 'fPrmEmpPOP');
|
|
74
|
-
const form = forms[0];
|
|
75
|
-
if (!form)
|
|
76
|
-
return undefined;
|
|
77
|
-
if (forms.length !== 1 || attr(form, 'method')?.toLowerCase() !== 'post')
|
|
78
|
-
return 'INVALID_RESPONSE';
|
|
79
|
-
try {
|
|
80
|
-
if (new URL(attr(form, 'action') ?? '', FACTURADOR).href !== `${FACTURADOR}mipeSelEmpresa.cgi`)
|
|
81
|
-
return 'INVALID_RESPONSE';
|
|
82
|
-
}
|
|
83
|
-
catch {
|
|
84
|
-
return 'INVALID_RESPONSE';
|
|
85
|
-
}
|
|
86
|
-
const controls = htmlElements(form);
|
|
87
|
-
const selects = controls.filter(e => e.tagName === 'select' && attr(e, 'name') === 'RUT_EMP');
|
|
88
|
-
const destinations = controls.filter(e => e.tagName === 'input' && attr(e, 'name') === 'DESDE_DONDE_URL');
|
|
89
|
-
const select = selects[0], destination = destinations[0];
|
|
90
|
-
if (selects.length !== 1 || destinations.length !== 1 || !select || !destination
|
|
91
|
-
|| attr(select, 'disabled') !== undefined || attr(select, 'multiple') !== undefined || attr(select, 'form') !== undefined
|
|
92
|
-
|| attr(destination, 'type')?.toLowerCase() !== 'hidden' || attr(destination, 'disabled') !== undefined || attr(destination, 'form') !== undefined
|
|
93
|
-
|| attr(destination, 'value') !== FACTURADOR_DESTINATION)
|
|
94
|
-
return 'INVALID_RESPONSE';
|
|
95
|
-
const options = htmlElements(select).filter(e => e.tagName === 'option' && attr(e, 'value')?.replace(/\./g, '').toUpperCase() === company);
|
|
96
|
-
if (options.length > 1)
|
|
97
|
-
return 'INVALID_RESPONSE';
|
|
98
|
-
const option = options[0];
|
|
99
|
-
if (!option || attr(option, 'disabled') !== undefined
|
|
100
|
-
|| (option.parentNode && 'tagName' in option.parentNode && option.parentNode.tagName === 'optgroup' && attr(option.parentNode, 'disabled') !== undefined))
|
|
101
|
-
return 'COMPANY_NOT_AUTHORIZED';
|
|
102
|
-
return new URLSearchParams({ DESDE_DONDE_URL: FACTURADOR_DESTINATION, RUT_EMP: company });
|
|
103
|
-
}
|
|
104
|
-
/** 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. */
|
|
105
13
|
class SiiClient {
|
|
106
|
-
#
|
|
107
|
-
#
|
|
108
|
-
#
|
|
109
|
-
#
|
|
110
|
-
#retries;
|
|
111
|
-
#identity;
|
|
112
|
-
#ready = false;
|
|
113
|
-
#used = false;
|
|
114
|
-
#closed = false;
|
|
115
|
-
#facturadorReady = false;
|
|
116
|
-
#requests = new Set();
|
|
14
|
+
#session;
|
|
15
|
+
#rcv;
|
|
16
|
+
#facturador;
|
|
17
|
+
#issuance;
|
|
117
18
|
#disposal;
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
if (typeof clave !== 'string' || !clave || clave.length > 256)
|
|
140
|
-
throw new TypeError('Clave inválida');
|
|
141
|
-
this.#used = true;
|
|
142
|
-
try {
|
|
143
|
-
const body = new URLSearchParams({ rut: identity.rut, dv: identity.dv, referencia: RCV, '411': '', rutcntr: identity.formatted, clave });
|
|
144
|
-
const response = await this.#request(AUTH, {
|
|
145
|
-
method: 'POST',
|
|
146
|
-
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: 'https://zeusr.sii.cl', Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${RCV}` },
|
|
147
|
-
body: body.toString(),
|
|
148
|
-
});
|
|
149
|
-
await response.body?.cancel();
|
|
150
|
-
const cookies = await this.#jar.getCookies(RCV);
|
|
151
|
-
if (!cookies.some(c => c.key === 'TOKEN' && c.value))
|
|
152
|
-
throw this.#failure('LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', 'LOGIN_NOT_CONFIRMED', response);
|
|
153
|
-
const sessionResponse = await this.#request(SESSION, {}, true);
|
|
154
|
-
const sessionEnvelope = await this.#json(sessionResponse, 'aaSessionService/load');
|
|
155
|
-
const session = isRecord(sessionEnvelope) && isRecord(sessionEnvelope.data) ? sessionEnvelope.data : undefined;
|
|
156
|
-
if (session?.hayRepresentacion !== false)
|
|
157
|
-
throw this.#failure('PERSONAL_SESSION_REQUIRED', 'aaSessionService/load', 'PERSONAL_SESSION_REQUIRED', sessionResponse);
|
|
158
|
-
if (`${session?.rut}-${session?.dv}`.toUpperCase() !== identity.formatted)
|
|
159
|
-
throw this.#failure('SESSION_IDENTITY_MISMATCH', 'aaSessionService/load', 'SESSION_IDENTITY_MISMATCH', sessionResponse);
|
|
160
|
-
this.#identity = identity;
|
|
161
|
-
const companies = await this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
|
|
162
|
-
if (!companies.data.some(c => `${c.usrEmpRut}-${c.usrEmpDv}`.toUpperCase() === this.#company.formatted)) {
|
|
163
|
-
throw this.#failure('COMPANY_NOT_AUTHORIZED', 'getDcvEmpresasAutorizadas', 'COMPANY_NOT_AUTHORIZED');
|
|
164
|
-
}
|
|
165
|
-
if (this.#closed)
|
|
166
|
-
throw new sii_error_1.SiiError('CLIENT_CLOSED');
|
|
167
|
-
this.#ready = true;
|
|
168
|
-
return { usuarioRut: identity.formatted, empresaRut: this.#company.formatted, representacion: false };
|
|
169
|
-
}
|
|
170
|
-
catch (error) {
|
|
171
|
-
await this.dispose();
|
|
172
|
-
throw error;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
async getEmpresasAutorizadas() {
|
|
176
|
-
const identity = this.#assertReady();
|
|
177
|
-
return this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
|
|
178
|
-
}
|
|
179
|
-
async getResumen({ periodo, operacion, estado = 'REGISTRO' }) {
|
|
180
|
-
this.#assertReady();
|
|
181
|
-
assertPeriod(periodo);
|
|
182
|
-
if (!['COMPRA', 'VENTA'].includes(operacion))
|
|
183
|
-
throw new TypeError('Operación inválida');
|
|
184
|
-
if (!STATES.has(estado) || (operacion === 'VENTA' && estado !== 'REGISTRO'))
|
|
185
|
-
throw new TypeError('Estado inválido');
|
|
186
|
-
return this.#call('getResumen', { rutEmisor: this.#company.rut, dvEmisor: this.#company.dv, ptributario: periodo, estadoContab: estado, operacion });
|
|
187
|
-
}
|
|
188
|
-
getFacturasEmitidas(input) {
|
|
189
|
-
return this.#getFacturas('VENTA', input, issued_invoice_1.normalizeIssuedInvoice);
|
|
190
|
-
}
|
|
191
|
-
/** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
|
|
192
|
-
getFacturasRecibidas(input) {
|
|
193
|
-
return this.#getFacturas('COMPRA', input, received_invoice_1.normalizeReceivedInvoice);
|
|
194
|
-
}
|
|
195
|
-
async #getFacturas(operacion, { periodo, tokenRecaptcha = 't-o-k-e-n-web' }, normalize) {
|
|
196
|
-
this.#assertReady();
|
|
197
|
-
assertPeriod(periodo);
|
|
198
|
-
if (typeof tokenRecaptcha !== 'string' || !tokenRecaptcha.trim())
|
|
199
|
-
throw new TypeError('tokenRecaptcha inválido');
|
|
200
|
-
const initial = await this.#call('getDatosInicio', {});
|
|
201
|
-
if (typeof initial.limiteDtes !== 'number' || !Number.isSafeInteger(initial.limiteDtes) || initial.limiteDtes < 1)
|
|
202
|
-
throw this.#failure('SII_INVALID_RESPONSE', 'getDatosInicio', 'INVALID_RESPONSE');
|
|
203
|
-
const summary = await this.getResumen({ periodo, operacion });
|
|
204
|
-
const expected = new Map();
|
|
205
|
-
let expectedCount = 0;
|
|
206
|
-
for (const row of summary.data) {
|
|
207
|
-
const type = row.rsmnTipoDocInteger;
|
|
208
|
-
if (typeof type !== 'number' || !Number.isSafeInteger(type) || type < 1)
|
|
209
|
-
throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
|
|
210
|
-
if (type !== 33 && type !== 34)
|
|
211
|
-
continue;
|
|
212
|
-
const count = row.rsmnTotDoc;
|
|
213
|
-
if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0 || (expected.has(type) && expected.get(type) !== count))
|
|
214
|
-
throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
|
|
215
|
-
if (!expected.has(type))
|
|
216
|
-
expectedCount += count;
|
|
217
|
-
if (!Number.isSafeInteger(expectedCount))
|
|
218
|
-
throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
|
|
219
|
-
expected.set(type, count);
|
|
220
|
-
}
|
|
221
|
-
const invoices = new Map();
|
|
222
|
-
const incompleteDocumentTypes = [];
|
|
223
|
-
for (const [type, count] of expected) {
|
|
224
|
-
if (count === 0)
|
|
225
|
-
continue;
|
|
226
|
-
const method = operacion === 'COMPRA' ? 'getDetalleCompra' : 'getDetalleVenta';
|
|
227
|
-
const details = await this.#call(method, {
|
|
228
|
-
rutEmisor: this.#company.rut, dvEmisor: this.#company.dv, ptributario: periodo,
|
|
229
|
-
codTipoDoc: String(type), operacion: operacion === 'COMPRA' ? 'COMPRA' : '', estadoContab: operacion === 'COMPRA' ? 'REGISTRO' : '', accionRecaptcha: operacion === 'COMPRA' ? 'RCV_DETC' : 'RCV_DETV', tokenRecaptcha,
|
|
230
|
-
});
|
|
231
|
-
let uniqueCount = 0;
|
|
232
|
-
for (const row of details.data) {
|
|
233
|
-
let invoice;
|
|
234
|
-
try {
|
|
235
|
-
invoice = normalize(row, this.#company.formatted, periodo, type);
|
|
236
|
-
}
|
|
237
|
-
catch {
|
|
238
|
-
throw this.#failure('SII_INVALID_RESPONSE', method, 'INVALID_RESPONSE');
|
|
239
|
-
}
|
|
240
|
-
const key = `${invoice.issuerRut}:${invoice.documentType}:${invoice.folio}`;
|
|
241
|
-
const previous = invoices.get(key);
|
|
242
|
-
if (previous && JSON.stringify(previous) !== JSON.stringify(invoice))
|
|
243
|
-
throw this.#failure('SII_INVALID_RESPONSE', method, 'INVALID_RESPONSE');
|
|
244
|
-
if (!previous) {
|
|
245
|
-
invoices.set(key, invoice);
|
|
246
|
-
uniqueCount++;
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
if (count > initial.limiteDtes || uniqueCount !== count)
|
|
250
|
-
incompleteDocumentTypes.push(type);
|
|
251
|
-
}
|
|
252
|
-
return { data: [...invoices.values()], complete: incompleteDocumentTypes.length === 0, expectedCount, observedAt: new Date().toISOString(), incompleteDocumentTypes };
|
|
253
|
-
}
|
|
254
|
-
/** Original DTE from the free SII facturador; RCV membership alone does not guarantee XML availability. */
|
|
255
|
-
getXmlFacturaEmitida(input) {
|
|
256
|
-
return this.#getXmlFactura(input);
|
|
257
|
-
}
|
|
258
|
-
getXmlFacturaRecibida(input) {
|
|
259
|
-
return this.#getXmlFactura(input, (0, rut_1.parseRut)(input.issuerRut));
|
|
260
|
-
}
|
|
261
|
-
async #getXmlFactura({ documentType, folio }, supplier) {
|
|
262
|
-
this.#assertReady();
|
|
263
|
-
if (![33, 34].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
|
|
264
|
-
throw new TypeError('Identidad de factura inválida');
|
|
265
|
-
if (!this.#facturadorReady) {
|
|
266
|
-
let url = `${FACTURADOR}mipeSelEmpresa.cgi?DESDE_DONDE_URL=OPCION%3D2%26TIPO%3D4`;
|
|
267
|
-
let options = {}, submitted = false;
|
|
268
|
-
for (let hop = 0;; hop++) {
|
|
269
|
-
const response = await this.#request(url, options, options.method !== 'POST', true);
|
|
270
|
-
const location = response.headers.get('location');
|
|
271
|
-
if (response.status >= 300 && response.status < 400) {
|
|
272
|
-
await response.body?.cancel();
|
|
273
|
-
if (!location || hop >= 4)
|
|
274
|
-
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
|
|
275
|
-
const next = new URL(location, url);
|
|
276
|
-
if (next.origin !== 'https://www1.sii.cl' || !['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi'].some(path => next.pathname === `/cgi-bin/Portal001/${path}`))
|
|
277
|
-
throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpointFor(url), 'SESSION_REQUIRED', response);
|
|
278
|
-
url = next.href;
|
|
279
|
-
options = {};
|
|
280
|
-
continue;
|
|
281
|
-
}
|
|
282
|
-
const page = response.body ? Buffer.from(await this.#readBounded(response, endpointFor(url))).toString('latin1') : '';
|
|
283
|
-
if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
|
|
284
|
-
throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', endpointFor(url), 'CAPTCHA_REQUIRED', response);
|
|
285
|
-
const selection = companySelection(page, this.#company.formatted);
|
|
286
|
-
if (typeof selection === 'string')
|
|
287
|
-
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), selection, response);
|
|
288
|
-
if (selection) {
|
|
289
|
-
if (submitted || hop >= 4)
|
|
290
|
-
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
|
|
291
|
-
submitted = true;
|
|
292
|
-
url = `${FACTURADOR}mipeSelEmpresa.cgi`;
|
|
293
|
-
options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: selection.toString() };
|
|
294
|
-
continue;
|
|
295
|
-
}
|
|
296
|
-
break;
|
|
297
|
-
}
|
|
298
|
-
const cookies = await this.#jar.getCookies(FACTURADOR);
|
|
299
|
-
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)
|
|
300
|
-
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', 'mipeSelEmpresa.cgi', 'COMPANY_SELECTION_REQUIRED');
|
|
301
|
-
this.#facturadorReady = true;
|
|
302
|
-
}
|
|
303
|
-
// A filtered backup is a read: no emission, cancellation or representation endpoint is called.
|
|
304
|
-
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' });
|
|
305
|
-
const response = await this.#request(`${FACTURADOR}mipeDownLoad.cgi?${query}`, {}, true);
|
|
306
|
-
const bytes = await this.#readBounded(response, 'mipeDownLoad.cgi');
|
|
307
|
-
const format = responseFormat(response, bytes);
|
|
308
|
-
if (format.responseType === 'EMPTY')
|
|
309
|
-
throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', 'EMPTY_RESPONSE', response, format);
|
|
310
|
-
if (format.responseType === 'PDF' || format.responseType === 'ZIP')
|
|
311
|
-
throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', format.responseType === 'PDF' ? 'UNEXPECTED_PDF' : 'UNEXPECTED_ARCHIVE', response, format);
|
|
312
|
-
if (format.responseType !== 'XML' && !(format.responseType === 'UNKNOWN' && format.contentType === 'application/octet-stream')) {
|
|
313
|
-
const page = Buffer.from(bytes).toString('latin1');
|
|
314
|
-
const siiMessageCode = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)?.[0];
|
|
315
|
-
const evidence = { ...format, ...(siiMessageCode ? { siiMessageCode } : {}) };
|
|
316
|
-
if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
|
|
317
|
-
throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', 'mipeDownLoad.cgi', 'CAPTCHA_REQUIRED', response, evidence);
|
|
318
|
-
const reason = /demasiados\s+documentos/i.test(page) ? 'DOCUMENT_LIMIT_EXCEEDED'
|
|
319
|
-
: /no\s+se\s+encontraron\s+documentos/i.test(page) ? 'DOCUMENT_NOT_FOUND'
|
|
320
|
-
: /error\s+al\s+contribuyente/i.test(page) ? 'PROVIDER_ERROR_PAGE'
|
|
321
|
-
: format.responseType === 'HTML' ? 'HTML_RESPONSE' : 'UNEXPECTED_FORMAT';
|
|
322
|
-
throw this.#failure(reason === 'DOCUMENT_NOT_FOUND' ? 'SII_XML_UNAVAILABLE' : 'SII_SERVICE_ERROR', 'mipeDownLoad.cgi', reason, response, evidence);
|
|
323
|
-
}
|
|
324
|
-
try {
|
|
325
|
-
return (0, invoice_xml_1.parseDteXml)(bytes, { issuerRut: supplier?.formatted ?? this.#company.formatted, ...(supplier ? { receiverRut: this.#company.formatted } : {}), documentType, folio });
|
|
326
|
-
}
|
|
327
|
-
catch (error) {
|
|
328
|
-
const code = error instanceof invoice_xml_1.DteXmlError ? error.code : 'SII_XML_INVALID';
|
|
329
|
-
throw this.#failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, { ...format, stage: 'XML_PARSE' });
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
/** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
|
|
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)); }
|
|
333
40
|
dispose() {
|
|
334
|
-
if (this.#disposal)
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
this.#ready = false;
|
|
338
|
-
this.#identity = undefined;
|
|
339
|
-
this.#facturadorReady = false;
|
|
340
|
-
this.#disposal = (async () => {
|
|
341
|
-
try {
|
|
342
|
-
// An in-flight login can still issue session cookies after local closure.
|
|
343
|
-
await Promise.allSettled(this.#requests);
|
|
344
|
-
const cookies = await this.#jar.getCookies(LOGOUT);
|
|
345
|
-
if (!cookies.some(c => c.value && ['TOKEN', 'NETSCAPE_LIVEWIRE.mac'].includes(c.key)))
|
|
346
|
-
return;
|
|
347
|
-
const headers = new Headers({ Referer: RCV, Cookie: cookies.map(c => c.cookieString()).join('; ') });
|
|
348
|
-
const response = await this.#fetch(LOGOUT, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
|
|
349
|
-
if (!response.ok) {
|
|
350
|
-
await response.body?.cancel();
|
|
351
|
-
if (!(response.status >= 300 && response.status < 400 && response.headers.get('location') === 'https://homer.sii.cl/'))
|
|
352
|
-
throw new sii_error_1.SiiError('SII_LOGOUT_FAILED');
|
|
353
|
-
}
|
|
354
|
-
else {
|
|
355
|
-
const page = Buffer.from(await this.#readBounded(response, 'autTermino.cgi')).toString('latin1');
|
|
356
|
-
const codes = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/g);
|
|
357
|
-
// Observed 2026-10-01: this code means the remote session is already absent.
|
|
358
|
-
if (codes?.some(code => code !== '01.01.205.529.269.28'))
|
|
359
|
-
throw new sii_error_1.SiiError('SII_LOGOUT_FAILED');
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
catch {
|
|
363
|
-
// Preserve the operation's original error; expose cleanup failure without secrets.
|
|
364
|
-
process.emitWarning('SII_LOGOUT_FAILED', { code: 'SII_LOGOUT_FAILED' });
|
|
365
|
-
}
|
|
366
|
-
finally {
|
|
367
|
-
await this.#jar.removeAllCookies();
|
|
368
|
-
}
|
|
369
|
-
})();
|
|
370
|
-
return this.#disposal;
|
|
371
|
-
}
|
|
372
|
-
#assertReady() {
|
|
373
|
-
if (!this.#ready || this.#closed || !this.#identity)
|
|
374
|
-
throw new sii_error_1.SiiError('SESSION_REQUIRED');
|
|
375
|
-
return this.#identity;
|
|
376
|
-
}
|
|
377
|
-
async #call(method, data) {
|
|
378
|
-
const token = (await this.#jar.getCookies(RCV)).find(c => c.key === 'TOKEN')?.value;
|
|
379
|
-
if (!token)
|
|
380
|
-
throw this.#failure('SESSION_REQUIRED', method, 'SESSION_REQUIRED');
|
|
381
|
-
const response = await this.#request(`${RCV}services/data/facadeService/${method}`, {
|
|
382
|
-
method: 'POST',
|
|
383
|
-
headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/plain, */*', Referer: RCV },
|
|
384
|
-
body: JSON.stringify({ metaData: { namespace: NAMESPACE + method, conversationId: token, transactionId: (0, node_crypto_1.randomUUID)(), page: null }, data }),
|
|
385
|
-
}, true);
|
|
386
|
-
const result = await this.#json(response, method);
|
|
387
|
-
if (!isRecord(result))
|
|
388
|
-
throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
|
|
389
|
-
const status = result.respEstado;
|
|
390
|
-
const rawMeta = result.metaData ?? {};
|
|
391
|
-
if (!isRecord(status) || !isRecord(rawMeta) || (rawMeta.errors != null && !Array.isArray(rawMeta.errors))) {
|
|
392
|
-
throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
|
|
393
|
-
}
|
|
394
|
-
if (status.codRespuesta === 98)
|
|
395
|
-
throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', method, 'CAPTCHA_REQUIRED', response, { siiResponseCode: 98 });
|
|
396
|
-
// RCV shows "No hay información" for this empty-summary response (observed 2026-10-01).
|
|
397
|
-
const emptySummary = method === 'getResumen' && status.codRespuesta === 3 && status.codError == null && result.data === null;
|
|
398
|
-
if ((!emptySummary && status.codRespuesta !== 0) || (Array.isArray(rawMeta.errors) && rawMeta.errors.length))
|
|
399
|
-
throw this.#failure('SII_SERVICE_ERROR', method, 'PROVIDER_REJECTED', response, { ...(typeof status.codRespuesta === 'number' ? { siiResponseCode: status.codRespuesta } : {}) });
|
|
400
|
-
const rows = emptySummary ? [] : result.data;
|
|
401
|
-
if (!Array.isArray(rows) || !rows.every(isRecord))
|
|
402
|
-
throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
|
|
403
|
-
const { conversationId: _secret, ...metaData } = rawMeta;
|
|
404
|
-
return { ...result, data: rows, metaData };
|
|
405
|
-
}
|
|
406
|
-
async #json(response, endpoint) {
|
|
407
|
-
if (!response.headers.get('content-type')?.toLowerCase().includes('json')) {
|
|
408
|
-
await response.body?.cancel();
|
|
409
|
-
throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpoint, 'SESSION_REQUIRED', response);
|
|
410
|
-
}
|
|
411
|
-
try {
|
|
412
|
-
return await response.json();
|
|
413
|
-
}
|
|
414
|
-
catch {
|
|
415
|
-
throw this.#failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
async #readBounded(response, endpoint) {
|
|
419
|
-
const reader = response.body?.getReader();
|
|
420
|
-
if (!reader)
|
|
421
|
-
throw this.#failure('SII_XML_UNAVAILABLE', endpoint, 'EMPTY_RESPONSE', response, { responseType: 'EMPTY' });
|
|
422
|
-
let size = 0;
|
|
423
|
-
const chunks = [];
|
|
424
|
-
try {
|
|
425
|
-
for (;;) {
|
|
426
|
-
const { done, value } = await reader.read();
|
|
427
|
-
if (done)
|
|
428
|
-
break;
|
|
429
|
-
size += value.byteLength;
|
|
430
|
-
if (size > invoice_xml_1.MAX_DTE_XML_BYTES) {
|
|
431
|
-
await reader.cancel();
|
|
432
|
-
throw this.#failure('SII_XML_INVALID', endpoint, 'RESPONSE_TOO_LARGE', response);
|
|
433
|
-
}
|
|
434
|
-
chunks.push(value);
|
|
435
|
-
}
|
|
436
|
-
return Buffer.concat(chunks, size);
|
|
437
|
-
}
|
|
438
|
-
catch (error) {
|
|
439
|
-
throw error instanceof sii_error_1.SiiError ? error : this.#failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response);
|
|
440
|
-
}
|
|
441
|
-
finally {
|
|
442
|
-
reader.releaseLock();
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
#request(url, options = {}, canRetry = false, allowRedirect = false) {
|
|
446
|
-
const request = this.#sendRequest(url, options, canRetry, allowRedirect);
|
|
447
|
-
this.#requests.add(request);
|
|
448
|
-
void request.then(() => this.#requests.delete(request), () => this.#requests.delete(request));
|
|
449
|
-
return request;
|
|
450
|
-
}
|
|
451
|
-
async #sendRequest(url, options, canRetry, allowRedirect) {
|
|
452
|
-
const endpoint = endpointFor(url);
|
|
453
|
-
for (let attempt = 0;; attempt++) {
|
|
454
|
-
if (this.#closed)
|
|
455
|
-
throw new sii_error_1.SiiError('CLIENT_CLOSED');
|
|
456
|
-
const headers = new Headers(options.headers);
|
|
457
|
-
const cookie = await this.#jar.getCookieString(url);
|
|
458
|
-
if (this.#closed)
|
|
459
|
-
throw new sii_error_1.SiiError('CLIENT_CLOSED');
|
|
460
|
-
if (cookie)
|
|
461
|
-
headers.set('Cookie', cookie);
|
|
462
|
-
let response;
|
|
463
|
-
try {
|
|
464
|
-
response = await this.#fetch(url, { ...options, headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
|
|
465
|
-
}
|
|
466
|
-
catch (error) {
|
|
467
|
-
if (!canRetry || attempt >= this.#retries)
|
|
468
|
-
throw this.#failure('SII_TRANSPORT_ERROR', endpoint, error instanceof Error && error.name === 'TimeoutError' ? 'TIMEOUT' : 'TRANSPORT_ERROR', undefined, { attempts: attempt + 1 });
|
|
469
|
-
await (0, promises_1.setTimeout)(250 * (attempt + 1));
|
|
470
|
-
continue;
|
|
471
|
-
}
|
|
472
|
-
for (const setCookie of response.headers.getSetCookie()) {
|
|
473
|
-
await this.#jar.setCookie(setCookie, url, { ignoreError: true });
|
|
474
|
-
}
|
|
475
|
-
if (this.#closed) {
|
|
476
|
-
await response.body?.cancel();
|
|
477
|
-
throw new sii_error_1.SiiError('CLIENT_CLOSED');
|
|
478
|
-
}
|
|
479
|
-
if (canRetry && RETRYABLE.has(response.status) && attempt < this.#retries) {
|
|
480
|
-
const retryAfter = response.headers.get('retry-after');
|
|
481
|
-
const seconds = retryAfter === null ? NaN : Number(retryAfter);
|
|
482
|
-
const waitMs = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : Date.parse(retryAfter ?? '') - Date.now();
|
|
483
|
-
await response.body?.cancel();
|
|
484
|
-
if (Number.isFinite(waitMs) && waitMs > 5000)
|
|
485
|
-
throw this.#failure('SII_RETRY_LATER', endpoint, 'RETRY_LATER', response, { attempts: attempt + 1 });
|
|
486
|
-
await (0, promises_1.setTimeout)(Number.isFinite(waitMs) ? Math.max(0, waitMs) : 250 * (attempt + 1));
|
|
487
|
-
continue;
|
|
488
|
-
}
|
|
489
|
-
if (!response.ok && !(allowRedirect && response.status >= 300 && response.status < 400)) {
|
|
490
|
-
await response.body?.cancel();
|
|
491
|
-
const redirect = response.status >= 300 && response.status < 400;
|
|
492
|
-
throw this.#failure(redirect ? 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' : 'SII_HTTP_ERROR', endpoint, redirect ? 'SESSION_REQUIRED' : 'HTTP_ERROR', response, { attempts: attempt + 1 });
|
|
493
|
-
}
|
|
494
|
-
return response;
|
|
41
|
+
if (!this.#disposal) {
|
|
42
|
+
this.#issuance.clearPreparation();
|
|
43
|
+
this.#disposal = this.#session.dispose(this.#issuance.pendingWrite).finally(() => this.#facturador.clearPreparation());
|
|
495
44
|
}
|
|
45
|
+
return this.#disposal;
|
|
496
46
|
}
|
|
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;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/** @deprecated Use getAuthorizedCompanies. */
|
|
57
|
+
getEmpresasAutorizadas() { return this.getAuthorizedCompanies(); }
|
|
58
|
+
/** @deprecated Use getSummary. */
|
|
59
|
+
getResumen(input) { return this.getSummary(input); }
|
|
60
|
+
/** @deprecated Use getIssuedInvoices. */
|
|
61
|
+
getFacturasEmitidas(input) { return this.getIssuedInvoices(input); }
|
|
62
|
+
/** @deprecated Use getReceivedInvoices. */
|
|
63
|
+
getFacturasRecibidas(input) { return this.getReceivedInvoices(input); }
|
|
64
|
+
/** @deprecated Use getIssuedInvoiceXml. */
|
|
65
|
+
getXmlFacturaEmitida(input) { return this.getIssuedInvoiceXml(input); }
|
|
66
|
+
/** @deprecated Use getReceivedInvoiceXml. */
|
|
67
|
+
getXmlFacturaRecibida(input) { return this.getReceivedInvoiceXml(input); }
|
|
68
|
+
/** @deprecated Use getIssuedDocumentXml. */
|
|
69
|
+
getXmlDocumentoEmitido(input) { return this.getIssuedDocumentXml(input); }
|
|
70
|
+
/** @deprecated Use prepareInvoice. */
|
|
71
|
+
prepararFactura(input) { return this.prepareInvoice(input); }
|
|
72
|
+
/** @deprecated Use prepareCancellationCreditNote. */
|
|
73
|
+
prepararNotaCreditoAnulacion(input) { return this.prepareCancellationCreditNote(input); }
|
|
74
|
+
/** @deprecated Use signAndSend. */
|
|
75
|
+
firmarYEnviar(input) { return this.signAndSend(input); }
|
|
497
76
|
}
|
|
498
77
|
exports.SiiClient = SiiClient;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { parseRut } from '../domain/rut';
|
|
2
|
+
import { SiiError, type SiiDiagnostics } from '../sii-error';
|
|
3
|
+
import type { SiiClientOptions, SiiCredentials, SiiSession, InvoicePdfResult } from '../contracts';
|
|
4
|
+
export declare const RCV = "https://www4.sii.cl/consdcvinternetui/";
|
|
5
|
+
export declare const FACTURADOR = "https://www1.sii.cl/cgi-bin/Portal001/";
|
|
6
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
7
|
+
/** Owns one personal HTTP session; body consumption belongs to the tracked request. */
|
|
8
|
+
export declare class SiiHttpSession {
|
|
9
|
+
#private;
|
|
10
|
+
readonly company: ReturnType<typeof parseRut>;
|
|
11
|
+
constructor({ empresaRut, timeoutMs, retries, fetchImpl }: SiiClientOptions);
|
|
12
|
+
login({ rut, clave }: SiiCredentials, authorize: (identity: ReturnType<typeof parseRut>) => Promise<boolean>): Promise<SiiSession>;
|
|
13
|
+
assertReady(): ReturnType<typeof parseRut>;
|
|
14
|
+
cookies(url: string): Promise<import("tough-cookie").Cookie[]>;
|
|
15
|
+
failure(code: string, endpoint: SiiDiagnostics['endpoint'], reason: SiiDiagnostics['reason'], response?: Response, extra?: Partial<SiiDiagnostics>): SiiError;
|
|
16
|
+
abortFailure(signal: AbortSignal, endpoint: SiiDiagnostics['endpoint']): SiiError;
|
|
17
|
+
/** Track the whole PDF operation, including an unconsumed stream, until its resources close. */
|
|
18
|
+
pdfOperation(endpoint: SiiDiagnostics['endpoint'], operation: (signal: AbortSignal, trackStream: (stream: InvoicePdfResult['stream']) => void) => Promise<InvoicePdfResult>, signal?: AbortSignal): Promise<InvoicePdfResult>;
|
|
19
|
+
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>;
|
|
21
|
+
readBounded(response: Response, endpoint: SiiDiagnostics['endpoint'], limit?: number, oversizedCode?: string, signal?: AbortSignal): Promise<Uint8Array>;
|
|
22
|
+
dispose(pendingWrite?: Promise<unknown>): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
export declare function endpointFor(url: string): SiiDiagnostics['endpoint'];
|
|
25
|
+
export declare function responseFormat(response: Response, bytes?: Uint8Array): Pick<SiiDiagnostics, 'contentType' | 'responseType'>;
|