bcv-today 0.0.0-stage → 1.0.1

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.
@@ -0,0 +1,412 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/rules.ts
4
+ var CURRENCIES = ["USD", "EUR", "CNY", "TRY", "RUB"];
5
+ var ANY_CURRENCIES = ["VES", ...CURRENCIES];
6
+ var SOURCE = "Banco Central de Venezuela (BCV), via https://bcv.today";
7
+ var UNIT = "VES (bolivars) per 1 unit of the currency";
8
+ var EARLIEST_SNAPSHOT = "2021-08-02";
9
+ var MAX_HISTORY_DAYS = 1830;
10
+ var MAX_AMOUNT = 1e15;
11
+ var STALE_AFTER_HOURS = 96;
12
+ var LATEST_PATH = "/api/v1/rate.json";
13
+ var HISTORY_PATH = "/api/v1/history.json";
14
+ var STATUS_PATH = "/api/v1/status.json";
15
+ var dayPath = (date) => `/api/v1/history/${date}.json`;
16
+ function rateOf(entry, currency) {
17
+ const v = entry[currency];
18
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : void 0;
19
+ }
20
+ function ratesOf(entry) {
21
+ const out = {};
22
+ for (const c of CURRENCIES) {
23
+ const v = rateOf(entry, c);
24
+ if (v !== void 0) out[c] = v;
25
+ }
26
+ return out;
27
+ }
28
+ var ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
29
+ var WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
30
+ function isIsoDate(s) {
31
+ const m = ISO_DATE.exec(s);
32
+ if (!m) return false;
33
+ const d = /* @__PURE__ */ new Date(`${s}T00:00:00Z`);
34
+ return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s;
35
+ }
36
+ function todayCaracas(now = Date.now()) {
37
+ return new Date(now - 4 * 3600 * 1e3).toISOString().slice(0, 10);
38
+ }
39
+ function addDays(date, days) {
40
+ const d = /* @__PURE__ */ new Date(`${date}T00:00:00Z`);
41
+ d.setUTCDate(d.getUTCDate() + days);
42
+ return d.toISOString().slice(0, 10);
43
+ }
44
+ function weekday(date) {
45
+ return WEEKDAYS[(/* @__PURE__ */ new Date(`${date}T00:00:00Z`)).getUTCDay()] ?? "";
46
+ }
47
+ function parseTimestamp(value) {
48
+ if (typeof value !== "string" || value === "") return void 0;
49
+ const t = Date.parse(value);
50
+ return Number.isFinite(t) ? new Date(t) : void 0;
51
+ }
52
+ var TOOL_HINTS = { latest: "get_latest_rates", onDay: "get_rate_by_date" };
53
+ var LIBRARY_HINTS = { latest: "latest()", onDay: "on()" };
54
+ function invalidDateMessage(label, value, example = true) {
55
+ return `Invalid ${label} "${value}": use a real calendar date in YYYY-MM-DD format${example ? ", e.g. 2026-01-02" : ""}.`;
56
+ }
57
+ function rangeOrderMessage(fromLabel, from, toLabel, to) {
58
+ return `"${fromLabel}" (${from}) must be on or before "${toLabel}" (${to}).`;
59
+ }
60
+ function sameCurrencyMessage(code) {
61
+ return `"from" and "to" are both ${code}; choose two different currencies.`;
62
+ }
63
+ function notPublishedMessage(date, latest, hints) {
64
+ return `No BCV rate published yet for ${date}. Daily snapshots are available from ${EARLIEST_SNAPSHOT}` + (latest ? ` to ${latest}.` : " to the latest business day.") + ` Use ${hints.latest} for the rate currently in effect.`;
65
+ }
66
+ function carryForwardNote(date, effective) {
67
+ if (!effective || effective === date) return void 0;
68
+ return `${date} (${weekday(date)}) uses the rate with effective date ${effective} (${weekday(effective)}): a published BCV rate stays in effect until the next publication (weekends and holidays carry it forward).`;
69
+ }
70
+ function checkDay(date, today = todayCaracas(), label = "date") {
71
+ if (!isIsoDate(date)) return { kind: "invalid_date", message: invalidDateMessage(label, date) };
72
+ if (date < EARLIEST_SNAPSHOT) {
73
+ return { kind: "out_of_range", message: `No BCV data for ${date}: daily snapshots start on ${EARLIEST_SNAPSHOT}.` };
74
+ }
75
+ if (date > addDays(today, 1)) {
76
+ return {
77
+ kind: "out_of_range",
78
+ message: `${date} is in the future (today in Caracas is ${today}); BCV rates are only known up to the next business day.`
79
+ };
80
+ }
81
+ return void 0;
82
+ }
83
+ function pickRates(entry, date, currency) {
84
+ const all = ratesOf(entry);
85
+ if (!currency) return { rates: all };
86
+ const v = all[currency];
87
+ if (v === void 0) {
88
+ const avail = Object.keys(all).join(", ") || "none";
89
+ return {
90
+ kind: "not_available",
91
+ message: `No ${currency} rate in the BCV data for ${date} (older entries may lack some currencies). Available that day: ${avail}.`
92
+ };
93
+ }
94
+ return { rates: { [currency]: v } };
95
+ }
96
+ function conversionRates(entry, from, to, day) {
97
+ const vesPer = (c) => c === "VES" ? 1 : rateOf(entry, c);
98
+ const rf = vesPer(from);
99
+ const rt = vesPer(to);
100
+ if (rf === void 0 || rt === void 0) {
101
+ const missing = [from, to].filter((_, i) => (i === 0 ? rf : rt) === void 0);
102
+ return {
103
+ kind: "not_available",
104
+ message: `No BCV rate for ${missing.join(" and ")} on ${day} (older entries may lack some currencies). Available: ${Object.keys(ratesOf(entry)).join(", ")}.`
105
+ };
106
+ }
107
+ const ratesUsed = {};
108
+ if (from !== "VES") ratesUsed[from] = rf;
109
+ if (to !== "VES") ratesUsed[to] = rt;
110
+ return { vesPerFrom: rf, vesPerTo: rt, ratesUsed };
111
+ }
112
+ function historyWindow(entries, currency, req, hints = TOOL_HINTS) {
113
+ const { days, from, to } = req;
114
+ const series = entries.filter((e) => typeof e.date === "string" && rateOf(e, currency) !== void 0).map((e) => ({ date: e.date, effective_date: e.effective_date ?? e.date, rate: rateOf(e, currency) }));
115
+ series.sort((a, b) => a.date < b.date ? -1 : a.date > b.date ? 1 : 0);
116
+ if (series.length === 0) return { kind: "not_available", message: `No ${currency} data in the BCV history.` };
117
+ const earliest = series[0].date;
118
+ const latest = series[series.length - 1].date;
119
+ let start;
120
+ let end;
121
+ if (from || to) {
122
+ start = from ?? earliest;
123
+ end = to ?? latest;
124
+ } else {
125
+ end = latest;
126
+ start = addDays(latest, -((days ?? 30) - 1));
127
+ }
128
+ const window = series.filter((p) => p.date >= start && p.date <= end);
129
+ if (window.length === 0) {
130
+ return {
131
+ kind: "out_of_range",
132
+ message: `No ${currency} rates between ${start} and ${end}. The history covers ${earliest} to ${latest} for ${currency} (latest ${MAX_HISTORY_DAYS} daily entries). For older single days use ${hints.onDay}.`
133
+ };
134
+ }
135
+ const first = window[0];
136
+ const last = window[window.length - 1];
137
+ let min = first;
138
+ let max = first;
139
+ for (const p of window) {
140
+ if (p.rate < min.rate) min = p;
141
+ if (p.rate > max.rate) max = p;
142
+ }
143
+ const notes = [];
144
+ if (start < earliest) notes.push(`History for ${currency} starts on ${earliest}; earlier dates were skipped.`);
145
+ if (end > latest) notes.push(`Latest available date is ${latest}.`);
146
+ return { series: window, first, last, min, max, notes };
147
+ }
148
+ function round(n, digits = 8) {
149
+ const f = 10 ** digits;
150
+ return Math.round(n * f) / f;
151
+ }
152
+ function freshness(doc, now = Date.now()) {
153
+ const updated = doc.updated_at ? Date.parse(doc.updated_at) : Number.NaN;
154
+ const ageHours = Number.isFinite(updated) ? round((now - updated) / 36e5, 1) : void 0;
155
+ const stale = ageHours === void 0 || ageHours > STALE_AFTER_HOURS || doc.status !== "ok";
156
+ return { ageHours, stale };
157
+ }
158
+ function isProblem(v) {
159
+ return typeof v === "object" && v !== null && "kind" in v && "message" in v && !("series" in v);
160
+ }
161
+
162
+ // src/errors.ts
163
+ var BCVError = class extends Error {
164
+ // Explicit names survive bundlers that rename classes.
165
+ name = "BCVError";
166
+ constructor(message, options) {
167
+ super(message);
168
+ if (options && "cause" in options) {
169
+ Object.defineProperty(this, "cause", { value: options.cause, writable: true, configurable: true });
170
+ }
171
+ }
172
+ };
173
+ var InvalidArgument = class extends BCVError {
174
+ name = "InvalidArgument";
175
+ };
176
+ var InvalidDate = class extends InvalidArgument {
177
+ name = "InvalidDate";
178
+ };
179
+ var InvalidCurrency = class extends InvalidArgument {
180
+ name = "InvalidCurrency";
181
+ };
182
+ var InvalidAmount = class extends InvalidArgument {
183
+ name = "InvalidAmount";
184
+ };
185
+ var DateOutOfRange = class extends BCVError {
186
+ name = "DateOutOfRange";
187
+ };
188
+ var CurrencyNotAvailable = class extends BCVError {
189
+ name = "CurrencyNotAvailable";
190
+ };
191
+ var NotFound = class extends BCVError {
192
+ name = "NotFound";
193
+ };
194
+ var UpstreamError = class extends BCVError {
195
+ name = "UpstreamError";
196
+ /** HTTP status code, when the error came from an HTTP response. */
197
+ status;
198
+ constructor(message, status, options) {
199
+ super(message, options);
200
+ this.status = status;
201
+ }
202
+ };
203
+
204
+ // src/api.ts
205
+ var DEFAULT_BASE_URL = "https://bcv.today";
206
+ var TTLCache = class _TTLCache {
207
+ constructor(ttlMs, clock = Date.now) {
208
+ this.ttlMs = ttlMs;
209
+ this.clock = clock;
210
+ }
211
+ ttlMs;
212
+ clock;
213
+ static MAX_ENTRIES = 64;
214
+ data = /* @__PURE__ */ new Map();
215
+ get(key) {
216
+ if (this.ttlMs <= 0) return void 0;
217
+ const hit = this.data.get(key);
218
+ if (!hit) return void 0;
219
+ if (hit.expires <= this.clock()) {
220
+ this.data.delete(key);
221
+ return void 0;
222
+ }
223
+ return hit.value;
224
+ }
225
+ set(key, value) {
226
+ if (this.ttlMs <= 0) return;
227
+ if (this.data.size >= _TTLCache.MAX_ENTRIES) this.data.clear();
228
+ this.data.set(key, { expires: this.clock() + this.ttlMs, value });
229
+ }
230
+ clear() {
231
+ this.data.clear();
232
+ }
233
+ };
234
+ function isBrowserLike() {
235
+ const nav = globalThis.navigator;
236
+ return typeof nav?.userAgent === "string" && nav.userAgent.startsWith("Mozilla/");
237
+ }
238
+ var Api = class {
239
+ baseUrl;
240
+ timeoutMs;
241
+ cache;
242
+ fetchImpl;
243
+ headersBase;
244
+ init;
245
+ inflight = /* @__PURE__ */ new Map();
246
+ constructor(opts = {}) {
247
+ this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
248
+ this.timeoutMs = opts.timeoutMs ?? 1e4;
249
+ this.cache = opts.cache ?? new TTLCache(3e5);
250
+ this.fetchImpl = opts.fetch;
251
+ this.headersBase = opts.userAgent && !isBrowserLike() ? { "user-agent": opts.userAgent } : {};
252
+ this.init = opts.init ?? {};
253
+ }
254
+ async request(path, accept) {
255
+ const url = this.baseUrl + path;
256
+ const doFetch = this.fetchImpl ?? (typeof fetch === "function" ? fetch : void 0);
257
+ if (!doFetch) {
258
+ throw new UpstreamError("No fetch implementation available: pass { fetch } to the client.");
259
+ }
260
+ const init = { ...this.init, headers: { accept, ...this.headersBase } };
261
+ let timer;
262
+ let controller;
263
+ if (this.timeoutMs > 0 && typeof AbortController === "function") {
264
+ controller = new AbortController();
265
+ init.signal = controller.signal;
266
+ timer = setTimeout(() => controller?.abort(), this.timeoutMs);
267
+ }
268
+ try {
269
+ let res;
270
+ try {
271
+ res = await doFetch(url, init);
272
+ } catch (err) {
273
+ const reason = controller?.signal.aborted ? `timed out after ${this.timeoutMs} ms` : errorText(err);
274
+ throw new UpstreamError(
275
+ `Could not reach the BCV Today data API (${reason}). Try again in a moment.`,
276
+ void 0,
277
+ {
278
+ cause: err
279
+ }
280
+ );
281
+ }
282
+ if (res.status === 404) {
283
+ await discard(res);
284
+ throw new NotFound(`Not found: ${path}`);
285
+ }
286
+ if (!res.ok) {
287
+ await discard(res);
288
+ throw new UpstreamError(
289
+ `The BCV Today data API answered HTTP ${res.status} for ${path}. Try again in a moment.`,
290
+ res.status
291
+ );
292
+ }
293
+ try {
294
+ return await res.text();
295
+ } catch (err) {
296
+ const reason = controller?.signal.aborted ? `timed out after ${this.timeoutMs} ms` : errorText(err);
297
+ throw new UpstreamError(
298
+ `Could not reach the BCV Today data API (${reason}). Try again in a moment.`,
299
+ void 0,
300
+ {
301
+ cause: err
302
+ }
303
+ );
304
+ }
305
+ } finally {
306
+ if (timer !== void 0) clearTimeout(timer);
307
+ }
308
+ }
309
+ /** Memoised fetch: one network request per key while it is cached or in flight. */
310
+ memo(key, load) {
311
+ const hit = this.cache.get(key);
312
+ if (hit !== void 0) return Promise.resolve(hit);
313
+ const pending = this.inflight.get(key);
314
+ if (pending) return pending;
315
+ const p = load().then(
316
+ (value) => {
317
+ this.inflight.delete(key);
318
+ this.cache.set(key, value);
319
+ return value;
320
+ },
321
+ (err) => {
322
+ this.inflight.delete(key);
323
+ throw err;
324
+ }
325
+ );
326
+ this.inflight.set(key, p);
327
+ return p;
328
+ }
329
+ /** Raw text of any path on the origin (e.g. "/llms.txt"). */
330
+ text(path, accept = "text/plain") {
331
+ return this.memo(`${accept} ${path}`, () => this.request(path, accept));
332
+ }
333
+ /** Parsed JSON of a path; errors are never cached. */
334
+ json(path) {
335
+ return this.memo(`json ${path}`, async () => {
336
+ const text = await this.request(path, "application/json");
337
+ try {
338
+ return JSON.parse(text);
339
+ } catch {
340
+ throw new UpstreamError(`The BCV Today data API returned invalid JSON for ${path}.`);
341
+ }
342
+ });
343
+ }
344
+ latest() {
345
+ return this.json(LATEST_PATH);
346
+ }
347
+ status() {
348
+ return this.json(STATUS_PATH);
349
+ }
350
+ async history() {
351
+ const data = await this.json(HISTORY_PATH);
352
+ if (!Array.isArray(data)) {
353
+ throw new UpstreamError("Unexpected history.json shape (expected an array).");
354
+ }
355
+ return data;
356
+ }
357
+ /** Snapshot for one calendar day; rejects with NotFound when out of range. */
358
+ day(date) {
359
+ return this.json(dayPath(date));
360
+ }
361
+ };
362
+ function errorText(err) {
363
+ return err instanceof Error ? err.message : String(err);
364
+ }
365
+ async function discard(res) {
366
+ try {
367
+ await res.body?.cancel();
368
+ } catch {
369
+ }
370
+ }
371
+
372
+ // src/version.ts
373
+ var VERSION = "1.0.1";
374
+
375
+ export {
376
+ BCVError,
377
+ InvalidArgument,
378
+ InvalidDate,
379
+ InvalidCurrency,
380
+ InvalidAmount,
381
+ DateOutOfRange,
382
+ CurrencyNotAvailable,
383
+ NotFound,
384
+ UpstreamError,
385
+ CURRENCIES,
386
+ ANY_CURRENCIES,
387
+ SOURCE,
388
+ UNIT,
389
+ MAX_HISTORY_DAYS,
390
+ MAX_AMOUNT,
391
+ isIsoDate,
392
+ todayCaracas,
393
+ parseTimestamp,
394
+ TOOL_HINTS,
395
+ LIBRARY_HINTS,
396
+ invalidDateMessage,
397
+ rangeOrderMessage,
398
+ sameCurrencyMessage,
399
+ notPublishedMessage,
400
+ carryForwardNote,
401
+ checkDay,
402
+ pickRates,
403
+ conversionRates,
404
+ historyWindow,
405
+ round,
406
+ freshness,
407
+ isProblem,
408
+ DEFAULT_BASE_URL,
409
+ TTLCache,
410
+ Api,
411
+ VERSION
412
+ };