From dce1e89917c12c0b213d1668f7ed03f70d9c7dee Mon Sep 17 00:00:00 2001 From: Harshvardhan Date: Thu, 19 Nov 2026 23:53:06 +0400 Subject: [PATCH] Convert the currencies beyond the ECB set The calculator knew the 30 currencies in the ECB reference rates, so "100 usd to dop" or "100 aed to inr" gave no result. frankfurter.dev's v2 API publishes rates from more central banks, so fetch /v2/rates and add the other 131 currencies it carries. The new currencies have no symbol and answer to their code or full name only, so none of them takes a name from a unit or from the 30 currencies already there. Rate parsing moves into core/Calculator.js (parseRates) so node can test it; it reads the v2 answer and the cache. Closes #106 Co-Authored-By: Claude Fable 5.2 --- CLAUDE.md | 2 +- README.md | 6 +- core/Calculator.js | 181 +++++++++++++++++++++++++++++++++++- core/Schema.js | 2 +- services/CalculatorData.qml | 13 +-- site/README.md | 2 +- site/public/index.html | 2 +- site/snapshot.mjs | 2 +- tests/calculator.test.js | 34 +++++++ 9 files changed, 224 insertions(+), 20 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index f0dfa48..10b5014 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -143,7 +143,7 @@ Works: - arithmetic and functions - Soulver-style percentages (`$30 + 20%`, `20% off 50`, `50 as a % of 200`) - ~250 units (`5 ft to cm`, `60 mph * 2 h`, `16px to rem`) - - currencies (ECB rates from frankfurter.dev, cached daily in `~/.cache/omacast/currencies.json`; turn off with `"currencyRates": false` in config.json) + - currencies (~160, central-bank rates from frankfurter.dev's v2 API, cached daily in `~/.cache/omacast/currencies.json`; turn off with `"currencyRates": false` in config.json) - dates (`3 days from now`, `days until christmas`) - time zones (`time in tokyo`, `3pm london to nyc`; offsets come from one bash `printf %(%z)T` pass because QML has no Intl) - bases (`255 to hex`) diff --git a/README.md b/README.md index d580440..a6a8cfb 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,7 @@ has its own engine, so there's nothing to install. | Arithmetic and functions | `2^10`, `sqrt(2) * 10`, `sin(30°)` | | Percentages | `$30 + 20%`, `20% off 50`, `50 as a % of 200` | | ~250 units, including mixed units | `5 ft to cm`, `5 ft 3 in to cm`, `60 mph * 2 h`, `16px to rem` | -| Currencies | `100 usd in eur` | +| ~160 currencies | `100 usd in eur`, `100 aed to inr` | | Dates | `3 days from now`, `days until christmas` | | Time zones | `time in tokyo`, `3pm london to nyc` | | Number bases | `255 to hex` | @@ -140,7 +140,7 @@ has its own engine, so there's nothing to install. "question = answer". Each one is saved to **Calculator History** (searchable, kept for 90 days; `Ctrl+D` deletes an entry, `Ctrl+Shift+D` deletes all). Trig takes radians unless you add `°` or `deg`. -Currency rates are ECB reference rates (see [network access](#dependencies-and-network-access)). +Currency rates are central-bank reference rates (see [network access](#dependencies-and-network-access)). `config.json` sets `remToPxRate` (16), `workHoursPerDay` (8) and `clockFormat` (`auto` follows your locale, or `12h` / `24h`). @@ -307,7 +307,7 @@ It adds no packages and no background services. (`com.superwhisper.ShellOverlay`), so Superwhisper's recording glow or pill draws on the launcher instead of the window under it. It makes no network requests, and does nothing without Superwhisper. - **Currency rates.** When you open the launcher and its rates are over 12 hours old, the calculator downloads - ECB exchange rates from `api.frankfurter.dev` (retrying 30 minutes after a failure) and caches them in + central-bank exchange rates from `api.frankfurter.dev` (retrying 30 minutes after a failure) and caches them in `~/.cache/omacast/currencies.json`. This is the only network request omacast makes. Turn it off with `"currencyRates": false` in `~/.config/omacast/config.json`. - **Optional search helper.** With Rust (`cargo`) installed, `omacast install` (or `omacast build-search`) diff --git a/core/Calculator.js b/core/Calculator.js index 2c94892..f70f04b 100644 --- a/core/Calculator.js +++ b/core/Calculator.js @@ -5,7 +5,7 @@ // arithmetic 2+2, 3(4+5), 2^10, 5!, 10 mod 3, sqrt 16, sin(30°), 2pi // percentages 20% of 50, 20% off 50, 20% on 50, $30 + 20%, 50 as a % of 200 // units 5 ft to cm, 60 mph in km/h, 1 GiB to MB, 100 °F to °C, 16px to rem -// currencies 10 usd to eur, €30 in £, $5k + 10% (env.rates, ECB via frankfurter) +// currencies 10 usd to eur, €30 in £, $5k + 10% (env.rates, central banks via frankfurter) // dates 3 days from now, christmas - today, days until dec 25, 2 weeks ago // time zones time in tokyo, tokyo time, 3pm london to new york (env.zones) // bases 255 to hex, 0xff + 1, 10 in binary @@ -254,8 +254,8 @@ def(["pt"], ["point", "points"], { P: 1 }, 4 / 3) var REM = def(["rem"], ["rem", "rems"], { P: 1 }, 16) var EM = def(["em"], ["em", "ems"], { P: 1 }, 16) -// Currencies: ECB reference rates (frankfurter.app). factor is resolved per -// call from env.rates, so it is 0 here. +// Currencies: central-bank reference rates (frankfurter.dev). factor is +// resolved per call from env.rates, so it is 0 here. var CURRENCIES = { USD: { symbol: "$", names: ["dollar", "dollars", "us dollar", "us dollars", "buck", "bucks", "usd"] }, EUR: { symbol: "€", names: ["euro", "euros", "eur"] }, @@ -288,12 +288,153 @@ var CURRENCIES = { PHP: { symbol: "", names: ["philippine peso", "philippine pesos", "php"] }, IDR: { symbol: "", names: ["rupiah", "indonesian rupiah", "idr"], decimals: 0 } } +// The other currencies frankfurter.dev v2 publishes, from central banks +// beyond the ECB. They have no symbol ("12.34 AED") and are named in full +// only, so a name here never takes over a unit or a currency above. label +// is the caption; names are what the parser accepts. +var MORE_CURRENCIES = { + AED: { label: "United Arab Emirates Dirham", names: ["united arab emirates dirham", "united arab emirates dirhams"] }, + AFN: { label: "Afghan Afghani", names: ["afghan afghani", "afghan afghanis"] }, + ALL: { label: "Albanian Lek", names: ["albanian lek", "albanian leks"] }, + AMD: { label: "Armenian Dram", names: ["armenian dram", "armenian drams"] }, + ANG: { label: "Netherlands Antillean Guilder", names: ["netherlands antillean guilder", "netherlands antillean guilders"] }, + AOA: { label: "Angolan Kwanza", names: ["angolan kwanza", "angolan kwanzas"] }, + ARS: { label: "Argentine Peso", names: ["argentine peso", "argentine pesos"] }, + AWG: { label: "Aruban Florin", names: ["aruban florin", "aruban florins"] }, + AZN: { label: "Azerbaijani Manat", names: ["azerbaijani manat", "azerbaijani manats"] }, + BAM: { label: "Bosnia and Herzegovina Convertible Mark", names: ["bosnia and herzegovina convertible mark", "bosnia and herzegovina convertible marks"] }, + BBD: { label: "Barbadian Dollar", names: ["barbadian dollar", "barbadian dollars"] }, + BDT: { label: "Bangladeshi Taka", names: ["bangladeshi taka", "bangladeshi takas"] }, + BHD: { label: "Bahraini Dinar", names: ["bahraini dinar", "bahraini dinars"], decimals: 3 }, + BIF: { label: "Burundian Franc", names: ["burundian franc", "burundian francs"], decimals: 0 }, + BMD: { label: "Bermudian Dollar", names: ["bermudian dollar", "bermudian dollars"] }, + BND: { label: "Brunei Dollar", names: ["brunei dollar", "brunei dollars"] }, + BOB: { label: "Bolivian Boliviano", names: ["bolivian boliviano", "bolivian bolivianos"] }, + BSD: { label: "Bahamian Dollar", names: ["bahamian dollar", "bahamian dollars"] }, + BTN: { label: "Bhutanese Ngultrum", names: ["bhutanese ngultrum", "bhutanese ngultrums"] }, + BWP: { label: "Botswana Pula", names: ["botswana pula", "botswana pulas"] }, + BYN: { label: "Belarusian Ruble", names: ["belarusian ruble", "belarusian rubles"] }, + BZD: { label: "Belize Dollar", names: ["belize dollar", "belize dollars"] }, + CDF: { label: "Congolese Franc", names: ["congolese franc", "congolese francs"] }, + CLP: { label: "Chilean Peso", names: ["chilean peso", "chilean pesos"], decimals: 0 }, + CMD: { label: "COMESA Dollar", names: ["comesa dollar", "comesa dollars"] }, + CNH: { label: "Chinese Renminbi Yuan Offshore", names: ["chinese renminbi yuan offshore", "chinese renminbi yuan offshores"] }, + COP: { label: "Colombian Peso", names: ["colombian peso", "colombian pesos"] }, + CRC: { label: "Costa Rican Colón", names: ["costa rican colón", "costa rican colóns", "costa rican colon", "costa rican colons"] }, + CUP: { label: "Cuban Peso", names: ["cuban peso", "cuban pesos"] }, + CVE: { label: "Cape Verdean Escudo", names: ["cape verdean escudo", "cape verdean escudos"] }, + DJF: { label: "Djiboutian Franc", names: ["djiboutian franc", "djiboutian francs"], decimals: 0 }, + DOP: { label: "Dominican Peso", names: ["dominican peso", "dominican pesos"] }, + DZD: { label: "Algerian Dinar", names: ["algerian dinar", "algerian dinars"] }, + EGP: { label: "Egyptian Pound", names: ["egyptian pound", "egyptian pounds"] }, + ERN: { label: "Eritrean Nakfa", names: ["eritrean nakfa", "eritrean nakfas"] }, + ETB: { label: "Ethiopian Birr", names: ["ethiopian birr", "ethiopian birrs"] }, + FJD: { label: "Fijian Dollar", names: ["fijian dollar", "fijian dollars"] }, + FKP: { label: "Falkland Pound", names: ["falkland pound", "falkland pounds"] }, + GEL: { label: "Georgian Lari", names: ["georgian lari", "georgian laris"] }, + GGP: { label: "Guernsey Pound", names: ["guernsey pound", "guernsey pounds"] }, + GHS: { label: "Ghanaian Cedi", names: ["ghanaian cedi", "ghanaian cedis"] }, + GIP: { label: "Gibraltar Pound", names: ["gibraltar pound", "gibraltar pounds"] }, + GMD: { label: "Gambian Dalasi", names: ["gambian dalasi", "gambian dalasis"] }, + GNF: { label: "Guinean Franc", names: ["guinean franc", "guinean francs"], decimals: 0 }, + GTQ: { label: "Guatemalan Quetzal", names: ["guatemalan quetzal", "guatemalan quetzals"] }, + GYD: { label: "Guyanese Dollar", names: ["guyanese dollar", "guyanese dollars"] }, + HNL: { label: "Honduran Lempira", names: ["honduran lempira", "honduran lempiras"] }, + HTG: { label: "Haitian Gourde", names: ["haitian gourde", "haitian gourdes"] }, + IMP: { label: "Isle of Man Pound", names: ["isle of man pound", "isle of man pounds"] }, + IQD: { label: "Iraqi Dinar", names: ["iraqi dinar", "iraqi dinars"], decimals: 3 }, + IRR: { label: "Iranian Rial", names: ["iranian rial", "iranian rials"] }, + JEP: { label: "Jersey Pound", names: ["jersey pound", "jersey pounds"] }, + JMD: { label: "Jamaican Dollar", names: ["jamaican dollar", "jamaican dollars"] }, + JOD: { label: "Jordanian Dinar", names: ["jordanian dinar", "jordanian dinars"], decimals: 3 }, + KES: { label: "Kenyan Shilling", names: ["kenyan shilling", "kenyan shillings"] }, + KGS: { label: "Kyrgyzstani Som", names: ["kyrgyzstani som", "kyrgyzstani soms"] }, + KHR: { label: "Cambodian Riel", names: ["cambodian riel", "cambodian riels"] }, + KMF: { label: "Comorian Franc", names: ["comorian franc", "comorian francs"], decimals: 0 }, + KPW: { label: "North Korean Won", names: ["north korean won", "north korean wons"] }, + KWD: { label: "Kuwaiti Dinar", names: ["kuwaiti dinar", "kuwaiti dinars"], decimals: 3 }, + KYD: { label: "Cayman Islands Dollar", names: ["cayman islands dollar", "cayman islands dollars"] }, + KZT: { label: "Kazakhstani Tenge", names: ["kazakhstani tenge", "kazakhstani tenges"] }, + LAK: { label: "Lao Kip", names: ["lao kip", "lao kips"] }, + LBP: { label: "Lebanese Pound", names: ["lebanese pound", "lebanese pounds"] }, + LKR: { label: "Sri Lankan Rupee", names: ["sri lankan rupee", "sri lankan rupees"] }, + LRD: { label: "Liberian Dollar", names: ["liberian dollar", "liberian dollars"] }, + LSL: { label: "Lesotho Loti", names: ["lesotho loti", "lesotho lotis"] }, + LYD: { label: "Libyan Dinar", names: ["libyan dinar", "libyan dinars"], decimals: 3 }, + MAD: { label: "Moroccan Dirham", names: ["moroccan dirham", "moroccan dirhams"] }, + MDL: { label: "Moldovan Leu", names: ["moldovan leu", "moldovan leus"] }, + MGA: { label: "Malagasy Ariary", names: ["malagasy ariary", "malagasy ariarys"] }, + MKD: { label: "Macedonian Denar", names: ["macedonian denar", "macedonian denars"] }, + MMK: { label: "Myanmar Kyat", names: ["myanmar kyat", "myanmar kyats"] }, + MNT: { label: "Mongolian Tögrög", names: ["mongolian tögrög", "mongolian tögrögs", "mongolian togrog", "mongolian togrogs"] }, + MOP: { label: "Macanese Pataca", names: ["macanese pataca", "macanese patacas"] }, + MRU: { label: "Mauritanian Ouguiya", names: ["mauritanian ouguiya", "mauritanian ouguiyas"] }, + MUR: { label: "Mauritian Rupee", names: ["mauritian rupee", "mauritian rupees"] }, + MVR: { label: "Maldivian Rufiyaa", names: ["maldivian rufiyaa", "maldivian rufiyaas"] }, + MWK: { label: "Malawian Kwacha", names: ["malawian kwacha", "malawian kwachas"] }, + MZN: { label: "Mozambican Metical", names: ["mozambican metical", "mozambican meticals"] }, + NAD: { label: "Namibian Dollar", names: ["namibian dollar", "namibian dollars"] }, + NGN: { label: "Nigerian Naira", names: ["nigerian naira", "nigerian nairas"] }, + NIO: { label: "Nicaraguan Córdoba", names: ["nicaraguan córdoba", "nicaraguan córdobas", "nicaraguan cordoba", "nicaraguan cordobas"] }, + NPR: { label: "Nepalese Rupee", names: ["nepalese rupee", "nepalese rupees"] }, + OMR: { label: "Omani Rial", names: ["omani rial", "omani rials"], decimals: 3 }, + PAB: { label: "Panamanian Balboa", names: ["panamanian balboa", "panamanian balboas"] }, + PEN: { label: "Peruvian Sol", names: ["peruvian sol", "peruvian sols"] }, + PGK: { label: "Papua New Guinean Kina", names: ["papua new guinean kina", "papua new guinean kinas"] }, + PKR: { label: "Pakistani Rupee", names: ["pakistani rupee", "pakistani rupees"] }, + PYG: { label: "Paraguayan Guaraní", names: ["paraguayan guaraní", "paraguayan guaranís", "paraguayan guarani", "paraguayan guaranis"], decimals: 0 }, + QAR: { label: "Qatari Riyal", names: ["qatari riyal", "qatari riyals"] }, + RSD: { label: "Serbian Dinar", names: ["serbian dinar", "serbian dinars"] }, + RUB: { label: "Russian Ruble", names: ["russian ruble", "russian rubles"] }, + RWF: { label: "Rwandan Franc", names: ["rwandan franc", "rwandan francs"], decimals: 0 }, + SAR: { label: "Saudi Riyal", names: ["saudi riyal", "saudi riyals"] }, + SBD: { label: "Solomon Islands Dollar", names: ["solomon islands dollar", "solomon islands dollars"] }, + SCR: { label: "Seychellois Rupee", names: ["seychellois rupee", "seychellois rupees"] }, + SDG: { label: "Sudanese Pound", names: ["sudanese pound", "sudanese pounds"] }, + SHP: { label: "Saint Helenian Pound", names: ["saint helenian pound", "saint helenian pounds"] }, + SLE: { label: "New Leone", names: ["new leone", "new leones"] }, + SOS: { label: "Somali Shilling", names: ["somali shilling", "somali shillings"] }, + SRD: { label: "Surinamese Dollar", names: ["surinamese dollar", "surinamese dollars"] }, + SSP: { label: "South Sudanese Pound", names: ["south sudanese pound", "south sudanese pounds"] }, + STN: { label: "São Tomé and Príncipe Second Dobra", names: ["são tomé and príncipe second dobra", "são tomé and príncipe second dobras", "sao tome and principe second dobra", "sao tome and principe second dobras"] }, + SVC: { label: "Salvadoran Colón", names: ["salvadoran colón", "salvadoran colóns", "salvadoran colon", "salvadoran colons"] }, + SYP: { label: "Syrian Pound", names: ["syrian pound", "syrian pounds"] }, + SZL: { label: "Swazi Lilangeni", names: ["swazi lilangeni", "swazi lilangenis"] }, + TJS: { label: "Tajikistani Somoni", names: ["tajikistani somoni", "tajikistani somonis"] }, + TMT: { label: "Turkmenistani Manat", names: ["turkmenistani manat", "turkmenistani manats"] }, + TND: { label: "Tunisian Dinar", names: ["tunisian dinar", "tunisian dinars"], decimals: 3 }, + TOP: { label: "Tongan Paʻanga", names: ["tongan paʻanga", "tongan paʻangas", "tongan paanga", "tongan paangas"] }, + TTD: { label: "Trinidad and Tobago Dollar", names: ["trinidad and tobago dollar", "trinidad and tobago dollars"] }, + TWD: { label: "New Taiwan Dollar", names: ["new taiwan dollar", "new taiwan dollars"] }, + TZS: { label: "Tanzanian Shilling", names: ["tanzanian shilling", "tanzanian shillings"] }, + UAH: { label: "Ukrainian Hryvnia", names: ["ukrainian hryvnia", "ukrainian hryvnias"] }, + UGX: { label: "Ugandan Shilling", names: ["ugandan shilling", "ugandan shillings"], decimals: 0 }, + UYU: { label: "Uruguayan Peso", names: ["uruguayan peso", "uruguayan pesos"] }, + UZS: { label: "Uzbekistan Som", names: ["uzbekistan som", "uzbekistan soms"] }, + VES: { label: "Venezuelan Bolívar Soberano", names: ["venezuelan bolívar soberano", "venezuelan bolívar soberanos", "venezuelan bolivar soberano", "venezuelan bolivar soberanos"] }, + VND: { label: "Vietnamese Đồng", names: ["vietnamese đồng", "vietnamese đồngs", "vietnamese dong", "vietnamese dongs"], decimals: 0 }, + VUV: { label: "Vanuatu Vatu", names: ["vanuatu vatu", "vanuatu vatus"], decimals: 0 }, + WST: { label: "Samoan Tala", names: ["samoan tala", "samoan talas"] }, + XAF: { label: "Central African CFA Franc", names: ["central african cfa franc", "central african cfa francs"], decimals: 0 }, + XCD: { label: "East Caribbean Dollar", names: ["east caribbean dollar", "east caribbean dollars"] }, + XCG: { label: "Caribbean Guilder", names: ["caribbean guilder", "caribbean guilders"] }, + XDR: { label: "Special Drawing Rights", names: ["special drawing rights"] }, + XOF: { label: "West African CFA Franc", names: ["west african cfa franc", "west african cfa francs"], decimals: 0 }, + XPF: { label: "CFP Franc", names: ["cfp franc", "cfp francs"], decimals: 0 }, + YER: { label: "Yemeni Rial", names: ["yemeni rial", "yemeni rials"] }, + ZMW: { label: "Zambian Kwacha", names: ["zambian kwacha", "zambian kwachas"] }, + ZWG: { label: "Zimbabwe Gold", names: ["zimbabwe gold", "zimbabwe golds"] } +} +for (var _more in MORE_CURRENCIES) { + var _m = MORE_CURRENCIES[_more] + if (!CURRENCIES[_more]) CURRENCIES[_more] = { symbol: "", label: _m.label, names: _m.names, decimals: _m.decimals } +} var CURRENCY_SYMBOLS = { "$": "USD", "€": "EUR", "£": "GBP", "¥": "JPY", "₹": "INR", "₩": "KRW", "₺": "TRY", "₪": "ILS" } for (var _code in CURRENCIES) { var _c = CURRENCIES[_code] var _cu = def([_code], [], { C: 1 }, 0, { currency: _code }) _cu.name = _code; _cu.plural = _code - for (var _n = 0; _n < _c.names.length; _n++) UNIT_NAMES[_c.names[_n]] = _cu + for (var _n = 0; _n < _c.names.length; _n++) if (!_c.label || !UNIT_NAMES[_c.names[_n]]) UNIT_NAMES[_c.names[_n]] = _cu } // Words that read as units only right after a number ("5 in", "3 d"). @@ -1250,8 +1391,39 @@ function present(v, state) { return { display: group(n), copy: n, caption: numberWords(v.n) } } +// Exchange rates as env.rates wants them, or null. Takes frankfurter's v2 +// answer ([{date, base, quote, rate}], one row per currency, each with the +// date its central bank last published) and the cached {base, date, rates}. +// date is the newest one. Rows that aren't a 3-letter code with a positive +// finite rate are dropped. +function parseRates(doc) { + var base = "", date = "", pairs = [] + if (Array.isArray(doc)) { + for (var i = 0; i < doc.length; i++) { + var row = doc[i] + if (!row || typeof row.base !== "string" || typeof row.quote !== "string") continue + if (!base) base = row.base + if (row.base !== base) continue + pairs.push([row.quote, row.rate]) + if (typeof row.date === "string" && row.date > date) date = row.date + } + } else if (doc && typeof doc.base === "string" && doc.rates && typeof doc.rates === "object") { + base = doc.base + date = String(doc.date || "") + for (var code in doc.rates) pairs.push([code, doc.rates[code]]) + } + var rates = {}, count = 0 + for (var p = 0; p < pairs.length; p++) { + if (!/^[A-Z]{3}$/.test(pairs[p][0]) || typeof pairs[p][1] !== "number" || !isFinite(pairs[p][1]) || pairs[p][1] <= 0) continue + rates[pairs[p][0]] = pairs[p][1] + count++ + } + return /^[A-Z]{3}$/.test(base) && count ? { base: base, date: date, rates: rates } : null +} + function currencyName(code) { var c = CURRENCIES[code] + if (c.label) return c.label + " (" + code + ")" var name = c.names.filter(function(n) { return n.indexOf(" ") > 0 })[0] || c.names[0] return titleCase(name).replace(/^Us /, "US ") + " (" + code + ")" } @@ -1396,6 +1568,7 @@ function filterHistory(history, query) { if (typeof module !== "undefined") { module.exports = { evaluate: evaluate, + parseRates: parseRates, lex: lex, words: numberWords, zoneList: zoneList, diff --git a/core/Schema.js b/core/Schema.js index 4ffd1ed..7e6493f 100644 --- a/core/Schema.js +++ b/core/Schema.js @@ -95,7 +95,7 @@ var documents = { var configDefaults = { logLevel: "info", keepVisibleOnFocusLoss: false, - // Daily ECB reference rates from frankfurter.dev for currency conversion + // Daily central-bank reference rates from frankfurter.dev for currency conversion // (SPEC §8 Calculator). The only network request omacast makes. [D] currencyRates: true, // Calculator preferences named after Raycast's (ref 04 App. B) [O]. diff --git a/services/CalculatorData.qml b/services/CalculatorData.qml index f192d0a..a6832e8 100644 --- a/services/CalculatorData.qml +++ b/services/CalculatorData.qml @@ -2,8 +2,8 @@ import QtQuick import Quickshell.Io import "../core/Calculator.js" as Calculator -// Live inputs for core/Calculator.js: ECB exchange rates (SPEC §8: cached -// daily, frankfurter.dev) and the current UTC offset of every time zone the +// Live inputs for core/Calculator.js: central-bank exchange rates (SPEC §8: +// cached daily, frankfurter.dev) and the current UTC offset of every time zone the // calculator knows. QML's JS engine has no Intl, so one bash process asks // strftime for all of them (~40 ms). Item { @@ -22,8 +22,8 @@ Item { property bool cacheRead: false property var request: null - readonly property string ratesUrl: "https://api.frankfurter.dev/v1/latest" - readonly property double ratesMaxAgeMs: 12 * 3600 * 1000 // ECB publishes once a working day + readonly property string ratesUrl: "https://api.frankfurter.dev/v2/rates" + readonly property double ratesMaxAgeMs: 12 * 3600 * 1000 // central banks publish once a working day readonly property double retryAfterMs: 30 * 60 * 1000 readonly property double zonesMaxAgeMs: 10 * 60 * 1000 // catches DST switches @@ -39,10 +39,7 @@ Item { } function validRates(doc) { - if (!doc || typeof doc.base !== "string" || !doc.rates || typeof doc.rates !== "object") return null - var out = {} - for (var code in doc.rates) if (/^[A-Z]{3}$/.test(code) && typeof doc.rates[code] === "number" && doc.rates[code] > 0) out[code] = doc.rates[code] - return { base: doc.base, date: String(doc.date || ""), rates: out } + return Calculator.parseRates(doc) } function fetchRates() { diff --git a/site/README.md b/site/README.md index e851d30..4ae5f27 100644 --- a/site/README.md +++ b/site/README.md @@ -31,7 +31,7 @@ What it runs on: | File in `public/demo/` | What | In git | |---|---|---| | `core.js`, `emoji.json` | `core/*.js` bundled, and a copy of `data/emoji.json`. Written by `node build.mjs` | no | -| `snapshot.json` | Omarchy's menu, which rows are hidden or checked, and ECB exchange rates. Written by `node snapshot.mjs` | yes | +| `snapshot.json` | Omarchy's menu, which rows are hidden or checked, and exchange rates. Written by `node snapshot.mjs` | yes | | `emoji-keywords.json` | Omarchy's emoji search keywords. Written by `node snapshot.mjs` | yes | | `symbols.woff2` | the icon glyphs, subset from JetBrainsMono Nerd Font. Written by `node snapshot.mjs` (needs `uvx`) | yes | | `NOTICE.md`, `OFL.txt` | licences for the three above | yes | diff --git a/site/public/index.html b/site/public/index.html index 200a2ac..f8aa245 100644 --- a/site/public/index.html +++ b/site/public/index.html @@ -207,7 +207,7 @@

Just type the question.

  • Math: arithmetic, powers, roots, trig and more
  • Percentages: $30 + 20%, 20% off 50, 50 as a % of 200
  • Units: about 250 of them, mixed units like 5 ft 3 in, and CSS px / rem
  • -
  • Currencies: daily ECB rates, cached for the day
  • +
  • Currencies: ~160 of them at daily central-bank rates, cached for the day
  • Dates and time zones: 3 days from now, days until christmas, 3pm london to nyc
  • Number bases, work time and Unix time
  • diff --git a/site/snapshot.mjs b/site/snapshot.mjs index 77e296d..097eb64 100644 --- a/site/snapshot.mjs +++ b/site/snapshot.mjs @@ -3,7 +3,7 @@ // node site/snapshot.mjs // Writes, under site/public/demo/ (all committed): // snapshot.json Omarchy's menu (default/omarchy/omarchy-menu.jsonc), which rows are hidden or -// checked, and the day's ECB exchange rates +// checked, and the day's exchange rates // emoji-keywords.json Omarchy's emoji search keywords (shell/plugins/emojis/emojis.json) // symbols.woff2 the icon glyphs the launcher draws, subset from JetBrainsMono Nerd Font // (needs `uvx`, which fetches fonttools) diff --git a/tests/calculator.test.js b/tests/calculator.test.js index bde8917..f667454 100644 --- a/tests/calculator.test.js +++ b/tests/calculator.test.js @@ -82,6 +82,40 @@ test("currencies use the rates and need them only to convert", () => { assert.equal(result("$30 + 20%", Object.assign({}, env, { rates: null })), "$36.00") }) +test("currencies beyond the ECB set convert by code or full name", () => { + const more = Object.assign({}, env, { rates: { base: "EUR", date: "2026-10-19", rates: { USD: 2, AED: 4, DOP: 100, KWD: 0.5, VND: 30000 } } }) + assert.equal(result("100 aed to usd", more), "$50.00") + assert.equal(result("10 usd in aed", more), "20.00 AED") + assert.equal(result("10 usd to dominican pesos", more), "500.00 DOP") + assert.equal(result("1 eur to kwd", more), "0.500 KWD", "three decimals") + assert.equal(result("1 eur to vnd", more), "30,000 VND", "no decimals") + assert.equal(result("1 eur to vietnamese dong", more), "30,000 VND", "accents are optional") + assert.equal(C.evaluate("10 usd in aed", more).resultCaption, "United Arab Emirates Dirham (AED)") + assert.equal(C.evaluate("10 usd in xof", Object.assign({}, more, { rates: Object.assign({}, more.rates, { rates: { USD: 2, XOF: 600 } }) })).resultCaption, "West African CFA Franc (XOF)") + assert.equal(result("10 usd in aed", env), null, "a known code still needs its rate") + assert.equal(result("5 cup to ml", more), "1,182.9412 mL", "CUP the currency leaves the cup alone") + assert.equal(result("2 ton to kg", more), "1,814.3695 kg") + assert.ok(Object.keys(C.CURRENCIES).length > 150) +}) + +test("exchange rates parse from the v2 answer and from the cache", () => { + const v2 = [ + { date: "2026-11-19", base: "EUR", quote: "USD", rate: 1.1 }, + { date: "2026-11-18", base: "EUR", quote: "AED", rate: 4.03 }, + { date: "2026-11-19", base: "EUR", quote: "USDT", rate: 1.1 }, + { date: "2026-11-19", base: "EUR", quote: "BAD", rate: 0 }, + { date: "2026-11-19", base: "EUR", quote: "NAN", rate: "1" }, + { date: "2026-11-19", base: "USD", quote: "GBP", rate: 0.8 }, + null + ] + assert.deepEqual(C.parseRates(v2), { base: "EUR", date: "2026-11-19", rates: { USD: 1.1, AED: 4.03 } }) + assert.deepEqual(C.parseRates({ fetchedAt: 1, base: "EUR", date: "2026-10-19", rates: { USD: 1.1, usd: 2, JPY: -1 } }), { base: "EUR", date: "2026-10-19", rates: { USD: 1.1 } }) + assert.equal(C.parseRates([]), null) + assert.equal(C.parseRates({ base: "EUR", rates: {} }), null) + assert.equal(C.parseRates(null), null) + assert.equal(C.parseRates("nope"), null) +}) + test("dates and durations", () => { assert.equal(result("3 days from now"), "Thursday, 22 October 2026 at 4:06 PM") assert.equal(result("2 weeks ago"), "Monday, 5 October 2026 at 4:06 PM")