@devly-cl/sii-client 0.0.0-stage → 0.4.3

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 CHANGED
@@ -1,3 +1,159 @@
1
- # Temporary Holding Version
1
+ # SII Client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@devly-cl/sii-client` es una biblioteca TypeScript independiente de framework. Inicia sesión personal en SII, comprueba autorización sobre una empresa y consulta resúmenes del Registro de Compras y Ventas y facturas emitidas y recibidas 33/34 mediante HTTP/JSON. Credenciales por parámetros; sin variables de entorno para login.
4
+
5
+ Basado en los servicios internos observados del portal. No es una API pública oficial ni una integración certificada. Esta versión ofrece operaciones de lectura; la emisión de facturas y notas de crédito todavía no forma parte del SDK. La prueba real del prototipo se realizó el 30-09-2026; el análisis, contrato observado y evidencia HTTP están en `docs/sii/` del repositorio, fuera del paquete npm.
6
+
7
+ ## Desarrollo
8
+
9
+ Requiere Node >=22.13 y npm. Verificado localmente en Node 24.13.1.
10
+
11
+ ```sh
12
+ npm ci
13
+ npm run check
14
+ npm pack
15
+ ```
16
+
17
+ `check` verifica tipos, genera `dist`, ejecuta checks de integración HTTP simulada/autorización y facturas emitidas, y compila el ejemplo. `npm pack` vuelve a validar antes de crear el tarball. `dist` y `node_modules` no se versionan. El paquete contiene sólo `dist` y este README.
18
+
19
+ ## Integración NestJS u otro backend
20
+
21
+ Instalar desde npm:
22
+
23
+ ```sh
24
+ npm install @devly-cl/sii-client
25
+ ```
26
+
27
+ Para probar cambios locales, crear el tarball con `npm pack` e instalarlo con `npm install <ruta-al-tarball>`. La licencia se mantiene como `UNLICENSED`.
28
+
29
+ ```ts
30
+ import { SiiClient, type ConsultaFacturasEmitidas, type CredencialesSii } from '@devly-cl/sii-client';
31
+
32
+ async function consultarFacturasEmitidas(
33
+ empresaRutAutorizada: string,
34
+ credenciales: CredencialesSii,
35
+ consulta: ConsultaFacturasEmitidas,
36
+ ) {
37
+ // El caso de uso ya autorizó actor, tenant, empresa, recurso y sucursal.
38
+ const sii = new SiiClient({ empresaRut: empresaRutAutorizada });
39
+ try {
40
+ await sii.login(credenciales);
41
+ return await sii.getFacturasEmitidas(consulta);
42
+ } finally {
43
+ await sii.dispose();
44
+ }
45
+ }
46
+ ```
47
+
48
+ `credenciales` recibe `{ rut, clave }`; `consulta` de facturas recibe `{ periodo: 'YYYYMM', tokenRecaptcha? }`. Los resúmenes conservan `{ periodo: 'YYYYMM', operacion: 'COMPRA' | 'VENTA', estado? }`. El repositorio incluye el ejemplo compilable `examples/consulta-rcv.ts`. CommonJS también admite `const { SiiClient } = require('@devly-cl/sii-client')`; las declaraciones TypeScript se generan desde el mismo código.
49
+
50
+ No registrar un cliente autenticado como singleton NestJS. Puede inyectarse un servicio sin estado que cree y descarte una instancia por operación autorizada. La empresa debe salir de un recurso autorizado del backend, no de un RUT libre enviado por el usuario.
51
+
52
+ ## Contrato
53
+
54
+ | Método | Resultado |
55
+ | --- | --- |
56
+ | `login({ rut, clave })` | Confirma identidad personal y autorización sobre la empresa fijada. Sin representación electrónica. |
57
+ | `getEmpresasAutorizadas()` | Devuelve autorizaciones del usuario en SII; el backend controla quién puede consultarlas. |
58
+ | `getResumen({ periodo, operacion, estado })` | Devuelve JSON del SII sin reinterpretar montos; elimina `metaData.conversationId` y normaliza el resumen vacío observado (`codRespuesta: 3`, `data: null`, sin errores) a `data: []`. |
59
+ | `getFacturasEmitidas({ periodo, tokenRecaptcha? })` | Facturas 33/34 normalizadas y cobertura explícita del período RCV. Sin metadatos crudos ni secretos. |
60
+ | `getFacturasRecibidas({ periodo, tokenRecaptcha? })` | Facturas 33/34 del registro de compras, con proveedor como emisor, empresa como receptor y cobertura explícita. |
61
+ | `getXmlFacturaEmitida({ documentType, folio })` | Bytes originales y detalle normalizado de un DTE emitido en el facturador gratuito del SII. |
62
+ | `getXmlFacturaRecibida({ issuerRut, documentType, folio })` | Original del DTE recibido; valida proveedor y receptor contra la empresa autorizada. |
63
+ | `dispose()` | Cierra la sesión remota propia con `autTermino.cgi`, descarta cookies y bloquea reutilización. Esperar siempre en `finally`. |
64
+
65
+ Una instancia permite un único login. Cada instancia tiene su propio CookieJar. La clase no guarda la clave como propiedad ni escribe cookies en disco. JavaScript no garantiza borrado físico inmediato de strings en memoria.
66
+
67
+ Desde 0.4.2, `dispose()` bloquea nuevas solicitudes, espera las que estén en curso y llama al cierre oficial del SII con las cookies de esa instancia antes de borrarlas. También limpia logins parcialmente autenticados que luego fallen; repetir o invocar simultáneamente `dispose()` produce un único cierre. No utiliza cookies del navegador ni cierra sesiones de otros clientes/tenants. Sin sesión creada, no solicita logout.
68
+
69
+ El cierre remoto tiene el timeout configurado, no reintenta login ni sigue redirecciones. Si SII rechaza el cierre o falla la red, descarta secretos locales y emite la advertencia Node `SII_LOGOUT_FAILED`, sin datos privados y sin reemplazar el error de la operación. Los logs del backend permiten observarla. Una respuesta de sesión ya ausente se acepta. No puede recuperar ni cerrar sesiones antiguas cuyas cookies ya se descartaron; tampoco garantiza cierre tras una terminación forzada del proceso.
70
+
71
+ Estados de compra: `REGISTRO`, `PENDIENTE`, `NO_INCLUIR`, `RECLAMADO`. Venta admite `REGISTRO`. Periodos desde 2017, meses 01 a 12; SII determina su disponibilidad real.
72
+
73
+ ## Facturas emitidas
74
+
75
+ `ResultadoFacturasEmitidas` contiene `data: FacturaEmitida[]`, `complete`, `expectedCount`, `observedAt` ISO e `incompleteDocumentTypes: (33 | 34)[]`. `expectedCount` suma sólo los tipos 33/34 presentes en el resumen de ventas del período. Consulta `getDatosInicio` para obtener `limiteDtes` y pide `getDetalleVenta` sólo para tipos presentes con cantidad positiva; cero comprobado no necesita pedir un detalle inexistente.
76
+
77
+ Cada factura contiene `issuerRut`, `documentType`, `folio`, `issuedDate`, `receiverRut`, `receiverName`, `netAmount`, `exemptAmount`, `vatAmount`, `totalAmount`, `siiBranchCode` y `rcvPeriod`. Emisor fijado por instancia; `detRutDoc` es el receptor. RUT con DV validado y normalizado; folio numérico seguro convertido a string; fecha de calendario `YYYY-MM-DD`, aceptando `dd/mm/yyyy` o `YYYY-MM-DD` del proveedor, sin conversión de zona horaria. `rcvPeriod` es el período consultado y puede diferir del mes de emisión.
78
+
79
+ Montos enteros seguros y no negativos; total obligatorio. Componentes ausentes/null permanecen `null`. No recalcula IVA ni exige que neto/exento/IVA sumen el total: éste puede incluir otros impuestos. Nombre o sucursal ausentes son `null`; código SII de sucursal `0` se conserva como `'0'`, sin mapearlo a una sucursal interna. No interpreta `detAnulado` como una decisión tributaria.
80
+
81
+ Identidad: `issuerRut + documentType + folio`, independiente del período y receptor. Duplicados normalizados idénticos se colapsan; valores distintos para esa identidad rechazan la respuesta con `SII_INVALID_RESPONSE`. Datos inválidos también rechazan la respuesta completa; el error no revela filas, identidades ni montos.
82
+
83
+ Cobertura completa exige cantidades únicas coincidentes con el resumen y cantidades esperadas dentro de `limiteDtes`. Si una cantidad supera el límite o no coincide, devuelve los registros válidos disponibles con `complete: false` y los tipos incompletos. Cero documentos reales devuelve `complete: true` y `data: []`. No inventa paginación ni descarga diferida; un resultado parcial no demuestra ausencia de otras facturas y no debe importarse como un período completo.
84
+
85
+ Por defecto envía el literal `t-o-k-e-n-web` usado por el servicio del portal observado; `tokenRecaptcha` permite un token explícito obtenido por el consumidor autorizado. Un CAPTCHA activo genera `CAPTCHA_INTERACTION_REQUIRED`: no hay solver, bypass ni reintento automático de esa respuesta. Código SII 99 es error de servicio, no resultado vacío.
86
+
87
+ ## Facturas recibidas
88
+
89
+ `getFacturasRecibidas({ periodo: '202609' })` devuelve `ResultadoFacturasRecibidas` con los mismos campos de cobertura que emitidas. Usa `COMPRA`, estado `REGISTRO` y `getDetalleCompra`, sólo para tipos 33/34 presentes en el resumen. No acepta, reclama ni modifica documentos. Cada `FacturaRecibida` conserva `issuerRut` e `issuerName` del proveedor, y `receiverRut` de la empresa fijada; `receiverName` es `null` si el RCV no lo informa. Folios iguales de distintos proveedores son documentos distintos.
90
+
91
+ En compras, `detTipoDoc` puede ser `null`: se usa el tipo de la consulta que devolvió esa fila y se rechaza un tipo explícito contradictorio. `vatAmount` conserva el IVA recuperable informado por RCV, que puede diferir del IVA total del XML. No se recalcula ni se reemplaza por el impuesto del DTE. Sólo se consulta registro; pendientes, reclamados, excluidos y notas de crédito/débito quedan fuera de este listado.
92
+
93
+ Verificación real del SDK 0.4.0, 01-10-2026: septiembre devolvió tres facturas recibidas con cobertura completa; una descarga devolvió 6.606 bytes ISO-8859-1 y una línea, con proveedor, receptor, folio y total coincidentes. Esto acredita ese piloto, no disponibilidad universal de XML.
94
+
95
+ ## XML de facturas emitidas y recibidas
96
+
97
+ Después de `login`, llamar `getXmlFacturaEmitida({ documentType: 33, folio: '20' })`. Devuelve `{ xml: Uint8Array, encoding, detail }`; no convierte el original a UTF-8 ni reescribe firmas. `parseDteXml(bytes, { issuerRut, documentType, folio })` permite interpretar un documento ya obtenido, validando su identidad.
98
+
99
+ Para recibidas, llamar `getXmlFacturaRecibida({ issuerRut: proveedorRut, documentType: 33, folio })`. La empresa de la instancia sigue siendo la empresa receptora autorizada. La descarga utiliza `ORIGEN=RCP` y `RUT_EMI` del proveedor, y valida ambos participantes en el XML. `parseDteXml` también acepta `receiverRut` como validación adicional. El respaldo de recibidos está descrito en la [guía del SII](https://www.sii.cl/portales/mipyme/administracion/Guia_Respaldo_DTEs_recibidos.html); su disponibilidad depende del documento y del servicio del facturador gratuito.
100
+
101
+ `detail` incluye emisor, tipo, folio, fecha civil, receptor, neto/exento/IVA/tasa/total, líneas, impuestos adicionales, descuentos/recargos globales y referencias. Cada línea contiene nombre, descripción, códigos, cantidad, unidad, precio unitario, descuentos/recargos, indicador de exención y monto. Cantidad, precio, porcentajes y valores globales permanecen como strings decimales; los montos CLP son enteros seguros. No recalcula impuestos ni verifica criptográficamente firmas: conserva la evidencia original para ese procesamiento posterior.
102
+
103
+ Admite `DTE`, `SetDTE` y `EnvioDTE`, con exactamente un documento 33/34, namespaces SII y codificación UTF-8 o ISO-8859-1. Límite 1 MiB, 10.000 nodos y 32 niveles. Rechaza DTD, entidades externas, documentos múltiples, identidad distinta, valores inválidos y XML mal formado. No consulta URLs incluidas en el documento.
104
+
105
+ La descarga usa HTTP del facturador gratuito; no scrapea filas ni usa un navegador. Comprueba la empresa seleccionada en la sesión antes de descargar y vuelve a comprobar el emisor dentro del XML. Si SII requiere selección interactiva de empresa o CAPTCHA, devuelve error explícito. El RCV también contiene facturas emitidas por otros sistemas; no garantiza que sus XML estén disponibles en este servicio. Prueba real del SDK 0.3.0: 01-10-2026, login personal nuevo y descarga de 5.938 bytes ISO-8859-1, raíz `SetDTE`, una línea con cantidad/precio. La evidencia está en `docs/QA.md` del repositorio.
106
+
107
+ El consumidor debe cotejar además receptor, fecha y total con su referencia autorizada antes de guardar; almacenar el original, hash y fecha de obtención; y reutilizar lo guardado ante reintentos. No iniciar descargas desde SSR ni desde usuarios con permiso sólo de lectura.
108
+
109
+ ## Errores y recuperación
110
+
111
+ Errores de parámetros generan `TypeError`. Proveedor/protocolo/sesión generan `SiiError` con `code` y, cuando corresponde, `httpStatus`. Mensajes no incluyen cuerpos HTTP ni secretos.
112
+
113
+ Desde 0.4.3, las fallas del proveedor incluyen `description` en español y `diagnostics` opcionales. `message` sigue siendo igual a `code`, compatible con consumidores anteriores. El diagnóstico identifica `stage`, nombre conocido de `endpoint` y `reason`; `traceId` es un UUID nuevo por instancia, útil para correlacionar los logs de una operación. Cuando hay evidencia, agrega `responseType`, MIME permitido sin parámetros, `httpStatus` del proveedor (también 200), `siiMessageCode` numérico oficial, `siiResponseCode` del JSON y `attempts` en fallas de transporte/HTTP. No incluye URL, query, cuerpo, HTML, XML, RUT, folio, clave ni cookies. `sanitizeSiiDiagnostics` permite aplicar la misma lista permitida en un adaptador.
114
+
115
+ La descarga distingue rechazo por demasiados documentos (`DOCUMENT_LIMIT_EXCEEDED`), respuesta vacía (`EMPTY_RESPONSE`), ausencia indicada explícitamente (`DOCUMENT_NOT_FOUND`), HTML genérico (`HTML_RESPONSE`), página de error (`PROVIDER_ERROR_PAGE`), PDF/ZIP inesperados, XML inválido y documento de identidad distinta. HTML genérico y una respuesta vacía no demuestran que el XML no exista. PDF/ZIP describen lo recibido en esa solicitud; no significan que ése sea el único formato que SII o el proveedor puedan entregar. No se guardan ni se convierten esos archivos. Una respuesta nueva/no reconocida conserva un motivo de formato genérico, sin inventar una causa.
116
+
117
+ ```ts
118
+ import { SiiError } from '@devly-cl/sii-client';
119
+
120
+ try {
121
+ await sii.getXmlFacturaRecibida(consulta);
122
+ } catch (error) {
123
+ if (error instanceof SiiError) {
124
+ // Campos saneados; jamás registrar credenciales ni el cuerpo del proveedor.
125
+ logger.warn({ code: error.code, description: error.description, diagnostics: error.diagnostics });
126
+ }
127
+ throw error;
128
+ } finally {
129
+ await sii.dispose();
130
+ }
131
+ ```
132
+
133
+ - `LOGIN_NOT_CONFIRMED`: no hubo cookie de sesión; HTTP 200 por sí solo no confirma login.
134
+ - `PERSONAL_SESSION_REQUIRED` / `SESSION_IDENTITY_MISMATCH`: sesión de representación o identidad distinta; acceso rechazado.
135
+ - `COMPANY_NOT_AUTHORIZED`: empresa fuera de las autorizaciones SII del usuario.
136
+ - `SESSION_REQUIRED` / `NEW_INSTANCE_REQUIRED`: falta login válido o instancia ya usada/cerrada.
137
+ - `SESSION_OR_INTERACTIVE_AUTH_REQUIRED`: redirección o HTML donde se esperaba JSON; resolver sesión/intervención y crear otra instancia.
138
+ - `SII_TRANSPORT_ERROR` / `SII_HTTP_ERROR`: transporte o estado HTTP fallido.
139
+ - `SII_RETRY_LATER`: `Retry-After` mayor a 5 segundos; el backend puede reprogramar la lectura.
140
+ - `SII_SERVICE_ERROR` / `SII_PROTOCOL_CHANGED`: respuesta SII fallida o formato inesperado. HTML durante un respaldo XML (incluida la página «Error al contribuyente») es `SII_SERVICE_ERROR`, incluso con HTTP 200; no confirma ausencia del XML.
141
+ - `SII_INVALID_RESPONSE`: identidad, fecha, monto, tipo, límite o cantidad de factura inválida; también conflicto de valores para una misma identidad.
142
+ - `CAPTCHA_INTERACTION_REQUIRED`: SII solicita intervención de CAPTCHA (código 98); resolver interacción fuera del SDK.
143
+ - `SII_XML_UNAVAILABLE`: el servicio no entregó un XML para esa factura.
144
+ - `SII_XML_COMPANY_SELECTION_REQUIRED`: la empresa seleccionada en el facturador no coincide con la empresa de la instancia.
145
+ - `SII_XML_INVALID` / `SII_XML_IDENTITY_MISMATCH`: XML inseguro/incorrecto o identidad distinta; no guardar.
146
+
147
+ Timeout por solicitud: 15 segundos por defecto, rango 1 a 30 segundos. Login nunca se reintenta automáticamente. Lecturas conocidas admiten 0 a 2 reintentos por transporte o HTTP 429/502/503/504; por defecto, uno. TLS conserva validación normal. Sólo la selección del facturador sigue redirecciones HTTPS entre sus dos rutas conocidas en `www1.sii.cl`, hasta cinco solicitudes; otras redirecciones se rechazan.
148
+
149
+ El contrato observado exige `conversationId` igual a la cookie secreta `TOKEN` y `Accept: application/json, text/plain, */*`. Ambos tienen checks de regresión. No se implementa resolución de CAPTCHA ni operaciones tributarias de escritura.
150
+
151
+ ## Límites y responsabilidades del consumidor
152
+
153
+ El SDK valida RUT, sesión personal y autorización SII por empresa. Cada backend implementa RBAC, mapeo tenant → empresa, permisos por recurso/sucursal, auditoría persistente, notificaciones in-app/correo y almacenamiento. RCV agrega datos empresariales: no exponer el resumen completo a un actor autorizado sólo para una sucursal.
154
+
155
+ Auditar actor interno, tenant, empresa autorizada, operación, periodo, resultado y correlación del backend. Nunca registrar clave, cookies, TOKEN, conversationId, tokens CAPTCHA, cuerpo del login ni respuesta financiera completa. Para importar facturas emitidas, usar clave única por emisor/tipo/folio; período y receptor no son parte de la identidad. El consumidor mantiene consultas indexadas, listados paginados e idempotencia para tolerar reintentos.
156
+
157
+ Otros documentos, documentos observados, descargas diferidas, grandes volúmenes, CAPTCHA activo y expiración real siguen pendientes. El SDK actual tiene pruebas reales de login personal, resúmenes, listado 33 y XML del facturador gratuito. Los casos 34, documentos incompletos y errores se validan con proveedor simulado; los checks no certifican disponibilidad productiva del SII.
158
+
159
+ `scripts/live-check.mjs` permite verificar SII real recibiendo una línea JSON por stdin con `empresaRut`, `rut`, `clave`, `periodo` y opcional `tokenRecaptcha`. Usar un programa que escriba stdin; nunca guardar credenciales o tokens en comandos, archivos, argumentos o variables de entorno. Su salida contiene sólo confirmación, cantidades por tipo documental y cobertura; no imprime facturas individuales. La ampliación del script no constituye una prueba real ejecutada.
@@ -0,0 +1,76 @@
1
+ import type { TipoFacturaEmitida } from './issued-invoice';
2
+ export declare const MAX_DTE_XML_BYTES = 1048576;
3
+ export interface ConsultaXmlFacturaEmitida {
4
+ documentType: TipoFacturaEmitida;
5
+ folio: string;
6
+ }
7
+ export interface ConsultaXmlFacturaRecibida extends ConsultaXmlFacturaEmitida {
8
+ issuerRut: string;
9
+ }
10
+ export interface DteInvoiceLine {
11
+ lineNumber: number;
12
+ name: string;
13
+ description: string | null;
14
+ codes: {
15
+ type: string;
16
+ value: string;
17
+ }[];
18
+ quantity: string | null;
19
+ unit: string | null;
20
+ unitPrice: string | null;
21
+ discountPercent: string | null;
22
+ discountAmount: number | null;
23
+ surchargePercent: string | null;
24
+ surchargeAmount: number | null;
25
+ exemptIndicator: number | null;
26
+ amount: number;
27
+ }
28
+ export interface DteInvoiceDetail {
29
+ issuerRut: string;
30
+ documentType: TipoFacturaEmitida;
31
+ folio: string;
32
+ issuedDate: string;
33
+ receiverRut: string;
34
+ netAmount: number | null;
35
+ exemptAmount: number | null;
36
+ vatRate: string | null;
37
+ vatAmount: number | null;
38
+ totalAmount: number;
39
+ lines: DteInvoiceLine[];
40
+ taxes: {
41
+ type: number;
42
+ rate: string | null;
43
+ amount: number;
44
+ }[];
45
+ adjustments: {
46
+ lineNumber: number;
47
+ movement: 'D' | 'R';
48
+ description: string | null;
49
+ valueType: '%' | '$';
50
+ value: string;
51
+ exemptIndicator: number | null;
52
+ }[];
53
+ references: {
54
+ lineNumber: number;
55
+ documentType: string;
56
+ folio: string;
57
+ date: string;
58
+ code: number | null;
59
+ reason: string | null;
60
+ }[];
61
+ }
62
+ export interface ResultadoXmlFacturaEmitida {
63
+ /** Original bytes, including the original encoding and signatures. */
64
+ xml: Uint8Array;
65
+ encoding: 'UTF-8' | 'ISO-8859-1';
66
+ detail: DteInvoiceDetail;
67
+ }
68
+ export declare class DteXmlError extends Error {
69
+ readonly code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH';
70
+ constructor(code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH');
71
+ }
72
+ /** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
73
+ export declare function parseDteXml(xml: Uint8Array, expected: ConsultaXmlFacturaEmitida & {
74
+ issuerRut: string;
75
+ receiverRut?: string;
76
+ }): ResultadoXmlFacturaEmitida;
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DteXmlError = exports.MAX_DTE_XML_BYTES = void 0;
4
+ exports.parseDteXml = parseDteXml;
5
+ const saxes_1 = require("saxes");
6
+ const rut_1 = require("./rut");
7
+ exports.MAX_DTE_XML_BYTES = 1_048_576;
8
+ class DteXmlError extends Error {
9
+ code;
10
+ constructor(code) {
11
+ super(code);
12
+ this.code = code;
13
+ }
14
+ }
15
+ exports.DteXmlError = DteXmlError;
16
+ function invalid() { throw new DteXmlError('SII_XML_INVALID'); }
17
+ const children = (node, name) => node.children.filter(n => n.name === name && n.uri === node.uri);
18
+ function one(node, name) {
19
+ const values = children(node, name);
20
+ return values.length === 1 ? values[0] : invalid();
21
+ }
22
+ function text(node, name, required = false, limit = 1000) {
23
+ const values = children(node, name);
24
+ if (values.length > 1 || (required && values.length !== 1))
25
+ invalid();
26
+ if (!values.length)
27
+ return null;
28
+ const value = values[0];
29
+ if (value.children.length || value.text.length > limit || (required && !value.text.trim()))
30
+ invalid();
31
+ return value.text.trim() || null;
32
+ }
33
+ function integer(node, name, required = false) {
34
+ const value = text(node, name, required, 20);
35
+ if (value === null)
36
+ return null;
37
+ const number = Number(value);
38
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(number))
39
+ invalid();
40
+ return number;
41
+ }
42
+ function decimal(node, name, required = false) {
43
+ const value = text(node, name, required, 40);
44
+ if (value !== null && !/^\d+(?:\.\d+)?$/.test(value))
45
+ invalid();
46
+ return value;
47
+ }
48
+ function date(node, name) {
49
+ const value = text(node, name, true, 10);
50
+ const parsed = new Date(`${value}T00:00:00Z`);
51
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value)
52
+ invalid();
53
+ return value;
54
+ }
55
+ function lineNumber(node, name) {
56
+ const value = integer(node, name, true);
57
+ return value > 0 ? value : invalid();
58
+ }
59
+ function uniqueLines(items) {
60
+ if (new Set(items.map(item => item.lineNumber)).size !== items.length)
61
+ invalid();
62
+ }
63
+ /** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
64
+ function parseDteXml(xml, expected) {
65
+ if (!(xml instanceof Uint8Array) || !xml.byteLength || xml.byteLength > exports.MAX_DTE_XML_BYTES)
66
+ invalid();
67
+ let root;
68
+ const stack = [];
69
+ let nodes = 0;
70
+ const header = Buffer.from(xml.subarray(0, 200)).toString('latin1');
71
+ const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(header)?.[1]?.toUpperCase() ?? 'UTF-8';
72
+ const encoding = declared === 'UTF-8' || declared === 'UTF8' ? 'UTF-8' : declared === 'ISO-8859-1' ? 'ISO-8859-1' : invalid();
73
+ try {
74
+ const source = encoding === 'ISO-8859-1' ? Buffer.from(xml).toString('latin1') : new TextDecoder('utf-8', { fatal: true }).decode(xml);
75
+ const parser = new saxes_1.SaxesParser({ xmlns: true });
76
+ parser.on('error', invalid);
77
+ parser.on('doctype', invalid);
78
+ parser.on('processinginstruction', invalid);
79
+ parser.on('opentag', tag => {
80
+ if (++nodes > 10000 || stack.length >= 32)
81
+ invalid();
82
+ const node = { name: tag.local, uri: tag.uri, text: '', children: [] };
83
+ if (stack.length)
84
+ stack[stack.length - 1].children.push(node);
85
+ else if (root)
86
+ invalid();
87
+ else
88
+ root = node;
89
+ stack.push(node);
90
+ });
91
+ const append = (value) => { if (stack.length)
92
+ stack[stack.length - 1].text += value; };
93
+ parser.on('text', append);
94
+ parser.on('cdata', append);
95
+ parser.on('closetag', () => { stack.pop(); });
96
+ parser.write(source).close();
97
+ }
98
+ catch {
99
+ invalid();
100
+ }
101
+ if (!root || !['', 'http://www.sii.cl/SiiDte'].includes(root.uri))
102
+ invalid();
103
+ const dtes = root.name === 'DTE' ? [root] : root.name === 'SetDTE' ? children(root, 'DTE') : root.name === 'EnvioDTE' ? children(one(root, 'SetDTE'), 'DTE') : [];
104
+ if (dtes.length !== 1)
105
+ invalid();
106
+ const document = one(dtes[0], 'Documento');
107
+ const headerNode = one(document, 'Encabezado');
108
+ const identity = one(headerNode, 'IdDoc');
109
+ const totals = one(headerNode, 'Totales');
110
+ const documentType = integer(identity, 'TipoDTE', true);
111
+ const folio = text(identity, 'Folio', true, 20);
112
+ let issuerRut, receiverRut;
113
+ try {
114
+ issuerRut = (0, rut_1.parseRut)(text(one(headerNode, 'Emisor'), 'RUTEmisor', true, 12)).formatted;
115
+ receiverRut = (0, rut_1.parseRut)(text(one(headerNode, 'Receptor'), 'RUTRecep', true, 12)).formatted;
116
+ }
117
+ catch {
118
+ return invalid();
119
+ }
120
+ if ((documentType !== 33 && documentType !== 34) || !/^[1-9]\d{0,19}$/.test(folio))
121
+ invalid();
122
+ if (issuerRut !== (0, rut_1.parseRut)(expected.issuerRut).formatted || documentType !== expected.documentType || folio !== expected.folio || (expected.receiverRut !== undefined && receiverRut !== (0, rut_1.parseRut)(expected.receiverRut).formatted))
123
+ throw new DteXmlError('SII_XML_IDENTITY_MISMATCH');
124
+ const lines = children(document, 'Detalle').map(line => ({
125
+ lineNumber: lineNumber(line, 'NroLinDet'), name: text(line, 'NmbItem', true, 80), description: text(line, 'DscItem'),
126
+ codes: children(line, 'CdgItem').map(code => ({ type: text(code, 'TpoCodigo', true, 10), value: text(code, 'VlrCodigo', true, 35) })),
127
+ quantity: decimal(line, 'QtyItem'), unit: text(line, 'UnmdItem', false, 4), unitPrice: decimal(line, 'PrcItem'),
128
+ discountPercent: decimal(line, 'DescuentoPct'), discountAmount: integer(line, 'DescuentoMonto'),
129
+ surchargePercent: decimal(line, 'RecargoPct'), surchargeAmount: integer(line, 'RecargoMonto'), exemptIndicator: integer(line, 'IndExe'), amount: integer(line, 'MontoItem', true),
130
+ }));
131
+ if (!lines.length || lines.length > 1000)
132
+ invalid();
133
+ const adjustments = children(document, 'DscRcgGlobal').map(node => {
134
+ const movement = text(node, 'TpoMov', true), valueType = text(node, 'TpoValor', true);
135
+ if ((movement !== 'D' && movement !== 'R') || (valueType !== '%' && valueType !== '$'))
136
+ invalid();
137
+ return { lineNumber: lineNumber(node, 'NroLinDR'), movement: movement, description: text(node, 'GlosaDR'), valueType: valueType, value: decimal(node, 'ValorDR', true), exemptIndicator: integer(node, 'IndExeDR') };
138
+ });
139
+ const references = children(document, 'Referencia').map(node => ({
140
+ lineNumber: lineNumber(node, 'NroLinRef'), documentType: text(node, 'TpoDocRef', true, 3), folio: text(node, 'FolioRef', true, 18), date: date(node, 'FchRef'), code: integer(node, 'CodRef'), reason: text(node, 'RazonRef', false, 90),
141
+ }));
142
+ uniqueLines(lines);
143
+ uniqueLines(adjustments);
144
+ uniqueLines(references);
145
+ return { xml: new Uint8Array(xml), encoding, detail: {
146
+ issuerRut, documentType: documentType, folio, issuedDate: date(identity, 'FchEmis'), receiverRut,
147
+ netAmount: integer(totals, 'MntNeto'), exemptAmount: integer(totals, 'MntExe'), vatRate: decimal(totals, 'TasaIVA'), vatAmount: integer(totals, 'IVA'), totalAmount: integer(totals, 'MntTotal', true), lines,
148
+ taxes: children(totals, 'ImptoReten').map(node => ({ type: integer(node, 'TipoImp', true), rate: decimal(node, 'TasaImp'), amount: integer(node, 'MontoImp', true) })), adjustments, references,
149
+ } };
150
+ }
@@ -0,0 +1,28 @@
1
+ export type TipoFacturaEmitida = 33 | 34;
2
+ export interface ConsultaFacturasEmitidas {
3
+ periodo: string;
4
+ tokenRecaptcha?: string;
5
+ }
6
+ export interface FacturaEmitida {
7
+ issuerRut: string;
8
+ documentType: TipoFacturaEmitida;
9
+ folio: string;
10
+ issuedDate: string;
11
+ receiverRut: string;
12
+ receiverName: string | null;
13
+ netAmount: number | null;
14
+ exemptAmount: number | null;
15
+ vatAmount: number | null;
16
+ totalAmount: number;
17
+ siiBranchCode: string | null;
18
+ rcvPeriod: string;
19
+ }
20
+ export interface ResultadoFacturasEmitidas {
21
+ data: FacturaEmitida[];
22
+ complete: boolean;
23
+ expectedCount: number;
24
+ observedAt: string;
25
+ incompleteDocumentTypes: TipoFacturaEmitida[];
26
+ }
27
+ /** Campos del proveedor validados; emisor y periodo vienen de la consulta autorizada. */
28
+ export declare function normalizeIssuedInvoice(row: Record<string, unknown>, issuerRut: string, period: string, type: TipoFacturaEmitida): FacturaEmitida;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeIssuedInvoice = normalizeIssuedInvoice;
4
+ const rut_1 = require("./rut");
5
+ function integer(value) {
6
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
7
+ throw new TypeError('SII_INVALID_RESPONSE');
8
+ return value;
9
+ }
10
+ function nullableAmount(value) { return value == null ? null : integer(value); }
11
+ function date(value) {
12
+ if (typeof value !== 'string')
13
+ throw new TypeError('SII_INVALID_RESPONSE');
14
+ const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
15
+ const local = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(value);
16
+ const [year, month, day] = iso ? [iso[1], iso[2], iso[3]] : local ? [local[3], local[2], local[1]] : [];
17
+ if (!year || !month || !day)
18
+ throw new TypeError('SII_INVALID_RESPONSE');
19
+ const y = Number(year), m = Number(month), d = Number(day);
20
+ const days = [31, y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
21
+ if (y < 1 || m < 1 || m > 12 || d < 1 || d > days[m - 1])
22
+ throw new TypeError('SII_INVALID_RESPONSE');
23
+ return `${year}-${month}-${day}`;
24
+ }
25
+ /** Campos del proveedor validados; emisor y periodo vienen de la consulta autorizada. */
26
+ function normalizeIssuedInvoice(row, issuerRut, period, type) {
27
+ if (row.detTipoDoc !== type || integer(row.detNroDoc) === 0 || integer(row.detRutDoc) === 0 || typeof row.detDvDoc !== 'string' || !/^[\dKk]$/.test(row.detDvDoc)) {
28
+ throw new TypeError('SII_INVALID_RESPONSE');
29
+ }
30
+ if (row.detRznSoc != null && typeof row.detRznSoc !== 'string')
31
+ throw new TypeError('SII_INVALID_RESPONSE');
32
+ let receiverRut;
33
+ try {
34
+ receiverRut = (0, rut_1.parseRut)(`${row.detRutDoc}-${row.detDvDoc}`).formatted;
35
+ }
36
+ catch {
37
+ throw new TypeError('SII_INVALID_RESPONSE');
38
+ }
39
+ return {
40
+ issuerRut, documentType: type, folio: String(row.detNroDoc), issuedDate: date(row.detFchDoc),
41
+ receiverRut, receiverName: typeof row.detRznSoc === 'string' ? row.detRznSoc.trim() || null : null,
42
+ netAmount: nullableAmount(row.detMntNeto), exemptAmount: nullableAmount(row.detMntExe),
43
+ vatAmount: nullableAmount(row.detMntIVA), totalAmount: integer(row.detMntTotal),
44
+ siiBranchCode: row.detCdgSIISucur == null ? null : String(integer(row.detCdgSIISucur)), rcvPeriod: period,
45
+ };
46
+ }
@@ -0,0 +1,10 @@
1
+ import { type ConsultaFacturasEmitidas, type FacturaEmitida, type ResultadoFacturasEmitidas, type TipoFacturaEmitida } from './issued-invoice';
2
+ export type ConsultaFacturasRecibidas = ConsultaFacturasEmitidas;
3
+ export interface FacturaRecibida extends FacturaEmitida {
4
+ issuerName: string | null;
5
+ }
6
+ export interface ResultadoFacturasRecibidas extends Omit<ResultadoFacturasEmitidas, 'data'> {
7
+ data: FacturaRecibida[];
8
+ }
9
+ /** In purchases detRutDoc identifies the supplier; the authorized company is the receiver. */
10
+ export declare function normalizeReceivedInvoice(row: Record<string, unknown>, receiverRut: string, period: string, type: TipoFacturaEmitida): FacturaRecibida;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeReceivedInvoice = normalizeReceivedInvoice;
4
+ const issued_invoice_1 = require("./issued-invoice");
5
+ /** In purchases detRutDoc identifies the supplier; the authorized company is the receiver. */
6
+ function normalizeReceivedInvoice(row, receiverRut, period, type) {
7
+ // getDetalleCompra returns detTipoDoc:null for the requested type (observed in RCV).
8
+ if (row.detTipoDoc != null && row.detTipoDoc !== type)
9
+ throw new TypeError('SII_INVALID_RESPONSE');
10
+ const invoice = (0, issued_invoice_1.normalizeIssuedInvoice)({ ...row, detTipoDoc: type }, receiverRut, period, type);
11
+ return { ...invoice, issuerRut: invoice.receiverRut, issuerName: invoice.receiverName, receiverRut, receiverName: null };
12
+ }
@@ -0,0 +1,6 @@
1
+ /** Valida RUT chileno sin framework, proveedores ni I/O. */
2
+ export declare function parseRut(input: string): {
3
+ rut: string;
4
+ dv: string;
5
+ formatted: string;
6
+ };
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseRut = parseRut;
4
+ /** Valida RUT chileno sin framework, proveedores ni I/O. */
5
+ function parseRut(input) {
6
+ if (typeof input !== 'string' || !/^(?:\d{1,8}|\d{1,2}(?:\.\d{3}){1,2})-?[\dkK]$/.test(input)) {
7
+ throw new TypeError('RUT inválido');
8
+ }
9
+ const normalized = input.replace(/[.-]/g, '').toUpperCase();
10
+ const rut = normalized.slice(0, -1).replace(/^0+/, '');
11
+ const dv = normalized.slice(-1);
12
+ if (!rut || rut.length > 8)
13
+ throw new TypeError('RUT inválido');
14
+ let sum = 0;
15
+ let factor = 2;
16
+ for (let i = rut.length - 1; i >= 0; i--) {
17
+ sum += Number(rut[i]) * factor;
18
+ factor = factor === 7 ? 2 : factor + 1;
19
+ }
20
+ const remainder = 11 - (sum % 11);
21
+ const expected = remainder === 11 ? '0' : remainder === 10 ? 'K' : String(remainder);
22
+ if (dv !== expected)
23
+ throw new TypeError('Dígito verificador inválido');
24
+ return { rut, dv, formatted: `${rut}-${dv}` };
25
+ }
@@ -0,0 +1,27 @@
1
+ declare const STAGES: readonly ["AUTHENTICATION", "SESSION_CHECK", "COMPANY_AUTHORIZATION", "RCV_INITIALIZATION", "RCV_SUMMARY", "RCV_DETAIL", "XML_COMPANY_SELECTION", "XML_DOWNLOAD", "XML_PARSE", "LOGOUT"];
2
+ declare const ENDPOINTS: readonly ["CAutInicio.cgi", "aaSessionService/load", "getDcvEmpresasAutorizadas", "getDatosInicio", "getResumen", "getDetalleCompra", "getDetalleVenta", "mipeSelEmpresa.cgi", "mipeLaunchPage.cgi", "mipeDownLoad.cgi", "autTermino.cgi"];
3
+ declare const REASONS: readonly ["DOCUMENT_LIMIT_EXCEEDED", "DOCUMENT_NOT_FOUND", "EMPTY_RESPONSE", "HTML_RESPONSE", "PROVIDER_ERROR_PAGE", "UNEXPECTED_PDF", "UNEXPECTED_ARCHIVE", "UNEXPECTED_FORMAT", "INVALID_XML", "XML_IDENTITY_MISMATCH", "RESPONSE_TOO_LARGE", "HTTP_ERROR", "TIMEOUT", "TRANSPORT_ERROR", "RETRY_LATER", "CAPTCHA_REQUIRED", "SESSION_REQUIRED", "LOGIN_NOT_CONFIRMED", "PERSONAL_SESSION_REQUIRED", "SESSION_IDENTITY_MISMATCH", "COMPANY_NOT_AUTHORIZED", "COMPANY_SELECTION_REQUIRED", "PROVIDER_REJECTED", "INVALID_RESPONSE"];
4
+ declare const RESPONSE_TYPES: readonly ["XML", "HTML", "PDF", "ZIP", "JSON", "EMPTY", "UNKNOWN"];
5
+ declare const CONTENT_TYPES: readonly ["application/xml", "text/xml", "application/octet-stream", "text/html", "application/pdf", "application/zip", "application/json", "text/plain"];
6
+ export interface SiiDiagnostics {
7
+ readonly traceId: string;
8
+ readonly stage: typeof STAGES[number];
9
+ readonly endpoint: typeof ENDPOINTS[number];
10
+ readonly reason: typeof REASONS[number];
11
+ readonly responseType?: typeof RESPONSE_TYPES[number];
12
+ readonly contentType?: typeof CONTENT_TYPES[number];
13
+ readonly httpStatus?: number;
14
+ readonly siiMessageCode?: string;
15
+ readonly siiResponseCode?: number;
16
+ readonly attempts?: number;
17
+ }
18
+ /** Only bounded, known protocol values cross this boundary. Never provider text or URLs. */
19
+ export declare function sanitizeSiiDiagnostics(value: unknown): SiiDiagnostics | undefined;
20
+ export declare class SiiError extends Error {
21
+ readonly code: string;
22
+ readonly httpStatus?: number | undefined;
23
+ readonly diagnostics?: SiiDiagnostics;
24
+ readonly description?: string;
25
+ constructor(code: string, httpStatus?: number | undefined, diagnostics?: unknown);
26
+ }
27
+ export {};
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SiiError = void 0;
4
+ exports.sanitizeSiiDiagnostics = sanitizeSiiDiagnostics;
5
+ const STAGES = ['AUTHENTICATION', 'SESSION_CHECK', 'COMPANY_AUTHORIZATION', 'RCV_INITIALIZATION', 'RCV_SUMMARY', 'RCV_DETAIL', 'XML_COMPANY_SELECTION', 'XML_DOWNLOAD', 'XML_PARSE', 'LOGOUT'];
6
+ const ENDPOINTS = ['CAutInicio.cgi', 'aaSessionService/load', 'getDcvEmpresasAutorizadas', 'getDatosInicio', 'getResumen', 'getDetalleCompra', 'getDetalleVenta', 'mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeDownLoad.cgi', 'autTermino.cgi'];
7
+ const REASONS = ['DOCUMENT_LIMIT_EXCEEDED', 'DOCUMENT_NOT_FOUND', 'EMPTY_RESPONSE', 'HTML_RESPONSE', 'PROVIDER_ERROR_PAGE', 'UNEXPECTED_PDF', 'UNEXPECTED_ARCHIVE', 'UNEXPECTED_FORMAT', 'INVALID_XML', 'XML_IDENTITY_MISMATCH', 'RESPONSE_TOO_LARGE', 'HTTP_ERROR', 'TIMEOUT', 'TRANSPORT_ERROR', 'RETRY_LATER', 'CAPTCHA_REQUIRED', 'SESSION_REQUIRED', 'LOGIN_NOT_CONFIRMED', 'PERSONAL_SESSION_REQUIRED', 'SESSION_IDENTITY_MISMATCH', 'COMPANY_NOT_AUTHORIZED', 'COMPANY_SELECTION_REQUIRED', 'PROVIDER_REJECTED', 'INVALID_RESPONSE'];
8
+ const RESPONSE_TYPES = ['XML', 'HTML', 'PDF', 'ZIP', 'JSON', 'EMPTY', 'UNKNOWN'];
9
+ const CONTENT_TYPES = ['application/xml', 'text/xml', 'application/octet-stream', 'text/html', 'application/pdf', 'application/zip', 'application/json', 'text/plain'];
10
+ function member(values, value) {
11
+ return typeof value === 'string' && values.some(item => item === value);
12
+ }
13
+ /** Only bounded, known protocol values cross this boundary. Never provider text or URLs. */
14
+ function sanitizeSiiDiagnostics(value) {
15
+ if (typeof value !== 'object' || value === null)
16
+ return undefined;
17
+ const raw = value;
18
+ if (typeof raw.traceId !== 'string' || !/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/i.test(raw.traceId)
19
+ || !member(STAGES, raw.stage) || !member(ENDPOINTS, raw.endpoint) || !member(REASONS, raw.reason))
20
+ return undefined;
21
+ return Object.freeze({
22
+ traceId: raw.traceId, stage: raw.stage, endpoint: raw.endpoint, reason: raw.reason,
23
+ ...(member(RESPONSE_TYPES, raw.responseType) ? { responseType: raw.responseType } : {}),
24
+ ...(member(CONTENT_TYPES, raw.contentType) ? { contentType: raw.contentType } : {}),
25
+ ...(typeof raw.httpStatus === 'number' && Number.isInteger(raw.httpStatus) && raw.httpStatus >= 100 && raw.httpStatus <= 599 ? { httpStatus: raw.httpStatus } : {}),
26
+ ...(typeof raw.siiMessageCode === 'string' && /^\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}$/.test(raw.siiMessageCode) ? { siiMessageCode: raw.siiMessageCode } : {}),
27
+ ...(typeof raw.siiResponseCode === 'number' && Number.isInteger(raw.siiResponseCode) && Math.abs(raw.siiResponseCode) <= 999999 ? { siiResponseCode: raw.siiResponseCode } : {}),
28
+ ...(typeof raw.attempts === 'number' && Number.isInteger(raw.attempts) && raw.attempts >= 1 && raw.attempts <= 3 ? { attempts: raw.attempts } : {}),
29
+ });
30
+ }
31
+ const STAGE_LABELS = {
32
+ AUTHENTICATION: 'inicio de sesión', SESSION_CHECK: 'validación de sesión', COMPANY_AUTHORIZATION: 'autorización de empresa',
33
+ RCV_INITIALIZATION: 'inicio del RCV', RCV_SUMMARY: 'resumen del RCV', RCV_DETAIL: 'detalle del RCV',
34
+ XML_COMPANY_SELECTION: 'selección de empresa en el facturador', XML_DOWNLOAD: 'descarga del XML', XML_PARSE: 'validación del XML', LOGOUT: 'cierre de sesión',
35
+ };
36
+ const REASON_LABELS = {
37
+ DOCUMENT_LIMIT_EXCEEDED: 'SII rechazó la consulta porque devuelve demasiados documentos. No confirmó si el XML individual está disponible.',
38
+ DOCUMENT_NOT_FOUND: 'SII indicó que no encontró documentos para esta consulta.',
39
+ EMPTY_RESPONSE: 'SII devolvió una respuesta vacía; no se recibió ningún documento.',
40
+ HTML_RESPONSE: 'SII devolvió una página HTML en lugar del XML. Esto no confirma que la factura carezca de XML.',
41
+ PROVIDER_ERROR_PAGE: 'SII devolvió una página de error en lugar del documento solicitado.',
42
+ UNEXPECTED_PDF: 'SII devolvió un PDF en esta solicitud de XML. Ese archivo no permite reconstruir el detalle desde XML.',
43
+ UNEXPECTED_ARCHIVE: 'SII devolvió un ZIP en esta solicitud de XML; el SDK esperaba un DTE individual.',
44
+ UNEXPECTED_FORMAT: 'SII devolvió un formato diferente al XML solicitado.',
45
+ INVALID_XML: 'El XML recibido no contiene un DTE individual válido y no se guardó.',
46
+ XML_IDENTITY_MISMATCH: 'El XML recibido corresponde a otro documento y no se guardó.',
47
+ RESPONSE_TOO_LARGE: 'La respuesta de SII supera el límite permitido de 1 MiB y no se procesó.',
48
+ HTTP_ERROR: 'SII respondió con un error HTTP.', TIMEOUT: 'SII no respondió dentro del tiempo permitido.',
49
+ TRANSPORT_ERROR: 'No se pudo completar la comunicación con SII.', RETRY_LATER: 'SII pidió esperar antes de volver a consultar.',
50
+ CAPTCHA_REQUIRED: 'SII requiere resolver un CAPTCHA en su sitio.', SESSION_REQUIRED: 'SII requiere autenticación interactiva o una sesión válida.',
51
+ LOGIN_NOT_CONFIRMED: 'SII no confirmó el inicio de sesión.', PERSONAL_SESSION_REQUIRED: 'SII no confirmó una sesión personal.',
52
+ SESSION_IDENTITY_MISMATCH: 'La sesión de SII no corresponde al usuario solicitado.', COMPANY_NOT_AUTHORIZED: 'SII no autorizó el acceso a la empresa solicitada.',
53
+ COMPANY_SELECTION_REQUIRED: 'SII no confirmó la selección de empresa en el facturador.',
54
+ PROVIDER_REJECTED: 'SII rechazó la consulta del RCV.', INVALID_RESPONSE: 'SII devolvió una respuesta que no cumple el contrato esperado.',
55
+ };
56
+ class SiiError extends Error {
57
+ code;
58
+ httpStatus;
59
+ diagnostics;
60
+ description;
61
+ constructor(code, httpStatus, diagnostics) {
62
+ super(code); // Preserve the existing code/message contract.
63
+ this.code = code;
64
+ this.httpStatus = httpStatus;
65
+ this.name = 'SiiError';
66
+ this.diagnostics = sanitizeSiiDiagnostics(diagnostics);
67
+ if (this.diagnostics) {
68
+ const d = this.diagnostics;
69
+ this.description = `Falló el paso: ${STAGE_LABELS[d.stage]} (${d.endpoint}). ${REASON_LABELS[d.reason]}`
70
+ + (d.httpStatus === undefined ? '' : ` HTTP ${d.httpStatus}.`)
71
+ + (d.siiMessageCode ? ` Código SII: ${d.siiMessageCode}.` : '')
72
+ + (d.siiResponseCode === undefined ? '' : ` Respuesta SII: ${d.siiResponseCode}.`);
73
+ }
74
+ }
75
+ }
76
+ exports.SiiError = SiiError;
@@ -0,0 +1,9 @@
1
+ export { SiiClient, SiiError } from './infrastructure/sii-client';
2
+ export { sanitizeSiiDiagnostics } from './domain/sii-error';
3
+ export type { SiiDiagnostics } from './domain/sii-error';
4
+ export { parseRut } from './domain/rut';
5
+ export { parseDteXml, DteXmlError, MAX_DTE_XML_BYTES } from './domain/invoice-xml';
6
+ export type { ConsultaXmlFacturaEmitida, ConsultaXmlFacturaRecibida, DteInvoiceLine, DteInvoiceDetail, ResultadoXmlFacturaEmitida } from './domain/invoice-xml';
7
+ export type { ConsultaFacturasEmitidas, FacturaEmitida, ResultadoFacturasEmitidas, TipoFacturaEmitida } from './domain/issued-invoice';
8
+ export type { ConsultaFacturasRecibidas, FacturaRecibida, ResultadoFacturasRecibidas } from './domain/received-invoice';
9
+ export type { ConsultaResumen, CredencialesSii, EmpresaAutorizada, EstadoCompra, Operacion, RegistroSii, RespuestaSii, SesionSii, SiiClientOptions, } from './infrastructure/sii-client';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteXml = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
4
+ var sii_client_1 = require("./infrastructure/sii-client");
5
+ Object.defineProperty(exports, "SiiClient", { enumerable: true, get: function () { return sii_client_1.SiiClient; } });
6
+ Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_client_1.SiiError; } });
7
+ var sii_error_1 = require("./domain/sii-error");
8
+ Object.defineProperty(exports, "sanitizeSiiDiagnostics", { enumerable: true, get: function () { return sii_error_1.sanitizeSiiDiagnostics; } });
9
+ var rut_1 = require("./domain/rut");
10
+ Object.defineProperty(exports, "parseRut", { enumerable: true, get: function () { return rut_1.parseRut; } });
11
+ var invoice_xml_1 = require("./domain/invoice-xml");
12
+ Object.defineProperty(exports, "parseDteXml", { enumerable: true, get: function () { return invoice_xml_1.parseDteXml; } });
13
+ Object.defineProperty(exports, "DteXmlError", { enumerable: true, get: function () { return invoice_xml_1.DteXmlError; } });
14
+ Object.defineProperty(exports, "MAX_DTE_XML_BYTES", { enumerable: true, get: function () { return invoice_xml_1.MAX_DTE_XML_BYTES; } });
@@ -0,0 +1,58 @@
1
+ export { SiiError } from '../domain/sii-error';
2
+ import { type ConsultaFacturasEmitidas, type ResultadoFacturasEmitidas } from '../domain/issued-invoice';
3
+ import { type ConsultaFacturasRecibidas, type ResultadoFacturasRecibidas } from '../domain/received-invoice';
4
+ import { type ConsultaXmlFacturaEmitida, type ConsultaXmlFacturaRecibida, type ResultadoXmlFacturaEmitida } from '../domain/invoice-xml';
5
+ export type Operacion = 'COMPRA' | 'VENTA';
6
+ export type EstadoCompra = 'REGISTRO' | 'PENDIENTE' | 'NO_INCLUIR' | 'RECLAMADO';
7
+ export type RegistroSii = Record<string, unknown>;
8
+ export interface RespuestaSii<T = RegistroSii> {
9
+ data: T[];
10
+ metaData: Record<string, unknown>;
11
+ respEstado: {
12
+ codRespuesta: number;
13
+ msgeRespuesta: string | null;
14
+ codError: unknown;
15
+ };
16
+ [key: string]: unknown;
17
+ }
18
+ export interface EmpresaAutorizada extends RegistroSii {
19
+ usrEmpRut: number;
20
+ usrEmpDv: string;
21
+ usrEmpRutDv: string;
22
+ }
23
+ export interface SiiClientOptions {
24
+ empresaRut: string;
25
+ timeoutMs?: number;
26
+ retries?: number;
27
+ fetchImpl?: typeof globalThis.fetch;
28
+ }
29
+ export interface CredencialesSii {
30
+ rut: string;
31
+ clave: string;
32
+ }
33
+ export interface ConsultaResumen {
34
+ periodo: string;
35
+ operacion: Operacion;
36
+ estado?: EstadoCompra;
37
+ }
38
+ export interface SesionSii {
39
+ usuarioRut: string;
40
+ empresaRut: string;
41
+ representacion: false;
42
+ }
43
+ /** Una instancia = una empresa y una sesión personal. Nunca comparte cookies. */
44
+ export declare class SiiClient {
45
+ #private;
46
+ constructor({ empresaRut, timeoutMs, retries, fetchImpl }: SiiClientOptions);
47
+ login({ rut, clave }: CredencialesSii): Promise<SesionSii>;
48
+ getEmpresasAutorizadas(): Promise<RespuestaSii<EmpresaAutorizada>>;
49
+ getResumen({ periodo, operacion, estado }: ConsultaResumen): Promise<RespuestaSii>;
50
+ getFacturasEmitidas(input: ConsultaFacturasEmitidas): Promise<ResultadoFacturasEmitidas>;
51
+ /** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
52
+ getFacturasRecibidas(input: ConsultaFacturasRecibidas): Promise<ResultadoFacturasRecibidas>;
53
+ /** Original DTE from the free SII facturador; RCV membership alone does not guarantee XML availability. */
54
+ getXmlFacturaEmitida(input: ConsultaXmlFacturaEmitida): Promise<ResultadoXmlFacturaEmitida>;
55
+ getXmlFacturaRecibida(input: ConsultaXmlFacturaRecibida): Promise<ResultadoXmlFacturaEmitida>;
56
+ /** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
57
+ dispose(): Promise<void>;
58
+ }
@@ -0,0 +1,434 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
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 rut_1 = require("../domain/rut");
8
+ const sii_error_1 = require("../domain/sii-error");
9
+ var sii_error_2 = require("../domain/sii-error");
10
+ Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_error_2.SiiError; } });
11
+ const issued_invoice_1 = require("../domain/issued-invoice");
12
+ const received_invoice_1 = require("../domain/received-invoice");
13
+ const invoice_xml_1 = require("../domain/invoice-xml");
14
+ const AUTH = 'https://zeusr.sii.cl/cgi_AUT2000/CAutInicio.cgi';
15
+ const LOGOUT = 'https://zeusr.sii.cl/cgi_AUT2000/autTermino.cgi';
16
+ const RCV = 'https://www4.sii.cl/consdcvinternetui/';
17
+ const SESSION = 'https://www4.sii.cl/common-1.0/services/aaSessionService/load';
18
+ const NAMESPACE = 'cl.sii.sdi.lob.diii.consdcv.data.api.interfaces.FacadeService/';
19
+ const RETRYABLE = new Set([429, 502, 503, 504]);
20
+ const STATES = new Set(['REGISTRO', 'PENDIENTE', 'NO_INCLUIR', 'RECLAMADO']);
21
+ const FACTURADOR = 'https://www1.sii.cl/cgi-bin/Portal001/';
22
+ const ENDPOINT_STAGES = {
23
+ 'CAutInicio.cgi': 'AUTHENTICATION', 'aaSessionService/load': 'SESSION_CHECK', getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
24
+ getDatosInicio: 'RCV_INITIALIZATION', getResumen: 'RCV_SUMMARY', getDetalleCompra: 'RCV_DETAIL', getDetalleVenta: 'RCV_DETAIL',
25
+ 'mipeSelEmpresa.cgi': 'XML_COMPANY_SELECTION', 'mipeLaunchPage.cgi': 'XML_COMPANY_SELECTION', 'mipeDownLoad.cgi': 'XML_DOWNLOAD', 'autTermino.cgi': 'LOGOUT',
26
+ };
27
+ function endpointFor(url) {
28
+ const path = new URL(url).pathname;
29
+ const endpoint = path.endsWith('/aaSessionService/load') ? 'aaSessionService/load' : path.slice(path.lastIndexOf('/') + 1);
30
+ if (!Object.hasOwn(ENDPOINT_STAGES, endpoint))
31
+ throw new TypeError('Endpoint SII desconocido');
32
+ return endpoint;
33
+ }
34
+ function responseFormat(response, bytes) {
35
+ const contentType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
36
+ const prefix = bytes ? Buffer.from(bytes.subarray(0, 512)).toString('latin1').trimStart() : '';
37
+ const responseType = bytes?.length === 0 ? 'EMPTY'
38
+ : prefix.startsWith('%PDF-') ? 'PDF'
39
+ : bytes && bytes[0] === 0x50 && bytes[1] === 0x4b && [0x03, 0x05, 0x07].includes(bytes[2] ?? -1) ? 'ZIP'
40
+ : /^(?:<!doctype\s+html|<html|<head|<body|<script|<div)\b/i.test(prefix) ? 'HTML'
41
+ : contentType === 'text/html' ? 'HTML'
42
+ : contentType === 'application/pdf' ? 'PDF'
43
+ : contentType === 'application/zip' ? 'ZIP'
44
+ : contentType?.includes('json') ? 'JSON'
45
+ : /^(?:application|text)\/xml$/.test(contentType ?? '') || /^<(?:\?xml|DTE|EnvioDTE|SetDTE)\b/i.test(prefix) ? 'XML' : 'UNKNOWN';
46
+ // The sanitizer copies only known MIME values.
47
+ return { responseType, ...(contentType ? { contentType: contentType } : {}) };
48
+ }
49
+ function isRecord(value) {
50
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
51
+ }
52
+ function assertPeriod(periodo) {
53
+ if (typeof periodo !== 'string' || !/^\d{4}(0[1-9]|1[0-2])$/.test(periodo) || Number(periodo.slice(0, 4)) < 2017)
54
+ throw new TypeError('Periodo inválido: YYYYMM');
55
+ }
56
+ /** Una instancia = una empresa y una sesión personal. Nunca comparte cookies. */
57
+ class SiiClient {
58
+ #jar = new tough_cookie_1.CookieJar();
59
+ #company;
60
+ #fetch;
61
+ #timeoutMs;
62
+ #retries;
63
+ #identity;
64
+ #ready = false;
65
+ #used = false;
66
+ #closed = false;
67
+ #facturadorReady = false;
68
+ #requests = new Set();
69
+ #disposal;
70
+ #traceId = (0, node_crypto_1.randomUUID)();
71
+ #failure(code, endpoint, reason, response, extra = {}) {
72
+ return new sii_error_1.SiiError(code, response?.status, { traceId: this.#traceId, stage: ENDPOINT_STAGES[endpoint], endpoint, reason,
73
+ ...(response ? { httpStatus: response.status, ...responseFormat(response) } : {}), ...extra });
74
+ }
75
+ constructor({ empresaRut, timeoutMs = 15000, retries = 1, fetchImpl = globalThis.fetch }) {
76
+ this.#company = (0, rut_1.parseRut)(empresaRut);
77
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 30000)
78
+ throw new TypeError('timeoutMs inválido');
79
+ if (!Number.isInteger(retries) || retries < 0 || retries > 2)
80
+ throw new TypeError('retries inválido');
81
+ if (typeof fetchImpl !== 'function')
82
+ throw new TypeError('fetchImpl inválido');
83
+ this.#fetch = fetchImpl;
84
+ this.#timeoutMs = timeoutMs;
85
+ this.#retries = retries;
86
+ }
87
+ async login({ rut, clave }) {
88
+ if (this.#used || this.#closed)
89
+ throw new sii_error_1.SiiError('NEW_INSTANCE_REQUIRED');
90
+ const identity = (0, rut_1.parseRut)(rut);
91
+ if (typeof clave !== 'string' || !clave || clave.length > 256)
92
+ throw new TypeError('Clave inválida');
93
+ this.#used = true;
94
+ try {
95
+ const body = new URLSearchParams({ rut: identity.rut, dv: identity.dv, referencia: RCV, '411': '', rutcntr: identity.formatted, clave });
96
+ const response = await this.#request(AUTH, {
97
+ method: 'POST',
98
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: 'https://zeusr.sii.cl', Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${RCV}` },
99
+ body: body.toString(),
100
+ });
101
+ await response.body?.cancel();
102
+ const cookies = await this.#jar.getCookies(RCV);
103
+ if (!cookies.some(c => c.key === 'TOKEN' && c.value))
104
+ throw this.#failure('LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', 'LOGIN_NOT_CONFIRMED', response);
105
+ const sessionResponse = await this.#request(SESSION, {}, true);
106
+ const sessionEnvelope = await this.#json(sessionResponse, 'aaSessionService/load');
107
+ const session = isRecord(sessionEnvelope) && isRecord(sessionEnvelope.data) ? sessionEnvelope.data : undefined;
108
+ if (session?.hayRepresentacion !== false)
109
+ throw this.#failure('PERSONAL_SESSION_REQUIRED', 'aaSessionService/load', 'PERSONAL_SESSION_REQUIRED', sessionResponse);
110
+ if (`${session?.rut}-${session?.dv}`.toUpperCase() !== identity.formatted)
111
+ throw this.#failure('SESSION_IDENTITY_MISMATCH', 'aaSessionService/load', 'SESSION_IDENTITY_MISMATCH', sessionResponse);
112
+ this.#identity = identity;
113
+ const companies = await this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
114
+ if (!companies.data.some(c => `${c.usrEmpRut}-${c.usrEmpDv}`.toUpperCase() === this.#company.formatted)) {
115
+ throw this.#failure('COMPANY_NOT_AUTHORIZED', 'getDcvEmpresasAutorizadas', 'COMPANY_NOT_AUTHORIZED');
116
+ }
117
+ if (this.#closed)
118
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
119
+ this.#ready = true;
120
+ return { usuarioRut: identity.formatted, empresaRut: this.#company.formatted, representacion: false };
121
+ }
122
+ catch (error) {
123
+ await this.dispose();
124
+ throw error;
125
+ }
126
+ }
127
+ async getEmpresasAutorizadas() {
128
+ const identity = this.#assertReady();
129
+ return this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
130
+ }
131
+ async getResumen({ periodo, operacion, estado = 'REGISTRO' }) {
132
+ this.#assertReady();
133
+ assertPeriod(periodo);
134
+ if (!['COMPRA', 'VENTA'].includes(operacion))
135
+ throw new TypeError('Operación inválida');
136
+ if (!STATES.has(estado) || (operacion === 'VENTA' && estado !== 'REGISTRO'))
137
+ throw new TypeError('Estado inválido');
138
+ return this.#call('getResumen', { rutEmisor: this.#company.rut, dvEmisor: this.#company.dv, ptributario: periodo, estadoContab: estado, operacion });
139
+ }
140
+ getFacturasEmitidas(input) {
141
+ return this.#getFacturas('VENTA', input, issued_invoice_1.normalizeIssuedInvoice);
142
+ }
143
+ /** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
144
+ getFacturasRecibidas(input) {
145
+ return this.#getFacturas('COMPRA', input, received_invoice_1.normalizeReceivedInvoice);
146
+ }
147
+ async #getFacturas(operacion, { periodo, tokenRecaptcha = 't-o-k-e-n-web' }, normalize) {
148
+ this.#assertReady();
149
+ assertPeriod(periodo);
150
+ if (typeof tokenRecaptcha !== 'string' || !tokenRecaptcha.trim())
151
+ throw new TypeError('tokenRecaptcha inválido');
152
+ const initial = await this.#call('getDatosInicio', {});
153
+ if (typeof initial.limiteDtes !== 'number' || !Number.isSafeInteger(initial.limiteDtes) || initial.limiteDtes < 1)
154
+ throw this.#failure('SII_INVALID_RESPONSE', 'getDatosInicio', 'INVALID_RESPONSE');
155
+ const summary = await this.getResumen({ periodo, operacion });
156
+ const expected = new Map();
157
+ let expectedCount = 0;
158
+ for (const row of summary.data) {
159
+ const type = row.rsmnTipoDocInteger;
160
+ if (typeof type !== 'number' || !Number.isSafeInteger(type) || type < 1)
161
+ throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
162
+ if (type !== 33 && type !== 34)
163
+ continue;
164
+ const count = row.rsmnTotDoc;
165
+ if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0 || (expected.has(type) && expected.get(type) !== count))
166
+ throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
167
+ if (!expected.has(type))
168
+ expectedCount += count;
169
+ if (!Number.isSafeInteger(expectedCount))
170
+ throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
171
+ expected.set(type, count);
172
+ }
173
+ const invoices = new Map();
174
+ const incompleteDocumentTypes = [];
175
+ for (const [type, count] of expected) {
176
+ if (count === 0)
177
+ continue;
178
+ const method = operacion === 'COMPRA' ? 'getDetalleCompra' : 'getDetalleVenta';
179
+ const details = await this.#call(method, {
180
+ rutEmisor: this.#company.rut, dvEmisor: this.#company.dv, ptributario: periodo,
181
+ codTipoDoc: String(type), operacion: operacion === 'COMPRA' ? 'COMPRA' : '', estadoContab: operacion === 'COMPRA' ? 'REGISTRO' : '', accionRecaptcha: operacion === 'COMPRA' ? 'RCV_DETC' : 'RCV_DETV', tokenRecaptcha,
182
+ });
183
+ let uniqueCount = 0;
184
+ for (const row of details.data) {
185
+ let invoice;
186
+ try {
187
+ invoice = normalize(row, this.#company.formatted, periodo, type);
188
+ }
189
+ catch {
190
+ throw this.#failure('SII_INVALID_RESPONSE', method, 'INVALID_RESPONSE');
191
+ }
192
+ const key = `${invoice.issuerRut}:${invoice.documentType}:${invoice.folio}`;
193
+ const previous = invoices.get(key);
194
+ if (previous && JSON.stringify(previous) !== JSON.stringify(invoice))
195
+ throw this.#failure('SII_INVALID_RESPONSE', method, 'INVALID_RESPONSE');
196
+ if (!previous) {
197
+ invoices.set(key, invoice);
198
+ uniqueCount++;
199
+ }
200
+ }
201
+ if (count > initial.limiteDtes || uniqueCount !== count)
202
+ incompleteDocumentTypes.push(type);
203
+ }
204
+ return { data: [...invoices.values()], complete: incompleteDocumentTypes.length === 0, expectedCount, observedAt: new Date().toISOString(), incompleteDocumentTypes };
205
+ }
206
+ /** Original DTE from the free SII facturador; RCV membership alone does not guarantee XML availability. */
207
+ getXmlFacturaEmitida(input) {
208
+ return this.#getXmlFactura(input);
209
+ }
210
+ getXmlFacturaRecibida(input) {
211
+ return this.#getXmlFactura(input, (0, rut_1.parseRut)(input.issuerRut));
212
+ }
213
+ async #getXmlFactura({ documentType, folio }, supplier) {
214
+ this.#assertReady();
215
+ if (![33, 34].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
216
+ throw new TypeError('Identidad de factura inválida');
217
+ if (!this.#facturadorReady) {
218
+ let url = `${FACTURADOR}mipeSelEmpresa.cgi?DESDE_DONDE_URL=OPCION%3D2%26TIPO%3D4`;
219
+ for (let hop = 0;; hop++) {
220
+ const response = await this.#request(url, {}, true, true);
221
+ const location = response.headers.get('location');
222
+ await response.body?.cancel();
223
+ if (response.status >= 300 && response.status < 400) {
224
+ if (!location || hop >= 4)
225
+ throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
226
+ const next = new URL(location, url);
227
+ if (next.origin !== 'https://www1.sii.cl' || !['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi'].some(path => next.pathname === `/cgi-bin/Portal001/${path}`))
228
+ throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpointFor(url), 'SESSION_REQUIRED', response);
229
+ url = next.href;
230
+ continue;
231
+ }
232
+ break;
233
+ }
234
+ const cookies = await this.#jar.getCookies(FACTURADOR);
235
+ 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)
236
+ throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', 'mipeSelEmpresa.cgi', 'COMPANY_SELECTION_REQUIRED');
237
+ this.#facturadorReady = true;
238
+ }
239
+ // A filtered backup is a read: no emission, cancellation or representation endpoint is called.
240
+ 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' });
241
+ const response = await this.#request(`${FACTURADOR}mipeDownLoad.cgi?${query}`, {}, true);
242
+ const bytes = await this.#readBounded(response, 'mipeDownLoad.cgi');
243
+ const format = responseFormat(response, bytes);
244
+ if (format.responseType === 'EMPTY')
245
+ throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', 'EMPTY_RESPONSE', response, format);
246
+ if (format.responseType === 'PDF' || format.responseType === 'ZIP')
247
+ throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', format.responseType === 'PDF' ? 'UNEXPECTED_PDF' : 'UNEXPECTED_ARCHIVE', response, format);
248
+ if (format.responseType !== 'XML' && !(format.responseType === 'UNKNOWN' && format.contentType === 'application/octet-stream')) {
249
+ const page = Buffer.from(bytes).toString('latin1');
250
+ const siiMessageCode = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)?.[0];
251
+ const evidence = { ...format, ...(siiMessageCode ? { siiMessageCode } : {}) };
252
+ if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
253
+ throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', 'mipeDownLoad.cgi', 'CAPTCHA_REQUIRED', response, evidence);
254
+ const reason = /demasiados\s+documentos/i.test(page) ? 'DOCUMENT_LIMIT_EXCEEDED'
255
+ : /no\s+se\s+encontraron\s+documentos/i.test(page) ? 'DOCUMENT_NOT_FOUND'
256
+ : /error\s+al\s+contribuyente/i.test(page) ? 'PROVIDER_ERROR_PAGE'
257
+ : format.responseType === 'HTML' ? 'HTML_RESPONSE' : 'UNEXPECTED_FORMAT';
258
+ throw this.#failure(reason === 'DOCUMENT_NOT_FOUND' ? 'SII_XML_UNAVAILABLE' : 'SII_SERVICE_ERROR', 'mipeDownLoad.cgi', reason, response, evidence);
259
+ }
260
+ try {
261
+ return (0, invoice_xml_1.parseDteXml)(bytes, { issuerRut: supplier?.formatted ?? this.#company.formatted, ...(supplier ? { receiverRut: this.#company.formatted } : {}), documentType, folio });
262
+ }
263
+ catch (error) {
264
+ const code = error instanceof invoice_xml_1.DteXmlError ? error.code : 'SII_XML_INVALID';
265
+ throw this.#failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, { ...format, stage: 'XML_PARSE' });
266
+ }
267
+ }
268
+ /** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
269
+ dispose() {
270
+ if (this.#disposal)
271
+ return this.#disposal;
272
+ this.#closed = true;
273
+ this.#ready = false;
274
+ this.#identity = undefined;
275
+ this.#facturadorReady = false;
276
+ this.#disposal = (async () => {
277
+ try {
278
+ // An in-flight login can still issue session cookies after local closure.
279
+ await Promise.allSettled(this.#requests);
280
+ const cookies = await this.#jar.getCookies(LOGOUT);
281
+ if (!cookies.some(c => c.value && ['TOKEN', 'NETSCAPE_LIVEWIRE.mac'].includes(c.key)))
282
+ return;
283
+ const headers = new Headers({ Referer: RCV, Cookie: cookies.map(c => c.cookieString()).join('; ') });
284
+ const response = await this.#fetch(LOGOUT, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
285
+ if (!response.ok) {
286
+ await response.body?.cancel();
287
+ if (!(response.status >= 300 && response.status < 400 && response.headers.get('location') === 'https://homer.sii.cl/'))
288
+ throw new sii_error_1.SiiError('SII_LOGOUT_FAILED');
289
+ }
290
+ else {
291
+ const page = Buffer.from(await this.#readBounded(response, 'autTermino.cgi')).toString('latin1');
292
+ const codes = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/g);
293
+ // Observed 2026-10-01: this code means the remote session is already absent.
294
+ if (codes?.some(code => code !== '01.01.205.529.269.28'))
295
+ throw new sii_error_1.SiiError('SII_LOGOUT_FAILED');
296
+ }
297
+ }
298
+ catch {
299
+ // Preserve the operation's original error; expose cleanup failure without secrets.
300
+ process.emitWarning('SII_LOGOUT_FAILED', { code: 'SII_LOGOUT_FAILED' });
301
+ }
302
+ finally {
303
+ await this.#jar.removeAllCookies();
304
+ }
305
+ })();
306
+ return this.#disposal;
307
+ }
308
+ #assertReady() {
309
+ if (!this.#ready || this.#closed || !this.#identity)
310
+ throw new sii_error_1.SiiError('SESSION_REQUIRED');
311
+ return this.#identity;
312
+ }
313
+ async #call(method, data) {
314
+ const token = (await this.#jar.getCookies(RCV)).find(c => c.key === 'TOKEN')?.value;
315
+ if (!token)
316
+ throw this.#failure('SESSION_REQUIRED', method, 'SESSION_REQUIRED');
317
+ const response = await this.#request(`${RCV}services/data/facadeService/${method}`, {
318
+ method: 'POST',
319
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/plain, */*', Referer: RCV },
320
+ body: JSON.stringify({ metaData: { namespace: NAMESPACE + method, conversationId: token, transactionId: (0, node_crypto_1.randomUUID)(), page: null }, data }),
321
+ }, true);
322
+ const result = await this.#json(response, method);
323
+ if (!isRecord(result))
324
+ throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
325
+ const status = result.respEstado;
326
+ const rawMeta = result.metaData ?? {};
327
+ if (!isRecord(status) || !isRecord(rawMeta) || (rawMeta.errors != null && !Array.isArray(rawMeta.errors))) {
328
+ throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
329
+ }
330
+ if (status.codRespuesta === 98)
331
+ throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', method, 'CAPTCHA_REQUIRED', response, { siiResponseCode: 98 });
332
+ // RCV shows "No hay información" for this empty-summary response (observed 2026-10-01).
333
+ const emptySummary = method === 'getResumen' && status.codRespuesta === 3 && status.codError == null && result.data === null;
334
+ if ((!emptySummary && status.codRespuesta !== 0) || (Array.isArray(rawMeta.errors) && rawMeta.errors.length))
335
+ throw this.#failure('SII_SERVICE_ERROR', method, 'PROVIDER_REJECTED', response, { ...(typeof status.codRespuesta === 'number' ? { siiResponseCode: status.codRespuesta } : {}) });
336
+ const rows = emptySummary ? [] : result.data;
337
+ if (!Array.isArray(rows) || !rows.every(isRecord))
338
+ throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
339
+ const { conversationId: _secret, ...metaData } = rawMeta;
340
+ return { ...result, data: rows, metaData };
341
+ }
342
+ async #json(response, endpoint) {
343
+ if (!response.headers.get('content-type')?.toLowerCase().includes('json')) {
344
+ await response.body?.cancel();
345
+ throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpoint, 'SESSION_REQUIRED', response);
346
+ }
347
+ try {
348
+ return await response.json();
349
+ }
350
+ catch {
351
+ throw this.#failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
352
+ }
353
+ }
354
+ async #readBounded(response, endpoint) {
355
+ const reader = response.body?.getReader();
356
+ if (!reader)
357
+ throw this.#failure('SII_XML_UNAVAILABLE', endpoint, 'EMPTY_RESPONSE', response, { responseType: 'EMPTY' });
358
+ let size = 0;
359
+ const chunks = [];
360
+ try {
361
+ for (;;) {
362
+ const { done, value } = await reader.read();
363
+ if (done)
364
+ break;
365
+ size += value.byteLength;
366
+ if (size > invoice_xml_1.MAX_DTE_XML_BYTES) {
367
+ await reader.cancel();
368
+ throw this.#failure('SII_XML_INVALID', endpoint, 'RESPONSE_TOO_LARGE', response);
369
+ }
370
+ chunks.push(value);
371
+ }
372
+ return Buffer.concat(chunks, size);
373
+ }
374
+ catch (error) {
375
+ throw error instanceof sii_error_1.SiiError ? error : this.#failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response);
376
+ }
377
+ finally {
378
+ reader.releaseLock();
379
+ }
380
+ }
381
+ #request(url, options = {}, canRetry = false, allowRedirect = false) {
382
+ const request = this.#sendRequest(url, options, canRetry, allowRedirect);
383
+ this.#requests.add(request);
384
+ void request.then(() => this.#requests.delete(request), () => this.#requests.delete(request));
385
+ return request;
386
+ }
387
+ async #sendRequest(url, options, canRetry, allowRedirect) {
388
+ const endpoint = endpointFor(url);
389
+ for (let attempt = 0;; attempt++) {
390
+ if (this.#closed)
391
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
392
+ const headers = new Headers(options.headers);
393
+ const cookie = await this.#jar.getCookieString(url);
394
+ if (this.#closed)
395
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
396
+ if (cookie)
397
+ headers.set('Cookie', cookie);
398
+ let response;
399
+ try {
400
+ response = await this.#fetch(url, { ...options, headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
401
+ }
402
+ catch (error) {
403
+ if (!canRetry || attempt >= this.#retries)
404
+ throw this.#failure('SII_TRANSPORT_ERROR', endpoint, error instanceof Error && error.name === 'TimeoutError' ? 'TIMEOUT' : 'TRANSPORT_ERROR', undefined, { attempts: attempt + 1 });
405
+ await (0, promises_1.setTimeout)(250 * (attempt + 1));
406
+ continue;
407
+ }
408
+ for (const setCookie of response.headers.getSetCookie()) {
409
+ await this.#jar.setCookie(setCookie, url, { ignoreError: true });
410
+ }
411
+ if (this.#closed) {
412
+ await response.body?.cancel();
413
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
414
+ }
415
+ if (canRetry && RETRYABLE.has(response.status) && attempt < this.#retries) {
416
+ const retryAfter = response.headers.get('retry-after');
417
+ const seconds = retryAfter === null ? NaN : Number(retryAfter);
418
+ const waitMs = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : Date.parse(retryAfter ?? '') - Date.now();
419
+ await response.body?.cancel();
420
+ if (Number.isFinite(waitMs) && waitMs > 5000)
421
+ throw this.#failure('SII_RETRY_LATER', endpoint, 'RETRY_LATER', response, { attempts: attempt + 1 });
422
+ await (0, promises_1.setTimeout)(Number.isFinite(waitMs) ? Math.max(0, waitMs) : 250 * (attempt + 1));
423
+ continue;
424
+ }
425
+ if (!response.ok && !(allowRedirect && response.status >= 300 && response.status < 400)) {
426
+ await response.body?.cancel();
427
+ const redirect = response.status >= 300 && response.status < 400;
428
+ throw this.#failure(redirect ? 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' : 'SII_HTTP_ERROR', endpoint, redirect ? 'SESSION_REQUIRED' : 'HTTP_ERROR', response, { attempts: attempt + 1 });
429
+ }
430
+ return response;
431
+ }
432
+ }
433
+ }
434
+ exports.SiiClient = SiiClient;
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@devly-cl/sii-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.3",
4
+ "description": "Cliente HTTP del SII para acceso personal, resúmenes RCV y facturas emitidas y recibidas, independiente de framework.",
5
+ "license": "UNLICENSED",
6
+ "type": "commonjs",
7
+ "engines": {
8
+ "node": ">=22.13.0"
9
+ },
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "require": "./dist/index.js",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "registry": "https://registry.npmjs.org"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json",
29
+ "typecheck": "tsc --noEmit -p tsconfig.json",
30
+ "test": "npm run build && node test/check.mjs && node test/invoices.mjs && node test/xml.mjs && node test/logout.mjs",
31
+ "check:example": "tsc --strict --noEmit --target ES2022 --module Node16 --moduleResolution Node16 --types node examples/consulta-rcv.ts",
32
+ "check": "npm run typecheck && npm test && npm run check:example",
33
+ "test:live": "npm run build && node scripts/live-check.mjs",
34
+ "prepack": "npm run check"
35
+ },
36
+ "dependencies": {
37
+ "saxes": "^6.0.0",
38
+ "tough-cookie": "6.0.2"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "22.20.2",
42
+ "typescript": "5.9.3"
43
+ }
44
+ }