bcv-today 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/dist/cli.js ADDED
@@ -0,0 +1,854 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ANY_CURRENCIES,
4
+ Api,
5
+ BCVError,
6
+ CURRENCIES,
7
+ CurrencyNotAvailable,
8
+ DEFAULT_BASE_URL,
9
+ DateOutOfRange,
10
+ InvalidAmount,
11
+ InvalidArgument,
12
+ InvalidCurrency,
13
+ InvalidDate,
14
+ LIBRARY_HINTS,
15
+ MAX_AMOUNT,
16
+ MAX_HISTORY_DAYS,
17
+ NotFound,
18
+ SOURCE,
19
+ TTLCache,
20
+ UNIT,
21
+ UpstreamError,
22
+ VERSION,
23
+ carryForwardNote,
24
+ checkDay,
25
+ conversionRates,
26
+ freshness,
27
+ historyWindow,
28
+ invalidDateMessage,
29
+ isIsoDate,
30
+ isProblem,
31
+ notPublishedMessage,
32
+ parseTimestamp,
33
+ pickRates,
34
+ rangeOrderMessage,
35
+ sameCurrencyMessage,
36
+ todayCaracas
37
+ } from "./chunk-2JWU4TEK.js";
38
+
39
+ // src/cli.ts
40
+ import { parseArgs } from "util";
41
+
42
+ // src/decimal.ts
43
+ var PRECISION = 28;
44
+ var TEN = BigInt(10);
45
+ var ZERO = BigInt(0);
46
+ var ONE = BigInt(1);
47
+ var TWO = BigInt(2);
48
+ var DECIMAL_RE = /^([+-])?(\d+)?(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/;
49
+ function pow10(n2) {
50
+ return TEN ** BigInt(n2);
51
+ }
52
+ function abs(n2) {
53
+ return n2 < ZERO ? -n2 : n2;
54
+ }
55
+ function digits(n2) {
56
+ return n2 === ZERO ? 1 : abs(n2).toString().length;
57
+ }
58
+ function parseDecimal(text) {
59
+ const m = DECIMAL_RE.exec(text);
60
+ if (!m) return void 0;
61
+ const [, sign, int2 = "", frac = "", e = "0"] = m;
62
+ if (int2 === "" && frac === "") return void 0;
63
+ const exp = Number(e) - frac.length;
64
+ if (!Number.isSafeInteger(exp) || Math.abs(exp) > 1e4) return void 0;
65
+ const coef = BigInt(`${int2}${frac}` || "0");
66
+ return normalize({ coef: sign === "-" ? -coef : coef, exp });
67
+ }
68
+ function fromNumber(n2) {
69
+ const d = parseDecimal(String(n2));
70
+ if (!d) throw new RangeError(`Not a finite number: ${n2}`);
71
+ return d;
72
+ }
73
+ function normalize(d) {
74
+ if (d.coef === ZERO) return { coef: ZERO, exp: 0 };
75
+ let { coef, exp } = d;
76
+ while (coef % TEN === ZERO) {
77
+ coef /= TEN;
78
+ exp += 1;
79
+ }
80
+ return { coef, exp };
81
+ }
82
+ function align(a, b) {
83
+ const exp = Math.min(a.exp, b.exp);
84
+ return [a.coef * pow10(a.exp - exp), b.coef * pow10(b.exp - exp), exp];
85
+ }
86
+ function sub(a, b) {
87
+ const [x, y, exp] = align(a, b);
88
+ return normalize({ coef: x - y, exp });
89
+ }
90
+ function mul(a, b) {
91
+ return normalize({ coef: a.coef * b.coef, exp: a.exp + b.exp });
92
+ }
93
+ function cmp(a, b) {
94
+ const [x, y] = align(a, b);
95
+ return x < y ? -1 : x > y ? 1 : 0;
96
+ }
97
+ function shiftRound(n2, k) {
98
+ if (k <= 0) return n2 * pow10(-k);
99
+ const p = pow10(k);
100
+ const q = n2 / p;
101
+ const r = abs(n2 % p);
102
+ if (r * TWO < p) return q;
103
+ return n2 < ZERO ? q - ONE : q + ONE;
104
+ }
105
+ function roundSignificant(a, prec = PRECISION) {
106
+ const extra = digits(a.coef) - prec;
107
+ if (extra <= 0) return a;
108
+ return normalize({ coef: shiftRound(a.coef, extra), exp: a.exp + extra });
109
+ }
110
+ function div(a, b, prec = PRECISION) {
111
+ if (b.coef === ZERO) throw new RangeError("Division by zero");
112
+ if (a.coef === ZERO) return { coef: ZERO, exp: 0 };
113
+ const k = Math.max(0, prec + 2 + digits(b.coef) - digits(a.coef));
114
+ const num2 = a.coef * pow10(k);
115
+ const q = num2 / b.coef;
116
+ const exp = a.exp - b.exp - k;
117
+ const extra = digits(q) - prec;
118
+ if (extra <= 0) return normalize({ coef: q, exp });
119
+ return normalize({ coef: shiftRound(q, extra), exp: exp + extra });
120
+ }
121
+ function quantize(a, places) {
122
+ const target = -places;
123
+ if (a.exp >= target) return { coef: a.coef * pow10(a.exp - target), exp: target };
124
+ return { coef: shiftRound(a.coef, target - a.exp), exp: target };
125
+ }
126
+ function toFixed(a, places) {
127
+ const d = places === void 0 ? a : quantize(a, places);
128
+ const neg = d.coef < ZERO;
129
+ let s = abs(d.coef).toString();
130
+ let out;
131
+ if (d.exp >= 0) {
132
+ out = s + "0".repeat(d.exp);
133
+ } else {
134
+ const scale = -d.exp;
135
+ if (s.length <= scale) s = "0".repeat(scale - s.length + 1) + s;
136
+ out = `${s.slice(0, s.length - scale)}.${s.slice(s.length - scale)}`;
137
+ }
138
+ return neg && /[1-9]/.test(out) ? `-${out}` : out;
139
+ }
140
+ function toPlain(a) {
141
+ return toFixed(normalize(a));
142
+ }
143
+ function toNumber(a) {
144
+ return Number(toPlain(a));
145
+ }
146
+ function group(a, places) {
147
+ const fixed = toFixed(a, places);
148
+ const neg = fixed.startsWith("-");
149
+ const body = neg ? fixed.slice(1) : fixed;
150
+ const [int2 = "0", frac] = body.split(".");
151
+ const grouped = int2.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
152
+ return `${neg ? "-" : ""}${grouped}${frac !== void 0 ? `.${frac}` : ""}`;
153
+ }
154
+
155
+ // src/client.ts
156
+ var DEFAULT_USER_AGENT = `bcv-today-js/${VERSION} (+https://bcv.today)`;
157
+ var HUNDRED = { coef: BigInt(100), exp: 0 };
158
+ var MAX_AMOUNT_DEC = fromNumber(MAX_AMOUNT);
159
+ function repr(value) {
160
+ if (typeof value === "string") return JSON.stringify(value);
161
+ if (typeof value === "bigint") return `${value}n`;
162
+ if (value instanceof Date) return `Date(${Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString()})`;
163
+ return String(value);
164
+ }
165
+ function parseDate(value, label = "date") {
166
+ if (value instanceof Date) {
167
+ if (Number.isNaN(value.getTime())) throw new InvalidDate(`Invalid ${label} ${repr(value)}: not a valid Date.`);
168
+ return value.toISOString().slice(0, 10);
169
+ }
170
+ if (typeof value === "string") {
171
+ const text = value.trim();
172
+ if (isIsoDate(text)) return text;
173
+ throw new InvalidDate(invalidDateMessage(label, value));
174
+ }
175
+ throw new InvalidDate(`Invalid ${label} ${repr(value)}: expected a Date or a YYYY-MM-DD string.`);
176
+ }
177
+ function normalizeCurrency(code, allowVes = false) {
178
+ const valid = allowVes ? ANY_CURRENCIES : CURRENCIES;
179
+ if (typeof code === "string") {
180
+ let upper = code.trim().toUpperCase();
181
+ if (upper === "VEF" && allowVes) upper = "VES";
182
+ if (valid.includes(upper)) return upper;
183
+ }
184
+ throw new InvalidCurrency(`Unsupported currency ${repr(code)}: use one of ${valid.join(", ")}.`);
185
+ }
186
+ function parseAmount(amount) {
187
+ let dec;
188
+ if (typeof amount === "number") {
189
+ if (!Number.isFinite(amount))
190
+ throw new InvalidAmount(`Invalid amount ${repr(amount)}: it must be a finite number.`);
191
+ dec = fromNumber(amount);
192
+ } else if (typeof amount === "bigint") {
193
+ dec = { coef: amount, exp: 0 };
194
+ } else if (typeof amount === "string") {
195
+ const text = amount.trim().replace(/_/g, "");
196
+ if (/^[+-]?(nan|inf|infinity)$/i.test(text)) {
197
+ throw new InvalidAmount(`Invalid amount ${repr(amount)}: it must be a finite number.`);
198
+ }
199
+ dec = parseDecimal(text);
200
+ }
201
+ if (!dec) throw new InvalidAmount(`Invalid amount ${repr(amount)}: expected a number.`);
202
+ if (dec.coef < BigInt(0)) throw new InvalidAmount(`Invalid amount ${repr(amount)}: it must be zero or positive.`);
203
+ if (cmp(dec, MAX_AMOUNT_DEC) > 0) {
204
+ throw new InvalidAmount(`Invalid amount ${repr(amount)}: it must not exceed 1e15.`);
205
+ }
206
+ return dec;
207
+ }
208
+ function checkDecimals(decimals) {
209
+ if (decimals === null) return null;
210
+ if (typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0 || decimals > 12) {
211
+ throw new InvalidAmount(`Invalid decimals ${repr(decimals)}: use a whole number from 0 to 12, or null.`);
212
+ }
213
+ return decimals;
214
+ }
215
+ function checkDays(days) {
216
+ if (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > MAX_HISTORY_DAYS) {
217
+ throw new InvalidDate(`Invalid days ${repr(days)}: use a whole number from 1 to ${MAX_HISTORY_DAYS}.`);
218
+ }
219
+ return days;
220
+ }
221
+ function raise(p) {
222
+ switch (p.kind) {
223
+ case "invalid_date":
224
+ throw new InvalidDate(p.message);
225
+ case "invalid_currency":
226
+ throw new InvalidCurrency(p.message);
227
+ case "not_available":
228
+ throw new CurrencyNotAvailable(p.message);
229
+ default:
230
+ throw new DateOutOfRange(p.message);
231
+ }
232
+ }
233
+ function expectObject(value, what) {
234
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
235
+ throw new UpstreamError(`Unexpected ${what} shape (expected an object).`);
236
+ }
237
+ return value;
238
+ }
239
+ function entryDates(entry, fallback) {
240
+ const valid = (v) => typeof v === "string" && isIsoDate(v);
241
+ const day = valid(entry.date) ? entry.date : fallback;
242
+ if (!day) throw new UpstreamError("Unexpected API response: the entry has no valid 'date'.");
243
+ return [day, valid(entry.effective_date) ? entry.effective_date : day];
244
+ }
245
+ function num(value, places = 4) {
246
+ return group(typeof value === "number" ? fromNumber(value) : value, places);
247
+ }
248
+ function ratesLine(rates) {
249
+ return Object.entries(rates).map(([c, v]) => `${c} ${num(v)}`).join(", ");
250
+ }
251
+ var BCV = class {
252
+ baseUrl;
253
+ timeoutMs;
254
+ cacheTtlMs;
255
+ userAgent;
256
+ api;
257
+ cache;
258
+ clock;
259
+ constructor(options = {}) {
260
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
261
+ if (typeof baseUrl !== "string" || !/^https?:\/\//.test(baseUrl)) {
262
+ throw new InvalidArgument(`Invalid baseUrl ${repr(baseUrl)}: it must start with https:// or http://.`);
263
+ }
264
+ const timeoutMs = options.timeoutMs ?? 1e4;
265
+ const cacheTtlMs = options.cacheTtlMs ?? 3e5;
266
+ for (const [label, v] of [
267
+ ["timeoutMs", timeoutMs],
268
+ ["cacheTtlMs", cacheTtlMs]
269
+ ]) {
270
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
271
+ throw new InvalidArgument(`Invalid ${label} ${repr(v)}: use a number of milliseconds >= 0.`);
272
+ }
273
+ }
274
+ if (options.fetch !== void 0 && typeof options.fetch !== "function") {
275
+ throw new InvalidArgument("Invalid fetch: expected a function.");
276
+ }
277
+ const now = options.now;
278
+ this.clock = now ? () => +now() : Date.now;
279
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
280
+ this.timeoutMs = timeoutMs;
281
+ this.cacheTtlMs = cacheTtlMs;
282
+ this.userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
283
+ this.cache = new TTLCache(cacheTtlMs, this.clock);
284
+ this.api = new Api({
285
+ baseUrl: this.baseUrl,
286
+ timeoutMs,
287
+ cache: this.cache,
288
+ userAgent: this.userAgent,
289
+ ...options.fetch ? { fetch: options.fetch } : {}
290
+ });
291
+ }
292
+ /** Forgets every cached response. */
293
+ clearCache() {
294
+ this.cache.clear();
295
+ }
296
+ today() {
297
+ return todayCaracas(this.clock());
298
+ }
299
+ async latestEntry() {
300
+ return expectObject(await this.api.latest(), "/api/v1/rate.json");
301
+ }
302
+ async dayEntry(date) {
303
+ const bad = checkDay(date, this.today());
304
+ if (bad) raise(bad);
305
+ try {
306
+ return expectObject(await this.api.day(date), "day snapshot");
307
+ } catch (err) {
308
+ if (!(err instanceof NotFound)) throw err;
309
+ let latest;
310
+ try {
311
+ latest = (await this.latest()).date;
312
+ } catch (e) {
313
+ if (!(e instanceof BCVError)) throw e;
314
+ }
315
+ throw new DateOutOfRange(notPublishedMessage(date, latest, LIBRARY_HINTS));
316
+ }
317
+ }
318
+ /** Official rates currently in effect (`/api/v1/rate.json`). */
319
+ async latest() {
320
+ const entry = await this.latestEntry();
321
+ const [date, effectiveDate] = entryDates(entry);
322
+ const rates = pickRates(entry, date).rates;
323
+ return {
324
+ rates,
325
+ date,
326
+ effectiveDate,
327
+ updatedAt: parseTimestamp(entry.updated_at) ?? null,
328
+ unit: UNIT,
329
+ source: SOURCE,
330
+ summary: `Official BCV rates (effective ${effectiveDate}, Bs. per unit): ${ratesLine(rates)}`,
331
+ raw: entry
332
+ };
333
+ }
334
+ /**
335
+ * Rate(s) in effect on a calendar day.
336
+ *
337
+ * BCV does not publish on weekends and holidays: the last published rate stays
338
+ * in effect, so `effectiveDate` may be earlier than `date` and `carriedForward`
339
+ * is then true (with an explanatory `note`). Data starts on 2021-08-02; dates
340
+ * after tomorrow (Caracas time) throw `DateOutOfRange`.
341
+ *
342
+ * @param date "YYYY-MM-DD" or a Date (its UTC calendar day).
343
+ * @param currency Restrict the result to one currency (throws `CurrencyNotAvailable` if it was not published that day).
344
+ */
345
+ async on(date, currency) {
346
+ const day = parseDate(date);
347
+ const code = currency !== void 0 && currency !== null ? normalizeCurrency(currency) : void 0;
348
+ const entry = await this.dayEntry(day);
349
+ const [, effectiveDate] = entryDates(entry, day);
350
+ const picked = pickRates(entry, day, code);
351
+ if (isProblem(picked)) raise(picked);
352
+ const { rates } = picked;
353
+ const note = carryForwardNote(day, effectiveDate) ?? null;
354
+ const values = Object.values(rates);
355
+ const text = `BCV rate in effect on ${day} (Bs. per unit): ${ratesLine(rates)}.`;
356
+ return {
357
+ date: day,
358
+ effectiveDate,
359
+ carriedForward: note !== null,
360
+ rates,
361
+ rate: values.length === 1 ? values[0] : void 0,
362
+ updatedAt: parseTimestamp(entry.updated_at) ?? null,
363
+ note,
364
+ unit: UNIT,
365
+ source: SOURCE,
366
+ summary: note ? `${text} ${note}` : text,
367
+ raw: entry
368
+ };
369
+ }
370
+ /**
371
+ * Daily series for one currency, oldest first: the last `days` calendar days
372
+ * ending on the latest published date (default 30, max 1830), or an inclusive
373
+ * `start`/`end` range (`days` is then ignored). Uses `/api/v1/history.json`,
374
+ * which keeps the latest 1830 daily entries; ranges are clipped to what it
375
+ * covers and `note` says so.
376
+ */
377
+ async history(currency, options = {}) {
378
+ const code = normalizeCurrency(currency);
379
+ const start = options.start !== void 0 ? parseDate(options.start, "start") : void 0;
380
+ const end = options.end !== void 0 ? parseDate(options.end, "end") : void 0;
381
+ const days = checkDays(options.days ?? 30);
382
+ if (start && end && start > end) throw new InvalidDate(rangeOrderMessage("start", start, "end", end));
383
+ const entries = (await this.api.history()).filter(
384
+ (e) => typeof e === "object" && e !== null && typeof e.date === "string" && isIsoDate(e.date)
385
+ );
386
+ const w = historyWindow(entries, code, { days, from: start, to: end }, LIBRARY_HINTS);
387
+ if (isProblem(w)) raise(w);
388
+ const point2 = (p) => ({
389
+ date: p.date,
390
+ effectiveDate: p.effective_date,
391
+ rate: p.rate,
392
+ carriedForward: p.effective_date !== p.date
393
+ });
394
+ const points = w.series.map(point2);
395
+ const first = points[0];
396
+ const last = points[points.length - 1];
397
+ const firstDec = fromNumber(first.rate);
398
+ const changeDec = sub(fromNumber(last.rate), firstDec);
399
+ const pctDec = quantize(mul(div(changeDec, firstDec), HUNDRED), 4);
400
+ const min = point2(w.min);
401
+ const max = point2(w.max);
402
+ const note = w.notes.length ? w.notes.join(" ") : null;
403
+ const sign = changeDec.coef >= BigInt(0) ? "+" : "";
404
+ const text = `${code}/VES from ${first.date} to ${last.date} (${points.length} days): ${num(first.rate)} -> ${num(last.rate)} (${sign}${toFixed(pctDec, 2)}%). Min ${num(min.rate)} on ${min.date}, max ${num(max.rate)} on ${max.date}.`;
405
+ return {
406
+ currency: code,
407
+ points,
408
+ start: first.date,
409
+ end: last.date,
410
+ first,
411
+ last,
412
+ min,
413
+ max,
414
+ change: toNumber(changeDec),
415
+ changeExact: toPlain(changeDec),
416
+ changePct: toNumber(pctDec),
417
+ note,
418
+ unit: UNIT,
419
+ source: SOURCE,
420
+ summary: note ? `${text} ${note}` : text
421
+ };
422
+ }
423
+ /**
424
+ * Converts `amount` between VES, USD, EUR, CNY, TRY and RUB at the BCV rate.
425
+ *
426
+ * Cross rates go through the bolivar: `amount * vesPerFrom / vesPerTo`. The
427
+ * math is exact decimal (no float drift; divisions keep 28 significant
428
+ * digits, half-up), then `result` is rounded half-up to `decimals` places
429
+ * (default 2; `null` keeps full precision). `resultExact` is the unrounded
430
+ * value as a string. Numbers are read via their shortest decimal string
431
+ * (0.1 is exactly "0.1"); pass a string for amounts beyond float precision.
432
+ */
433
+ async convert(amount, from, to, options = {}) {
434
+ const value = parseAmount(amount);
435
+ const src = normalizeCurrency(from, true);
436
+ const dst = normalizeCurrency(to, true);
437
+ if (src === dst) throw new InvalidCurrency(sameCurrencyMessage(src));
438
+ const decimals = checkDecimals(options.decimals === void 0 ? 2 : options.decimals);
439
+ const date = options.date !== void 0 ? parseDate(options.date) : void 0;
440
+ const entry = date !== void 0 ? await this.dayEntry(date) : await this.latestEntry();
441
+ const [entryDay, effectiveDate] = entryDates(entry, date);
442
+ const day = date ?? entryDay;
443
+ const picked = conversionRates(entry, src, dst, day);
444
+ if (isProblem(picked)) raise(picked);
445
+ const rf = fromNumber(picked.vesPerFrom);
446
+ const rt = fromNumber(picked.vesPerTo);
447
+ const rate = div(rf, rt);
448
+ const exact = div(roundSignificant(mul(value, rf)), rt);
449
+ const result = decimals === null ? exact : quantize(exact, decimals);
450
+ const note = date !== void 0 ? carryForwardNote(date, effectiveDate) ?? null : null;
451
+ const places = decimals ?? 8;
452
+ const text = `${num(value, 2)} ${src} = ${num(result, places)} ${dst} at the official BCV rate (effective ${effectiveDate}; 1 ${src} = ${num(rate, 6)} ${dst}).`;
453
+ return {
454
+ amount: toNumber(value),
455
+ amountExact: toPlain(value),
456
+ from: src,
457
+ to: dst,
458
+ result: toNumber(result),
459
+ resultText: decimals === null ? toPlain(exact) : toFixed(result, decimals),
460
+ resultExact: toPlain(exact),
461
+ rate: toNumber(rate),
462
+ rateExact: toPlain(rate),
463
+ ratesUsed: picked.ratesUsed,
464
+ date: day,
465
+ effectiveDate,
466
+ carriedForward: note !== null,
467
+ decimals,
468
+ note,
469
+ source: SOURCE,
470
+ summary: note ? `${text} ${note}` : text
471
+ };
472
+ }
473
+ /** Freshness of the published data (`/api/v1/status.json`). */
474
+ async status() {
475
+ const doc = expectObject(await this.api.status(), "/api/v1/status.json");
476
+ const { ageHours, stale } = freshness(doc, this.clock());
477
+ const text = (v) => typeof v === "string" ? v : null;
478
+ const day = (v) => typeof v === "string" && isIsoDate(v) ? v : null;
479
+ const status = text(doc.status) ?? "unknown";
480
+ const age = ageHours !== void 0 ? ` (${ageHours} h ago)` : "";
481
+ return {
482
+ status,
483
+ updatedAt: parseTimestamp(doc.updated_at) ?? null,
484
+ generatedAt: parseTimestamp(doc.generated_at) ?? null,
485
+ date: day(doc.date),
486
+ effectiveDate: day(doc.effective_date),
487
+ ageHours: ageHours ?? null,
488
+ stale,
489
+ supportedCurrencies: Array.isArray(doc.supported_currencies) ? doc.supported_currencies.map(String) : [...CURRENCIES],
490
+ currencies: doc.currencies && typeof doc.currencies === "object" ? Object.fromEntries(Object.entries(doc.currencies).map(([k, v]) => [k, Boolean(v)])) : {},
491
+ timezone: text(doc.timezone),
492
+ apiVersion: text(doc.api_version),
493
+ summary: `Status ${status}${stale ? " (STALE)" : ""}: last capture ${text(doc.updated_at) ?? "unknown"}${age}, effective date ${day(doc.effective_date) ?? "unknown"}.`,
494
+ raw: doc
495
+ };
496
+ }
497
+ };
498
+
499
+ // src/cli.ts
500
+ var EXIT_OK = 0;
501
+ var EXIT_NO_DATA = 1;
502
+ var EXIT_USAGE = 2;
503
+ var EXIT_UPSTREAM = 3;
504
+ var PROG = "bcv-today";
505
+ var ATTRIBUTION = "Source: Banco Central de Venezuela via BCV Today (https://bcv.today). Unofficial.";
506
+ var HELP = `Usage: ${PROG} [options] <command> [args]
507
+
508
+ Official Banco Central de Venezuela exchange rates from the BCV Today API
509
+ (https://bcv.today). Unofficial client, not affiliated with the bank.
510
+
511
+ Commands:
512
+ latest rates currently in effect
513
+ on <date> [-c CUR] rate in effect on a date (YYYY-MM-DD)
514
+ convert <amount> <from> <to> convert an amount, e.g. "${PROG} convert 100 USD VES"
515
+ [-d DATE] [--decimals N]
516
+ history <currency> [-n DAYS] daily series (last N days, default 30, max ${MAX_HISTORY_DAYS})
517
+ [--start DATE] [--end DATE]
518
+ status data freshness
519
+ mcp run a local MCP server over stdio (needs @modelcontextprotocol/sdk)
520
+
521
+ Options:
522
+ --json machine-readable JSON output
523
+ --base-url URL API origin (default https://bcv.today)
524
+ --timeout SECONDS request timeout (default 10)
525
+ -h, --help show this help
526
+ -v, --version show the version
527
+
528
+ Exit codes: 0 ok, 1 no data for the request, 2 invalid arguments, 3 network/API error.`;
529
+ var OPTIONS = {
530
+ json: { type: "boolean" },
531
+ "base-url": { type: "string" },
532
+ timeout: { type: "string" },
533
+ help: { type: "boolean", short: "h" },
534
+ version: { type: "boolean", short: "v" },
535
+ currency: { type: "string", short: "c" },
536
+ date: { type: "string", short: "d" },
537
+ decimals: { type: "string" },
538
+ days: { type: "string", short: "n" },
539
+ start: { type: "string" },
540
+ end: { type: "string" }
541
+ };
542
+ var COMMON = ["json", "base-url", "timeout", "help", "version"];
543
+ var COMMANDS = {
544
+ latest: { args: [], options: [] },
545
+ on: { args: ["date"], options: ["currency"] },
546
+ convert: { args: ["amount", "from", "to"], options: ["date", "decimals"] },
547
+ history: { args: ["currency"], options: ["days", "start", "end"] },
548
+ status: { args: [], options: [] },
549
+ mcp: { args: [], options: [] }
550
+ };
551
+ var UsageError = class extends Error {
552
+ };
553
+ var NEGATIVE = /^-\d+(?:\.\d*)?$/;
554
+ var NEG_MARK = "\0";
555
+ var defaultIo = {
556
+ stdout: (t) => process.stdout.write(`${t}
557
+ `),
558
+ stderr: (t) => process.stderr.write(`${t}
559
+ `)
560
+ };
561
+ function n(value, places = 4) {
562
+ const d = typeof value === "number" ? fromNumber(value) : parseDecimal(value);
563
+ return d ? group(d, places) : String(value);
564
+ }
565
+ function table(headers, rows, align2) {
566
+ const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
567
+ const line = (cells) => cells.map((c, i) => align2[i] === "r" ? c.padStart(widths[i] ?? 0) : c.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
568
+ return [line(headers), widths.map((w) => "-".repeat(w)).join(" "), ...rows.map(line)].join("\n");
569
+ }
570
+ function bare(rows) {
571
+ return table(["", ""], rows, "ll").split("\n").slice(2).join("\n");
572
+ }
573
+ function utc(d) {
574
+ if (!d) return "unknown";
575
+ return `${d.toISOString().slice(0, 16).replace("T", " ")} UTC`;
576
+ }
577
+ function renderRates(r) {
578
+ const rows = Object.entries(r.rates).map(([c, v]) => [c, n(v)]);
579
+ return [
580
+ `Official BCV rates, effective ${r.effectiveDate} (Bs. per unit)`,
581
+ "",
582
+ table(["Currency", "Rate (VES)"], rows, "lr"),
583
+ "",
584
+ `Updated ${utc(r.updatedAt)}. ${ATTRIBUTION}`
585
+ ].join("\n");
586
+ }
587
+ function renderDay(d) {
588
+ const rows = Object.entries(d.rates).map(([c, v]) => [c, n(v)]);
589
+ const out = [
590
+ `BCV rate in effect on ${d.date} (effective date ${d.effectiveDate}, Bs. per unit)`,
591
+ "",
592
+ table(["Currency", "Rate (VES)"], rows, "lr")
593
+ ];
594
+ if (d.note) out.push("", `Note: ${d.note}`);
595
+ return [...out, "", ATTRIBUTION].join("\n");
596
+ }
597
+ function renderConversion(c) {
598
+ const places = c.decimals ?? 8;
599
+ const rows = [
600
+ ["Amount", `${n(c.amountExact, 2)} ${c.from}`],
601
+ ["Result", `${n(c.resultText, places)} ${c.to}`],
602
+ ["Rate", `1 ${c.from} = ${n(c.rateExact, 6)} ${c.to}`],
603
+ ...Object.entries(c.ratesUsed).map(([code, v]) => [`BCV ${code}`, `${n(v)} VES`]),
604
+ ["Effective", c.effectiveDate]
605
+ ];
606
+ const out = [bare(rows)];
607
+ if (c.note) out.push("", `Note: ${c.note}`);
608
+ return [...out, "", ATTRIBUTION].join("\n");
609
+ }
610
+ function renderHistory(h) {
611
+ const rows = h.points.map((p) => [p.date, p.effectiveDate + (p.carriedForward ? " *" : ""), n(p.rate)]);
612
+ const sign = h.change >= 0 ? "+" : "";
613
+ const out = [
614
+ `${h.currency}/VES official BCV rate, ${h.start} to ${h.end} (${h.points.length} days)`,
615
+ "",
616
+ table(["Date", "Effective", "Rate (VES)"], rows, "llr"),
617
+ "",
618
+ `First ${n(h.first.rate)} Last ${n(h.last.rate)} Change ${sign}${n(h.changeExact)} (${sign}${h.changePct.toFixed(2)}%)`,
619
+ `Min ${n(h.min.rate)} on ${h.min.date} Max ${n(h.max.rate)} on ${h.max.date}`
620
+ ];
621
+ if (h.points.some((p) => p.carriedForward))
622
+ out.push("* rate carried forward from the effective date (weekend/holiday).");
623
+ if (h.note) out.push(`Note: ${h.note}`);
624
+ return [...out, ATTRIBUTION].join("\n");
625
+ }
626
+ function renderStatus(s) {
627
+ return bare([
628
+ ["Status", s.status + (s.stale ? " (STALE)" : "")],
629
+ ["Updated", typeof s.raw.updated_at === "string" && s.updatedAt ? s.raw.updated_at : "unknown"],
630
+ ["Age", s.ageHours !== null ? `${s.ageHours} h` : "unknown"],
631
+ ["Effective date", s.effectiveDate ?? "unknown"],
632
+ ["Currencies", s.supportedCurrencies.join(", ")]
633
+ ]);
634
+ }
635
+ function stamp(raw, parsed) {
636
+ return parsed ? typeof raw === "string" ? raw : parsed.toISOString() : null;
637
+ }
638
+ var point = (p) => ({ date: p.date, rate: p.rate });
639
+ function toJson(result, kind) {
640
+ switch (kind) {
641
+ case "latest": {
642
+ const r = result;
643
+ return {
644
+ rates: r.rates,
645
+ date: r.date,
646
+ effective_date: r.effectiveDate,
647
+ updated_at: stamp(r.raw.updated_at, r.updatedAt),
648
+ unit: UNIT,
649
+ source: r.source
650
+ };
651
+ }
652
+ case "on": {
653
+ const d = result;
654
+ return {
655
+ date: d.date,
656
+ effective_date: d.effectiveDate,
657
+ carried_forward: d.carriedForward,
658
+ rates: d.rates,
659
+ updated_at: stamp(d.raw.updated_at, d.updatedAt),
660
+ unit: UNIT,
661
+ source: d.source,
662
+ ...d.note ? { note: d.note } : {}
663
+ };
664
+ }
665
+ case "history": {
666
+ const h = result;
667
+ return {
668
+ currency: h.currency,
669
+ from: h.start,
670
+ to: h.end,
671
+ points: h.points.length,
672
+ first: point(h.first),
673
+ last: point(h.last),
674
+ min: point(h.min),
675
+ max: point(h.max),
676
+ change: h.change,
677
+ change_pct: h.changePct,
678
+ series: h.points.map((p) => ({ date: p.date, effective_date: p.effectiveDate, rate: p.rate })),
679
+ unit: UNIT,
680
+ source: h.source,
681
+ ...h.note ? { note: h.note } : {}
682
+ };
683
+ }
684
+ case "convert": {
685
+ const c = result;
686
+ return {
687
+ amount: c.amount,
688
+ from: c.from,
689
+ to: c.to,
690
+ result: c.result,
691
+ result_text: c.resultText,
692
+ result_exact: c.resultExact,
693
+ rate: c.rate,
694
+ rates_used: c.ratesUsed,
695
+ date: c.date,
696
+ effective_date: c.effectiveDate,
697
+ carried_forward: c.carriedForward,
698
+ source: c.source,
699
+ ...c.note ? { note: c.note } : {}
700
+ };
701
+ }
702
+ default: {
703
+ const s = result;
704
+ return {
705
+ status: s.status,
706
+ updated_at: stamp(s.raw.updated_at, s.updatedAt),
707
+ generated_at: stamp(s.raw.generated_at, s.generatedAt),
708
+ date: s.date,
709
+ effective_date: s.effectiveDate,
710
+ age_hours: s.ageHours,
711
+ stale: s.stale,
712
+ supported_currencies: s.supportedCurrencies,
713
+ currencies: s.currencies,
714
+ timezone: s.timezone,
715
+ api_version: s.apiVersion,
716
+ source: SOURCE
717
+ };
718
+ }
719
+ }
720
+ }
721
+ function parse(argv) {
722
+ let parsed;
723
+ try {
724
+ const args = argv.map((a) => NEGATIVE.test(a) ? `${NEG_MARK}${a}` : a);
725
+ parsed = parseArgs({ args, options: OPTIONS, allowPositionals: true, strict: true });
726
+ const unmark = (a) => a.startsWith(NEG_MARK) ? a.slice(NEG_MARK.length) : a;
727
+ parsed.positionals = parsed.positionals.map(unmark);
728
+ for (const [k, v] of Object.entries(parsed.values)) if (typeof v === "string") parsed.values[k] = unmark(v);
729
+ } catch (err) {
730
+ throw new UsageError(err.message);
731
+ }
732
+ const values = parsed.values;
733
+ if (values.version) return "version";
734
+ if (values.help) return "help";
735
+ const [command, ...positionals] = parsed.positionals;
736
+ if (!command) throw new UsageError("missing command");
737
+ const spec = COMMANDS[command];
738
+ if (!spec) throw new UsageError(`unknown command "${command}" (choose from ${Object.keys(COMMANDS).join(", ")})`);
739
+ if (positionals.length !== spec.args.length) {
740
+ const want = spec.args.length ? spec.args.map((a) => `<${a}>`).join(" ") : "no arguments";
741
+ throw new UsageError(`"${command}" expects ${want}`);
742
+ }
743
+ for (const key of Object.keys(values)) {
744
+ if (!COMMON.includes(key) && !spec.options.includes(key)) {
745
+ throw new UsageError(`option --${key} is not valid for "${command}"`);
746
+ }
747
+ }
748
+ return { command, positionals, values };
749
+ }
750
+ function int(value, label) {
751
+ if (value === void 0) return void 0;
752
+ if (typeof value !== "string" || !/^-?\d+$/.test(value.trim())) {
753
+ throw new UsageError(`argument --${label}: invalid int value: '${String(value)}'`);
754
+ }
755
+ return Number(value);
756
+ }
757
+ async function main(argv = process.argv.slice(2), io = defaultIo, client) {
758
+ let args;
759
+ try {
760
+ const p = parse(argv);
761
+ if (p === "version") {
762
+ io.stdout(`${PROG} ${VERSION}`);
763
+ return EXIT_OK;
764
+ }
765
+ if (p === "help") {
766
+ io.stdout(HELP);
767
+ return EXIT_OK;
768
+ }
769
+ args = p;
770
+ } catch (err) {
771
+ if (!(err instanceof UsageError)) throw err;
772
+ io.stderr(`Usage: ${PROG} [options] <command> [args] (${PROG} --help for details)`);
773
+ io.stderr(`${PROG}: error: ${err.message}`);
774
+ return EXIT_USAGE;
775
+ }
776
+ const { command, positionals: pos, values } = args;
777
+ const asJson = values.json === true;
778
+ try {
779
+ const timeoutSec = values.timeout !== void 0 ? Number(values.timeout) : 10;
780
+ if (!Number.isFinite(timeoutSec) || timeoutSec < 0) {
781
+ throw new UsageError(`argument --timeout: invalid float value: '${String(values.timeout)}'`);
782
+ }
783
+ const baseUrl = typeof values["base-url"] === "string" ? values["base-url"] : void 0;
784
+ if (command === "mcp") {
785
+ const { runStdioServer } = await import("./stdio-HI6U6UUH.js");
786
+ await runStdioServer({ ...baseUrl ? { baseUrl } : {}, timeoutMs: timeoutSec * 1e3 });
787
+ return EXIT_OK;
788
+ }
789
+ const bcv = client ?? new BCV({ ...baseUrl ? { baseUrl } : {}, timeoutMs: timeoutSec * 1e3 });
790
+ let result;
791
+ let text;
792
+ switch (command) {
793
+ case "latest": {
794
+ const r = await bcv.latest();
795
+ [result, text] = [r, renderRates(r)];
796
+ break;
797
+ }
798
+ case "on": {
799
+ const d = await bcv.on(pos[0], values.currency);
800
+ [result, text] = [d, renderDay(d)];
801
+ break;
802
+ }
803
+ case "convert": {
804
+ const decimals = int(values.decimals, "decimals");
805
+ const c = await bcv.convert(pos[0], pos[1], pos[2], {
806
+ ...values.date !== void 0 ? { date: values.date } : {},
807
+ ...decimals !== void 0 ? { decimals } : {}
808
+ });
809
+ [result, text] = [c, renderConversion(c)];
810
+ break;
811
+ }
812
+ case "history": {
813
+ const days = int(values.days, "days");
814
+ const h = await bcv.history(pos[0], {
815
+ ...days !== void 0 ? { days } : {},
816
+ ...values.start !== void 0 ? { start: values.start } : {},
817
+ ...values.end !== void 0 ? { end: values.end } : {}
818
+ });
819
+ [result, text] = [h, renderHistory(h)];
820
+ break;
821
+ }
822
+ default: {
823
+ const s = await bcv.status();
824
+ [result, text] = [s, renderStatus(s)];
825
+ }
826
+ }
827
+ io.stdout(asJson ? JSON.stringify(toJson(result, command), null, 2) : text);
828
+ return EXIT_OK;
829
+ } catch (err) {
830
+ if (err instanceof UsageError) {
831
+ io.stderr(`${PROG}: error: ${err.message}`);
832
+ return EXIT_USAGE;
833
+ }
834
+ if (err instanceof BCVError || err instanceof Error && err.name === "MissingSdk") {
835
+ const code = err instanceof InvalidArgument || err.name === "MissingSdk" ? EXIT_USAGE : err instanceof UpstreamError ? EXIT_UPSTREAM : EXIT_NO_DATA;
836
+ if (asJson) io.stdout(JSON.stringify({ error: { type: err.name, message: err.message } }));
837
+ io.stderr(`${PROG}: error: ${err.message}`);
838
+ return code;
839
+ }
840
+ throw err;
841
+ }
842
+ }
843
+
844
+ // src/bin.ts
845
+ main().then(
846
+ (code) => {
847
+ if (code !== EXIT_OK) process.exitCode = code;
848
+ },
849
+ (err) => {
850
+ process.stderr.write(`bcv-today: unexpected error: ${err?.stack ?? String(err)}
851
+ `);
852
+ process.exitCode = EXIT_UPSTREAM;
853
+ }
854
+ );