bcv-fx 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +208 -2
- package/dist/currencies.d.ts +18 -0
- package/dist/currencies.js +21 -0
- package/dist/errors.d.ts +26 -0
- package/dist/errors.js +30 -0
- package/dist/extract.d.ts +4 -0
- package/dist/extract.js +27 -0
- package/dist/fetch.d.ts +27 -0
- package/dist/fetch.js +37 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.js +36 -0
- package/dist/parse.d.ts +4 -0
- package/dist/parse.js +28 -0
- package/package.json +56 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alejandro R.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,209 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# bcv-fx
|
|
4
|
+
|
|
5
|
+
**Consulta el tipo de cambio de referencia del Banco Central de Venezuela, mediante web scraping.**
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/bcv-fx)
|
|
8
|
+
[](https://nodejs.org)
|
|
9
|
+
[](https://www.npmjs.com/package/bcv-fx)
|
|
10
|
+
[](https://github.com/imalescript/bcv-fx)
|
|
11
|
+
[](https://www.npmjs.com/package/bcv-fx)
|
|
12
|
+
[](./LICENSE)
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
*USD, EUR, CNY, TRY y RUB, con fecha valor, directo desde la página oficial del BCV.*
|
|
17
|
+
|
|
18
|
+
</div>
|
|
19
|
+
|
|
20
|
+
## ✨ Características
|
|
21
|
+
|
|
22
|
+
- **Cero dependencias de runtime:** solo módulos nativos de Node.js.
|
|
23
|
+
- **ESM + TypeScript:** fuente en TypeScript estricto, tipos incluidos y publicados.
|
|
24
|
+
- **Tasas como texto:** conserva los decimales que publica el BCV, sin pérdida de precisión.
|
|
25
|
+
- **Timeout configurable:** 10 segundos por defecto.
|
|
26
|
+
- **TLS configurable:** validación activa por defecto, desactivable de forma explícita.
|
|
27
|
+
- **Errores tipados:** `NetworkError`, `ParseError` y `CurrencyNotFoundError`.
|
|
28
|
+
|
|
29
|
+
## 📦 Instalación
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
# Con npm
|
|
33
|
+
npm install bcv-fx
|
|
34
|
+
|
|
35
|
+
# Con pnpm
|
|
36
|
+
pnpm add bcv-fx
|
|
37
|
+
|
|
38
|
+
# Con yarn
|
|
39
|
+
yarn add bcv-fx
|
|
40
|
+
|
|
41
|
+
# Con bun
|
|
42
|
+
bun add bcv-fx
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## 🚀 Inicio Rápido
|
|
46
|
+
|
|
47
|
+
```js
|
|
48
|
+
import { getRates, getRate } from 'bcv-fx';
|
|
49
|
+
|
|
50
|
+
// Todas las monedas
|
|
51
|
+
const { meta, rates } = await getRates();
|
|
52
|
+
|
|
53
|
+
console.log(meta);
|
|
54
|
+
// { valueDate: '2026-11-16' }
|
|
55
|
+
|
|
56
|
+
console.log(rates);
|
|
57
|
+
// {
|
|
58
|
+
// USD: '914.02180000',
|
|
59
|
+
// EUR: '1010.56078251',
|
|
60
|
+
// CNY: '137.02448092',
|
|
61
|
+
// TRY: '18.14739022',
|
|
62
|
+
// RUB: '11.12760896'
|
|
63
|
+
// }
|
|
64
|
+
|
|
65
|
+
// Una sola moneda (el código va en mayúsculas)
|
|
66
|
+
const { meta, rate } = await getRate('USD');
|
|
67
|
+
// rate -> '914.02180000'
|
|
68
|
+
// meta -> { valueDate: '2026-11-16' }
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
En TypeScript, los códigos de moneda están restringidos en tiempo de compilación:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { getRate, type CurrencyCode } from 'bcv-fx';
|
|
75
|
+
|
|
76
|
+
const code: CurrencyCode = 'USD';
|
|
77
|
+
const { rate } = await getRate(code);
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### `rates`
|
|
81
|
+
|
|
82
|
+
Las tasas se devuelven como **texto con punto decimal**, con los mismos decimales que publica el BCV, en bolívares por una unidad de la moneda. Si necesitas operar con ellas, se recomienda usar una librería de decimales (como `decimal.js`).
|
|
83
|
+
|
|
84
|
+
### `meta`
|
|
85
|
+
|
|
86
|
+
| Campo | Qué es | Formato | Tipo |
|
|
87
|
+
| --- | --- | --- | --- |
|
|
88
|
+
| `valueDate` | Fecha valor: el día para el que rige la tasa, según el BCV. Puede ser posterior a hoy. | `YYYY-MM-DD` | `string` |
|
|
89
|
+
|
|
90
|
+
## ⚙️ Opciones
|
|
91
|
+
|
|
92
|
+
`getRates(options)` y `getRate(code, options)` aceptan:
|
|
93
|
+
|
|
94
|
+
| Opción | Por defecto | Descripción | Tipo |
|
|
95
|
+
| --- | --- | --- | --- |
|
|
96
|
+
| `timeoutMs` | `10000` | Tiempo máximo de espera, en milisegundos. | `number` |
|
|
97
|
+
| `rejectUnauthorized` | `true` | Verifica el certificado TLS del sitio. | `boolean` |
|
|
98
|
+
|
|
99
|
+
En `getRate`, el código de la moneda es el primer argumento (`getRate('USD', options)`). Debe ser `USD`, `EUR`, `CNY`, `TRY` o `RUB`.
|
|
100
|
+
|
|
101
|
+
Si el certificado del BCV no se puede verificar, obtendrás un `NetworkError` que lo indica. Actualmente el BCV presenta una cadena de certificados que Node no puede validar con la configuración por defecto, así que `getRates()` sin opciones fallará. Si confías en el sitio, puedes desactivar la verificación bajo tu responsabilidad:
|
|
102
|
+
|
|
103
|
+
```js
|
|
104
|
+
const { rates } = await getRates({ rejectUnauthorized: false });
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
En entornos de producción se recomienda dejar el valor por defecto (`true`) y solucionar el problema del certificado en la infraestructura del proyecto, no desactivar la verificación.
|
|
108
|
+
|
|
109
|
+
- **Nota:** otras librerías (como `bcv-divisas`) desactivan esta verificación de manera permanente; `bcv-fx` te da la libertad de configurarlo según tu entorno.
|
|
110
|
+
|
|
111
|
+
## ⚠️ Jerarquía de errores
|
|
112
|
+
|
|
113
|
+
Todos heredan de `BcvRatesError`:
|
|
114
|
+
|
|
115
|
+
| Error | Cuándo ocurre |
|
|
116
|
+
| --- | --- |
|
|
117
|
+
| `NetworkError` | No se pudo descargar la página (sin conexión, tiempo agotado, certificado, estado HTTP distinto de 2xx). El error original, si existe, queda en `error.cause`. |
|
|
118
|
+
| `ParseError` | La página se descargó, pero no tiene la estructura o el formato esperados. Casi siempre significa que **el BCV cambió su HTML**. |
|
|
119
|
+
| `CurrencyNotFoundError` | Se pidió una moneda no soportada con `getRate`. No se hace ninguna consulta. |
|
|
120
|
+
|
|
121
|
+
```js
|
|
122
|
+
import { getRates, NetworkError, ParseError } from 'bcv-fx';
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
const { rates } = await getRates();
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (error instanceof NetworkError) { /* reintentar más tarde */ }
|
|
128
|
+
else if (error instanceof ParseError) { /* el BCV cambió la página: revisar la librería */ }
|
|
129
|
+
else throw error;
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
La librería **prefiere fallar a devolver un dato dudoso**: valida que cada tasa tenga el formato numérico del BCV y sea mayor que 0, y que la fecha valor exista en el calendario.
|
|
134
|
+
|
|
135
|
+
## 🧪 Tests y cobertura
|
|
136
|
+
|
|
137
|
+
| Suite | Archivo | Tests | Aserciones |
|
|
138
|
+
| --- | --- | ---: | ---: |
|
|
139
|
+
| Unit · currencies | `test/currencies.unit.test.ts` | 4 | 8 |
|
|
140
|
+
| Unit · extract | `test/extract.unit.test.ts` | 6 | 7 |
|
|
141
|
+
| Unit · fetch | `test/fetch.unit.test.ts` | 5 | 13 |
|
|
142
|
+
| Unit · index | `test/index.unit.test.ts` | 3 | 8 |
|
|
143
|
+
| Unit · parse | `test/parse.unit.test.ts` | 5 | 10 |
|
|
144
|
+
| Live · API | `test/index.live.test.ts` | 2 | 6 |
|
|
145
|
+
| **Total** | | **25** | **52** |
|
|
146
|
+
|
|
147
|
+
Cobertura unitaria por módulo:
|
|
148
|
+
|
|
149
|
+
| Módulo | Líneas | Ramas | Funciones |
|
|
150
|
+
| --- | ---: | ---: | ---: |
|
|
151
|
+
| `currencies.ts` | 100% | 100% | 100% |
|
|
152
|
+
| `errors.ts` | 100% | 100% | 100% |
|
|
153
|
+
| `extract.ts` | 100% | 100% | 100% |
|
|
154
|
+
| `fetch.ts` | 100% | 100% | 100% |
|
|
155
|
+
| `index.ts` | 100% | 100% | 100% |
|
|
156
|
+
| `parse.ts` | 100% | 100% | 100% |
|
|
157
|
+
| **Total unitario** | **100%** | **100%** | **100%** |
|
|
158
|
+
|
|
159
|
+
## 🔄 Flujo
|
|
160
|
+
|
|
161
|
+
```text
|
|
162
|
+
┌──────────────────────┐
|
|
163
|
+
│ Tu app │
|
|
164
|
+
│ (Node.js) │
|
|
165
|
+
└──────────┬───────────┘
|
|
166
|
+
│ getRates() / getRate('USD')
|
|
167
|
+
▼
|
|
168
|
+
┌──────────────────────┐
|
|
169
|
+
│ index.ts │
|
|
170
|
+
│ orquesta la API │
|
|
171
|
+
└──────────┬───────────┘
|
|
172
|
+
│
|
|
173
|
+
▼
|
|
174
|
+
┌──────────────────────┐ ┌──────────────────────┐
|
|
175
|
+
│ fetch.ts │───────── HTTPS ────────▶│ BCV website │
|
|
176
|
+
│ descarga el HTML │◀──────── HTML ──────────│ (HTML page) │
|
|
177
|
+
└──────────┬───────────┘ └──────────────────────┘
|
|
178
|
+
│
|
|
179
|
+
▼
|
|
180
|
+
┌──────────────────────┐
|
|
181
|
+
│ extract.ts │
|
|
182
|
+
│ tasas y fecha │
|
|
183
|
+
└──────────┬───────────┘
|
|
184
|
+
│
|
|
185
|
+
▼
|
|
186
|
+
┌──────────────────────┐
|
|
187
|
+
│ parse.ts │
|
|
188
|
+
│ tasas y fecha │
|
|
189
|
+
└──────────┬───────────┘
|
|
190
|
+
│
|
|
191
|
+
▼
|
|
192
|
+
┌──────────────────────┐
|
|
193
|
+
│ { meta, rates } │
|
|
194
|
+
└──────────────────────┘
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`fetch.ts` obtiene el HTML del BCV; `extract.ts` y `parse.ts` lo transforman hasta `{ meta, rates }`.
|
|
198
|
+
|
|
199
|
+
## 🛠️ Si el BCV cambia su página
|
|
200
|
+
|
|
201
|
+
| Qué cambió | Dónde se arregla |
|
|
202
|
+
| --- | --- |
|
|
203
|
+
| Se agregó una moneda o cambió el `id` de un bloque | `CURRENCIES` en `src/currencies.ts` |
|
|
204
|
+
| Cambió dónde está la fecha o la tasa en el HTML | `src/extract.ts` |
|
|
205
|
+
| Cambió cómo se escribe la tasa o la fecha | `src/parse.ts` |
|
|
206
|
+
|
|
207
|
+
## 📄 Licencia
|
|
208
|
+
|
|
209
|
+
MIT. Ver [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare const CURRENCIES: {
|
|
2
|
+
readonly USD: 'dolar';
|
|
3
|
+
readonly EUR: 'euro';
|
|
4
|
+
readonly CNY: 'yuan';
|
|
5
|
+
readonly TRY: 'lira';
|
|
6
|
+
readonly RUB: 'rublo';
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Supported currency codes by the BCV.
|
|
10
|
+
*/
|
|
11
|
+
export type CurrencyCode = keyof typeof CURRENCIES;
|
|
12
|
+
/**
|
|
13
|
+
* The rate of every supported currency.
|
|
14
|
+
*/
|
|
15
|
+
export type Rates = Record<CurrencyCode, string>;
|
|
16
|
+
export declare const SUPPORTED_CURRENCIES: CurrencyCode[];
|
|
17
|
+
export declare function isSupportedCurrency(currency: string): currency is CurrencyCode;
|
|
18
|
+
export declare function mapCurrencies<T>(build: (code: CurrencyCode) => T): Record<CurrencyCode, T>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const CURRENCIES = {
|
|
2
|
+
USD: 'dolar',
|
|
3
|
+
EUR: 'euro',
|
|
4
|
+
CNY: 'yuan',
|
|
5
|
+
TRY: 'lira',
|
|
6
|
+
RUB: 'rublo',
|
|
7
|
+
};
|
|
8
|
+
export const SUPPORTED_CURRENCIES = Object.keys(CURRENCIES);
|
|
9
|
+
export function isSupportedCurrency(currency) {
|
|
10
|
+
if (typeof currency !== 'string') {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
return Object.hasOwn(CURRENCIES, currency);
|
|
14
|
+
}
|
|
15
|
+
export function mapCurrencies(build) {
|
|
16
|
+
const result = {};
|
|
17
|
+
for (const code of SUPPORTED_CURRENCIES) {
|
|
18
|
+
result[code] = build(code);
|
|
19
|
+
}
|
|
20
|
+
return result;
|
|
21
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base error class for all bcv-rates related errors.
|
|
3
|
+
*/
|
|
4
|
+
export declare class BcvRatesError extends Error {
|
|
5
|
+
constructor(message: string, options?: {
|
|
6
|
+
cause?: unknown;
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Thrown when a network failure or timeout occurs while fetching the BCV page.
|
|
11
|
+
*/
|
|
12
|
+
export declare class NetworkError extends BcvRatesError {
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Thrown when the HTML structure cannot be parsed or expected elements are missing.
|
|
16
|
+
*/
|
|
17
|
+
export declare class ParseError extends BcvRatesError {
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Thrown when an unsupported or invalid currency code is requested.
|
|
21
|
+
*/
|
|
22
|
+
export declare class CurrencyNotFoundError extends BcvRatesError {
|
|
23
|
+
/** The invalid currency code that triggered the error. */
|
|
24
|
+
readonly currency: string;
|
|
25
|
+
constructor(currency: string, supported: readonly string[]);
|
|
26
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base error class for all bcv-rates related errors.
|
|
3
|
+
*/
|
|
4
|
+
export class BcvRatesError extends Error {
|
|
5
|
+
constructor(message, options) {
|
|
6
|
+
super(message, options);
|
|
7
|
+
this.name = new.target.name;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Thrown when a network failure or timeout occurs while fetching the BCV page.
|
|
12
|
+
*/
|
|
13
|
+
export class NetworkError extends BcvRatesError {
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Thrown when the HTML structure cannot be parsed or expected elements are missing.
|
|
17
|
+
*/
|
|
18
|
+
export class ParseError extends BcvRatesError {
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Thrown when an unsupported or invalid currency code is requested.
|
|
22
|
+
*/
|
|
23
|
+
export class CurrencyNotFoundError extends BcvRatesError {
|
|
24
|
+
/** The invalid currency code that triggered the error. */
|
|
25
|
+
currency;
|
|
26
|
+
constructor(currency, supported) {
|
|
27
|
+
super(`Unsupported currency: "${currency}". Available: ${supported.join(', ')}.`);
|
|
28
|
+
this.currency = currency;
|
|
29
|
+
}
|
|
30
|
+
}
|
package/dist/extract.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ParseError } from './errors.js';
|
|
2
|
+
import { CURRENCIES, mapCurrencies } from './currencies.js';
|
|
3
|
+
export function extractRates(html) {
|
|
4
|
+
return mapCurrencies((code) => extractRate(html, code));
|
|
5
|
+
}
|
|
6
|
+
export function extractRate(html, code) {
|
|
7
|
+
const id = CURRENCIES[code];
|
|
8
|
+
const start = html.indexOf(` id="${id}"`);
|
|
9
|
+
if (start === -1) {
|
|
10
|
+
throw new ParseError(`Failed to find the currency block for id="${id}" in BCV HTML.`);
|
|
11
|
+
}
|
|
12
|
+
const end = html.indexOf(' id="', start + 1);
|
|
13
|
+
const block = html.slice(start, end === -1 ? undefined : end);
|
|
14
|
+
const rate = /<strong[^>]*>([^<]*)<\/strong>/.exec(block)?.[1]?.trim();
|
|
15
|
+
if (!rate) {
|
|
16
|
+
throw new ParseError(`Failed to extract raw rate value for currency "${code}" within block id="${id}".`);
|
|
17
|
+
}
|
|
18
|
+
return rate;
|
|
19
|
+
}
|
|
20
|
+
export function extractDate(html) {
|
|
21
|
+
const spanAttributes = /Fecha Valor[^<]*<span([^>]*)>/.exec(html)?.[1];
|
|
22
|
+
const date = /content="([^"]*)"/.exec(spanAttributes ?? '')?.[1];
|
|
23
|
+
if (!date) {
|
|
24
|
+
throw new ParseError('Failed to extract the value date from BCV HTML. Structure might have changed.');
|
|
25
|
+
}
|
|
26
|
+
return date;
|
|
27
|
+
}
|
package/dist/fetch.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration options for fetching rates.
|
|
3
|
+
*/
|
|
4
|
+
export interface Options {
|
|
5
|
+
/** Maximum time to wait, in milliseconds. Default: 10000. */
|
|
6
|
+
timeoutMs?: number;
|
|
7
|
+
/** Set to false to skip TLS certificate verification. Default: true. */
|
|
8
|
+
rejectUnauthorized?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface HttpClient {
|
|
11
|
+
get(url: string, options: {
|
|
12
|
+
rejectUnauthorized: boolean;
|
|
13
|
+
signal: AbortSignal;
|
|
14
|
+
}, callback: (response: {
|
|
15
|
+
statusCode?: number | undefined;
|
|
16
|
+
resume(): void;
|
|
17
|
+
on(event: 'data', listener: (chunk: Buffer) => void): void;
|
|
18
|
+
on(event: 'end', listener: () => void): void;
|
|
19
|
+
on(event: 'error', listener: (error: Error) => void): void;
|
|
20
|
+
}) => void): {
|
|
21
|
+
on(event: 'error', listener: (error: Error) => void): void;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export interface FetchOptions extends Options {
|
|
25
|
+
httpClient?: HttpClient;
|
|
26
|
+
}
|
|
27
|
+
export declare function fetchHtml({ timeoutMs, rejectUnauthorized, httpClient, }?: FetchOptions): Promise<string>;
|
package/dist/fetch.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import https from 'node:https';
|
|
2
|
+
import { NetworkError } from './errors.js';
|
|
3
|
+
const BCV_URL = 'https://www.bcv.org.ve';
|
|
4
|
+
export async function fetchHtml({ timeoutMs = 10_000, rejectUnauthorized = true, httpClient = https, } = {}) {
|
|
5
|
+
return new Promise((resolve, reject) => {
|
|
6
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
7
|
+
const fail = (error) => {
|
|
8
|
+
reject(signal.aborted
|
|
9
|
+
? new NetworkError(`Request to BCV timed out after ${timeoutMs} ms.`, { cause: error })
|
|
10
|
+
: toNetworkError(error));
|
|
11
|
+
};
|
|
12
|
+
const requestOptions = {
|
|
13
|
+
rejectUnauthorized,
|
|
14
|
+
signal,
|
|
15
|
+
};
|
|
16
|
+
httpClient.get(BCV_URL, requestOptions, (response) => {
|
|
17
|
+
const status = response.statusCode ?? 0;
|
|
18
|
+
if (status < 200 || status >= 300) {
|
|
19
|
+
response.resume();
|
|
20
|
+
reject(new NetworkError(`BCV responded with HTTP status ${status}.`));
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const chunks = [];
|
|
24
|
+
response.on('data', (chunk) => chunks.push(chunk));
|
|
25
|
+
response.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
26
|
+
response.on('error', fail);
|
|
27
|
+
})
|
|
28
|
+
.on('error', fail);
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function toNetworkError(error) {
|
|
32
|
+
const isCertificateError = /CERT|SIGNATURE/.test(error.code ?? '');
|
|
33
|
+
const hint = isCertificateError
|
|
34
|
+
? 'Certificate verification failed; if you trust the site, use { rejectUnauthorized: false }.'
|
|
35
|
+
: '';
|
|
36
|
+
return new NetworkError(`Failed to connect to BCV: ${error.message}. ${hint}`, { cause: error });
|
|
37
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type Options } from './fetch.ts';
|
|
2
|
+
import { type CurrencyCode, type Rates } from './currencies.ts';
|
|
3
|
+
export { BcvRatesError, NetworkError, ParseError, CurrencyNotFoundError } from './errors.ts';
|
|
4
|
+
export type { CurrencyCode, Rates } from './currencies.ts';
|
|
5
|
+
export type { Options } from './fetch.ts';
|
|
6
|
+
/**
|
|
7
|
+
* Metadata associated with the fetched exchange rates.
|
|
8
|
+
*/
|
|
9
|
+
export interface Meta {
|
|
10
|
+
/** Value date of the rates, formatted as YYYY-MM-DD. */
|
|
11
|
+
valueDate: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Every reference exchange rate published by the BCV.
|
|
15
|
+
*/
|
|
16
|
+
export interface RatesResult {
|
|
17
|
+
meta: Meta;
|
|
18
|
+
rates: Rates;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The exchange rate of a single currency.
|
|
22
|
+
*/
|
|
23
|
+
export interface RateResult {
|
|
24
|
+
meta: Meta;
|
|
25
|
+
rate: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Fetches every reference exchange rate published by the BCV.
|
|
29
|
+
*
|
|
30
|
+
* @param options - Optional configuration parameters for the request.
|
|
31
|
+
* @returns A promise resolving to the metadata and a record of all currency rates.
|
|
32
|
+
*/
|
|
33
|
+
export declare function getRates(options?: Options): Promise<RatesResult>;
|
|
34
|
+
/**
|
|
35
|
+
* Fetches the exchange rate of a single specified currency.
|
|
36
|
+
*
|
|
37
|
+
* @param code - The target currency code to fetch.
|
|
38
|
+
* @param options - Optional configuration parameters for the request.
|
|
39
|
+
* @returns A promise resolving to the metadata and the specific currency rate.
|
|
40
|
+
*/
|
|
41
|
+
export declare function getRate(code: CurrencyCode, options?: Options): Promise<RateResult>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { fetchHtml } from './fetch.js';
|
|
2
|
+
import { extractDate, extractRate, extractRates } from './extract.js';
|
|
3
|
+
import { parseDate, parseRate, parseRates } from './parse.js';
|
|
4
|
+
import { SUPPORTED_CURRENCIES, isSupportedCurrency } from './currencies.js';
|
|
5
|
+
import { CurrencyNotFoundError } from './errors.js';
|
|
6
|
+
export { BcvRatesError, NetworkError, ParseError, CurrencyNotFoundError } from './errors.js';
|
|
7
|
+
/**
|
|
8
|
+
* Fetches every reference exchange rate published by the BCV.
|
|
9
|
+
*
|
|
10
|
+
* @param options - Optional configuration parameters for the request.
|
|
11
|
+
* @returns A promise resolving to the metadata and a record of all currency rates.
|
|
12
|
+
*/
|
|
13
|
+
export async function getRates(options = {}) {
|
|
14
|
+
const html = await fetchHtml(options);
|
|
15
|
+
return {
|
|
16
|
+
rates: parseRates(extractRates(html)),
|
|
17
|
+
meta: { valueDate: parseDate(extractDate(html)) },
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Fetches the exchange rate of a single specified currency.
|
|
22
|
+
*
|
|
23
|
+
* @param code - The target currency code to fetch.
|
|
24
|
+
* @param options - Optional configuration parameters for the request.
|
|
25
|
+
* @returns A promise resolving to the metadata and the specific currency rate.
|
|
26
|
+
*/
|
|
27
|
+
export async function getRate(code, options = {}) {
|
|
28
|
+
if (!isSupportedCurrency(code)) {
|
|
29
|
+
throw new CurrencyNotFoundError(code, SUPPORTED_CURRENCIES);
|
|
30
|
+
}
|
|
31
|
+
const html = await fetchHtml(options);
|
|
32
|
+
return {
|
|
33
|
+
rate: parseRate(extractRate(html, code)),
|
|
34
|
+
meta: { valueDate: parseDate(extractDate(html)) },
|
|
35
|
+
};
|
|
36
|
+
}
|
package/dist/parse.d.ts
ADDED
package/dist/parse.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { ParseError } from './errors.js';
|
|
2
|
+
import { mapCurrencies } from './currencies.js';
|
|
3
|
+
const BCV_NUMBER_FORMAT = /^\d+(?:\.\d{3})*(?:,\d+)?$/;
|
|
4
|
+
export function parseRates(rawRates) {
|
|
5
|
+
return mapCurrencies((code) => parseRate(rawRates[code]));
|
|
6
|
+
}
|
|
7
|
+
export function parseRate(toParse) {
|
|
8
|
+
const clean = toParse.trim();
|
|
9
|
+
if (!BCV_NUMBER_FORMAT.test(clean)) {
|
|
10
|
+
throw new ParseError(`Failed to parse rate format: "${clean}".`);
|
|
11
|
+
}
|
|
12
|
+
const rate = clean.replaceAll('.', '').replace(',', '.');
|
|
13
|
+
if (Number(rate) <= 0) {
|
|
14
|
+
throw new ParseError(`Rate must be greater than 0: "${clean}".`);
|
|
15
|
+
}
|
|
16
|
+
return rate;
|
|
17
|
+
}
|
|
18
|
+
export function parseDate(toParse) {
|
|
19
|
+
const valueDate = toParse.trim().slice(0, 10);
|
|
20
|
+
const check = new Date(`${valueDate}T00:00:00Z`);
|
|
21
|
+
const exists = /^\d{4}-\d{2}-\d{2}$/.test(valueDate)
|
|
22
|
+
&& !Number.isNaN(check.getTime())
|
|
23
|
+
&& check.toISOString().startsWith(valueDate);
|
|
24
|
+
if (!exists) {
|
|
25
|
+
throw new ParseError(`Failed to parse value date: "${toParse.trim()}".`);
|
|
26
|
+
}
|
|
27
|
+
return valueDate;
|
|
28
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bcv-fx",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Ligera y sin dependencias, para consultar el tipo de cambio de referencia publicado por el Banco Central de Venezuela, mediante web scraping.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"bcv",
|
|
7
|
+
"fx",
|
|
8
|
+
"dolar",
|
|
9
|
+
"euro",
|
|
10
|
+
"banco-central",
|
|
11
|
+
"venezuela",
|
|
12
|
+
"tasas",
|
|
13
|
+
"tasas-bcv",
|
|
14
|
+
"bcv-rates",
|
|
15
|
+
"bcv-fx",
|
|
16
|
+
"divisas",
|
|
17
|
+
"currency",
|
|
18
|
+
"exchange-rates",
|
|
19
|
+
"foreign-exchange"
|
|
20
|
+
],
|
|
21
|
+
"homepage": "https://github.com/imalescript/bcv-fx#readme",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/imalescript/bcv-fx/issues"
|
|
24
|
+
},
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/imalescript/bcv-fx.git"
|
|
28
|
+
},
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"author": "alescript",
|
|
31
|
+
"type": "module",
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=18"
|
|
34
|
+
},
|
|
35
|
+
"main": "./dist/index.js",
|
|
36
|
+
"types": "./dist/index.d.ts",
|
|
37
|
+
"exports": {
|
|
38
|
+
".": {
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"import": "./dist/index.js"
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"files": [
|
|
44
|
+
"dist/"
|
|
45
|
+
],
|
|
46
|
+
"sideEffects": false,
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build": "tsc -p tsconfig.build.json",
|
|
49
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
50
|
+
"test": "node --test \"test/*.unit.test.ts\"",
|
|
51
|
+
"test:live": "node --test \"test/*.live.test.ts\"",
|
|
52
|
+
"test:coverage": "node --test --experimental-test-coverage --test-coverage-include=\"src/**\" \"test/*.unit.test.ts\""
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@types/node": "^26.6.6",
|
|
56
|
+
"typescript": "^7.0.2"
|
|
57
|
+
}
|
|
58
|
+
}
|